mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
Sprites for helicopters, ground vehicles, stations and vessel types; history to live without an empty map; model parts in Cesium
Aircraft icons are one size; helicopters turn a three-frame rotor while airborne or moving; ADS-B ground vehicles share one amber sprite and stations/obstacles one mast; vessels get hull sprites by type and one buoy. Going live keeps contacts until the first live answer and replaces them by id; fast playback holds before the loaded positions end and prefetches ahead. Cesium models move their parts from the optional model part state.
This commit is contained in:
1 parent
624c229bc2
commit
7186f720df
97 files changed
+6586
-343
No files matched your search
+35
-13
@@ -401,6 +401,11 @@ const OPENSKY_CATEGORY = {
|
||||
7: 'fastjet', // High performance (>5g, >400 kt)
|
||||
8: 'helicopter', // Rotorcraft
|
||||
9: 'glider',
|
||||
16: 'vehicle', // Surface vehicle, emergency
|
||||
17: 'vehicle', // Surface vehicle, service
|
||||
18: 'station', // Point obstacle
|
||||
19: 'station', // Cluster obstacle
|
||||
20: 'station', // Line obstacle
|
||||
};
|
||||
|
||||
/** ADS-B emitter-category string → class. */
|
||||
@@ -413,13 +418,35 @@ const EMITTER_CATEGORY = {
|
||||
A6: 'fastjet',
|
||||
A7: 'helicopter',
|
||||
B1: 'glider',
|
||||
C1: 'vehicle', // Surface vehicle, emergency
|
||||
C2: 'vehicle', // Surface vehicle, service
|
||||
C3: 'station', // Point obstacle
|
||||
C4: 'station', // Cluster obstacle
|
||||
C5: 'station', // Line obstacle
|
||||
};
|
||||
|
||||
/**
|
||||
* The type codes feeds give what is not an aircraft: an airport vehicle
|
||||
* (ZVEH) and a ground station (GRND).
|
||||
*/
|
||||
const GROUND_TYPE_CLASS = { ZVEH: 'vehicle', GRND: 'station' };
|
||||
|
||||
/**
|
||||
* The class an aircraft draws and reads as, from its ICAO type code (which
|
||||
* outranks the category), else its OpenSky integer or ADS-B emitter category.
|
||||
* Besides the aircraft classes, `vehicle` is an airport vehicle (type ZVEH,
|
||||
* emitter C1 or C2) and `station` a ground station or obstacle (type GRND,
|
||||
* emitter C3 to C5). A known type code outside every set is an airliner, and
|
||||
* so is a contact with nothing to go on.
|
||||
* @param {{typeCode?: string|null, category?: string|number|null}} [record]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function classifyAircraft({ typeCode, category } = {}) {
|
||||
const code = String(typeCode || '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (code) {
|
||||
if (GROUND_TYPE_CLASS[code]) return GROUND_TYPE_CLASS[code];
|
||||
if (FASTJET.has(code)) return 'fastjet';
|
||||
if (UAV.has(code)) return 'uav';
|
||||
if (HELI.has(code)) return 'helicopter';
|
||||
@@ -452,18 +479,13 @@ export const AIRCRAFT_CLASS_LABELS = Object.freeze({
|
||||
fastjet: msg('Fast jet'),
|
||||
bizjet: msg('Business jet'),
|
||||
uav: msg('Drone'),
|
||||
vehicle: msg('Airport vehicle'),
|
||||
station: msg('Ground station / obstacle'),
|
||||
});
|
||||
|
||||
/** Billboard scale multipliers (skylight GLYPH_SCALE, + fastjet). */
|
||||
export const CLASS_SCALE_2D = {
|
||||
light: 0.62,
|
||||
glider: 0.58,
|
||||
turboprop: 0.86,
|
||||
airliner: 1.0,
|
||||
widebody: 1.3,
|
||||
quadjet: 1.45,
|
||||
helicopter: 0.82,
|
||||
fastjet: 0.8,
|
||||
bizjet: 0.72,
|
||||
uav: 0.75,
|
||||
};
|
||||
/**
|
||||
* The tint an airport vehicle's sprite draws with in Flights and Local
|
||||
* ADS-B: an orange amber, apart from aircraft white and the military layer's
|
||||
* yellow amber (#FFB800).
|
||||
*/
|
||||
export const VEHICLE_TINT_CSS = '#FF8F1F';
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/data/aircraftClass.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyAircraft, CLASS_SCALE_2D } from './aircraftClass.js';
|
||||
import { AIRCRAFT_CLASS_LABELS, classifyAircraft } from './aircraftClass.js';
|
||||
|
||||
test('type-code classification (military layer path)', () => {
|
||||
assert.equal(classifyAircraft({ typeCode: 'F16' }), 'fastjet');
|
||||
@@ -48,8 +48,53 @@ test('typeCode outranks category; unknown → airliner', () => {
|
||||
assert.equal(classifyAircraft({ typeCode: null, category: 0 }), 'airliner');
|
||||
});
|
||||
|
||||
test('the icon scale table covers every class', () => {
|
||||
for (const kind of ['light','glider','turboprop','airliner','widebody','quadjet','helicopter','fastjet','bizjet','uav']) {
|
||||
assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind);
|
||||
test('every class has a label', () => {
|
||||
for (const kind of [
|
||||
'light',
|
||||
'glider',
|
||||
'turboprop',
|
||||
'airliner',
|
||||
'widebody',
|
||||
'quadjet',
|
||||
'helicopter',
|
||||
'fastjet',
|
||||
'bizjet',
|
||||
'uav',
|
||||
'vehicle',
|
||||
'station',
|
||||
]) {
|
||||
assert.ok(AIRCRAFT_CLASS_LABELS[kind], kind);
|
||||
}
|
||||
});
|
||||
|
||||
test('airport vehicles and ground stations class apart from aircraft', () => {
|
||||
// A feed's own types, in any case.
|
||||
assert.equal(classifyAircraft({ typeCode: 'ZVEH' }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ typeCode: ' zveh ' }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ typeCode: 'GRND' }), 'station');
|
||||
// Emitter categories: surface vehicles, then obstacles.
|
||||
assert.equal(classifyAircraft({ category: 'C1' }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ category: 'C2' }), 'vehicle');
|
||||
for (const category of ['C3', 'C4', 'C5'])
|
||||
assert.equal(classifyAircraft({ category }), 'station', category);
|
||||
// OpenSky's integer categories for the same.
|
||||
assert.equal(classifyAircraft({ category: 16 }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ category: 17 }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ category: 18 }), 'station');
|
||||
// A type code still outranks the category.
|
||||
assert.equal(
|
||||
classifyAircraft({ typeCode: 'ZVEH', category: 'A3' }),
|
||||
'vehicle',
|
||||
);
|
||||
assert.equal(
|
||||
classifyAircraft({ typeCode: 'A320', category: 'C1' }),
|
||||
'airliner',
|
||||
);
|
||||
});
|
||||
|
||||
test('helicopter types and categories', () => {
|
||||
for (const typeCode of ['EC35', 'R44', 'S76', 'H60', 'AS50', 'B407'])
|
||||
assert.equal(classifyAircraft({ typeCode }), 'helicopter', typeCode);
|
||||
assert.equal(classifyAircraft({ category: 'A7' }), 'helicopter');
|
||||
assert.equal(classifyAircraft({ category: 8 }), 'helicopter');
|
||||
});
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
TRACKED_ICON_PX,
|
||||
} from './aircraftIcons.js';
|
||||
import { cockpitContactDotImage } from './cockpitContactDot.js';
|
||||
import { rotorFrame, rotorTurns } from './rotorFrames.js';
|
||||
import { aircraftRecedeSpec } from './aircraftRecession.js';
|
||||
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
|
||||
|
||||
@@ -456,6 +457,14 @@ export function createAircraftIcons({
|
||||
const { focusPassIsNeeded } = services.focus;
|
||||
// The near-image switch the rows were last written with (CSS px).
|
||||
let switchPx = nearImageSwitchPx(1);
|
||||
/**
|
||||
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
|
||||
* frame each was last drawn at, and the frame it was last judged at
|
||||
* (`_turnRotors`), so one out of view is judged again only once its frame
|
||||
* has stepped on.
|
||||
* @type {Map<string, {drawn: number, checked: number}>}
|
||||
*/
|
||||
const rotors = new Map();
|
||||
|
||||
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
|
||||
const _displayMs = () =>
|
||||
@@ -473,6 +482,9 @@ export function createAircraftIcons({
|
||||
* back before it (`_replanExpired`).
|
||||
*/
|
||||
const planFrom = new Map();
|
||||
/** When each placed contact's running ease ends (epoch ms): a new answer
|
||||
* while it runs eases on from where it is drawn instead of cutting it. */
|
||||
const easeEnds = new Map();
|
||||
/** The display time the rows were last checked against. */
|
||||
let replannedAt = -Infinity;
|
||||
|
||||
@@ -543,7 +555,9 @@ export function createAircraftIcons({
|
||||
state._icons?.dispose();
|
||||
state._icons = null;
|
||||
liveSet = null;
|
||||
rotors.clear();
|
||||
planFrom.clear();
|
||||
easeEnds.clear();
|
||||
replannedAt = -Infinity;
|
||||
}
|
||||
|
||||
@@ -607,13 +621,19 @@ export function createAircraftIcons({
|
||||
* Following the clock, a contact not there yet at the time drawn
|
||||
* (`regime.unseen`) is not drawn until its warm-up begins.
|
||||
* @param {string} icao24
|
||||
* @param {{fromCourseDeg?: number|null, rewound?: boolean}} [options]
|
||||
* @param {{fromCourseDeg?: number|null, rewound?: boolean,
|
||||
* handover?: boolean}} [options]
|
||||
* `fromCourseDeg`: nose to glide from when the row's own motion is not
|
||||
* what was on screen (tracking handoff). `rewound`: the time drawn moved
|
||||
* back before the row's motion; it is drawn where it was then, with no
|
||||
* easing from where it is drawn now.
|
||||
* easing from where it is drawn now. `handover`: the clock came back to
|
||||
* live and this is the contact's first live fix: it eases from where it
|
||||
* is drawn onto its live path, however its last plan ran out.
|
||||
*/
|
||||
function _planIcon(icao24, { fromCourseDeg, rewound = false } = {}) {
|
||||
function _planIcon(
|
||||
icao24,
|
||||
{ fromCourseDeg, rewound = false, handover = false } = {},
|
||||
) {
|
||||
const icons = state._icons;
|
||||
if (!icons?.has(icao24) || holdsPlan(icao24)) return;
|
||||
const history = state._positionHistory.get(icao24);
|
||||
@@ -628,7 +648,7 @@ export function createAircraftIcons({
|
||||
|
||||
// A host-supplied placement decides where a live contact is drawn; with
|
||||
// none, or no answer for this contact, the layer's own motion below does.
|
||||
if (_planPlaced(icao24, info, history, t)) return;
|
||||
if (_planPlaced(icao24, info, history, t, handover)) return;
|
||||
|
||||
const regime = parts.motion._motionRegime(history, info, renderTime);
|
||||
if (regime.unseen) {
|
||||
@@ -745,7 +765,7 @@ export function createAircraftIcons({
|
||||
fromCourseDeg == null &&
|
||||
!rewound &&
|
||||
icons.shown(icao24) &&
|
||||
icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS
|
||||
(handover || icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS)
|
||||
) {
|
||||
const prev = icons.item(icao24);
|
||||
const drawn = motionPosition(prev.motion, prev.pos, t);
|
||||
@@ -804,13 +824,21 @@ export function createAircraftIcons({
|
||||
* @returns {boolean} False when there is no placement, the layer follows
|
||||
* the world clock, or it has no answer for this contact.
|
||||
*/
|
||||
function _planPlaced(icao24, info, history, t) {
|
||||
function _planPlaced(icao24, info, history, t, handover = false) {
|
||||
if (!placeAt || followsClock()) return false;
|
||||
const leadMs = displayDelay.currentMs;
|
||||
const from = vec();
|
||||
const start = placeAt(icao24, t + leadMs, info, history, from);
|
||||
if (!start) return false;
|
||||
const { courseDeg: course } = start;
|
||||
// Back at live, or while an ease runs, it eases on from where it is drawn.
|
||||
const easing = easeEnds.get(icao24) > t;
|
||||
if (
|
||||
(handover || easing) &&
|
||||
_easePlaced(icao24, info, history, t, from, start)
|
||||
)
|
||||
return true;
|
||||
easeEnds.delete(icao24);
|
||||
const t1 = t + PLACED_PLAN_MS;
|
||||
const to = vec();
|
||||
const end = placeAt(icao24, t1 + leadMs, info, history, to);
|
||||
@@ -835,6 +863,40 @@ export function createAircraftIcons({
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live, a placed contact still on screen eases from where it is
|
||||
* drawn onto where it is placed, as the layer's own motion recovers (and a
|
||||
* new answer while that ease runs eases on from where it is then): along
|
||||
* the straight line to where the placement has it when the ease ends, nose
|
||||
* along that line, unless it is nearer than a recovery or farther than a
|
||||
* jump would be.
|
||||
* @returns {boolean} Whether the contact was planned to ease.
|
||||
*/
|
||||
function _easePlaced(icao24, info, history, t, placed, start) {
|
||||
const icons = state._icons;
|
||||
if (!icons.shown(icao24)) return false;
|
||||
const prev = icons.item(icao24);
|
||||
const drawn = motionPosition(prev.motion, prev.pos, t);
|
||||
const errorM = distance(drawn, placed);
|
||||
if (!(errorM > RECOVER_MIN_M && errorM < RECOVER_SNAP_M)) return false;
|
||||
const speed = start.speedMps ?? info?.velocity ?? 0;
|
||||
const end = t + recoveryMs(errorM, speed);
|
||||
const target = vec();
|
||||
if (!placeAt(icao24, end + displayDelay.currentMs, info, history, target))
|
||||
return false;
|
||||
const motion = straightSegment(drawn, t, end, target);
|
||||
const course = motionCourse(motion, undefined, t);
|
||||
icons.setUnseen(icao24, false);
|
||||
icons.update(
|
||||
icao24,
|
||||
{ pos: clone(drawn), course, motion, courseGlide: undefined },
|
||||
{ expiresAt: end },
|
||||
);
|
||||
planFrom.set(icao24, t);
|
||||
easeEnds.set(icao24, end);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plan every row whose regime ended by `t` (epoch ms), and, following
|
||||
* the clock, every row whose motion starts after `t` once the time drawn
|
||||
@@ -906,26 +968,94 @@ export function createAircraftIcons({
|
||||
* @returns {{image: string, imageLod: {near: string, switchPx: number},
|
||||
* size: [number, number], scale: number, scaleByDistance: object}}
|
||||
*/
|
||||
function _fleetLook(icao24, info = state.records.data.get(icao24)) {
|
||||
function _fleetLook(
|
||||
icao24,
|
||||
info = state.records.data.get(icao24),
|
||||
frame = _rotorFrameOf(icao24, info, Date.now()),
|
||||
) {
|
||||
const rendering = parts.rendering;
|
||||
return {
|
||||
image: aircraftIcon(
|
||||
rendering._iconKind(icao24, info?.klass),
|
||||
FLEET_ICON_PX,
|
||||
frame,
|
||||
),
|
||||
imageLod: {
|
||||
near: aircraftIcon(
|
||||
rendering._iconKind(icao24, info?.klass),
|
||||
TRACKED_ICON_PX,
|
||||
frame,
|
||||
),
|
||||
switchPx,
|
||||
},
|
||||
size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX],
|
||||
scale: rendering._fleetBillboardScale(icao24, info?.klass),
|
||||
scale: rendering._fleetBillboardScale(icao24),
|
||||
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotor frame a contact draws at `nowMs` (`rotorFrames.js`): a
|
||||
* helicopter's, which holds still on the ground unless it taxis; undefined
|
||||
* for every other kind.
|
||||
*/
|
||||
function _rotorFrameOf(icao24, info, nowMs) {
|
||||
if (parts.rendering._iconKind(icao24, info?.klass) !== 'helicopter')
|
||||
return undefined;
|
||||
return rotorFrame(icao24, nowMs, _rotorState(info));
|
||||
}
|
||||
|
||||
/** What turns a contact's rotor: whether it is grounded, and its speed (m/s). */
|
||||
function _rotorState(info) {
|
||||
const speed = info?.velocity ?? info?.speedMps;
|
||||
return {
|
||||
onGround: info?.onGround === true,
|
||||
speedMps: Number.isFinite(speed) ? speed : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the rotors of the airborne helicopters in view: each one's images
|
||||
* are written again only when its rotor frame changed (`ROTOR_FPS`, run
|
||||
* from the fleet pass). One out of view, below the horizon, or hidden for
|
||||
* its 3D model keeps its frame. The tracked one is drawn by the tracked
|
||||
* icon, which is given its new images. With no airborne helicopter drawn
|
||||
* this does nothing.
|
||||
* @param {number} nowMs Epoch ms the frame is chosen at.
|
||||
* @param {number} t The display instant, epoch ms (where icons are drawn).
|
||||
* @param {((position: {x: number, y: number, z: number}) => boolean)|null}
|
||||
* [inView] Whether a position is in the camera's view; none: all are.
|
||||
*/
|
||||
function _turnRotors(nowMs, t, inView = null) {
|
||||
const icons = state._icons;
|
||||
if (!rotors.size || !icons) return;
|
||||
let occluder;
|
||||
for (const [id, rotor] of rotors) {
|
||||
const frame = rotorFrame(id, nowMs);
|
||||
// Drawn at this frame, or already judged at it: nothing to do.
|
||||
if (frame === rotor.drawn || frame === rotor.checked) continue;
|
||||
rotor.checked = frame;
|
||||
const tracked = id === state._trackedIcao;
|
||||
if (!icons.has(id) || (!tracked && !icons.shown(id))) continue;
|
||||
const position = icons.position(id, t);
|
||||
if (!position) continue;
|
||||
if (occluder === undefined) occluder = _occluder();
|
||||
if (!_aboveHorizon(position, occluder)) continue;
|
||||
if (inView && !inView(position)) continue;
|
||||
rotor.drawn = frame;
|
||||
if (tracked) {
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
continue;
|
||||
}
|
||||
const { image, imageLod } = _fleetLook(
|
||||
id,
|
||||
state.records.data.get(id),
|
||||
frame,
|
||||
);
|
||||
icons.update(id, { image, imageLod });
|
||||
}
|
||||
}
|
||||
|
||||
/** Image, size, scale, tint and freshness for one row under the current
|
||||
* normal/cockpit contract. Motion and course stay with `_planIcon`. */
|
||||
function _applyIconPresentation(icao24) {
|
||||
@@ -953,8 +1083,27 @@ export function createAircraftIcons({
|
||||
color: rgba(rendering._fleetBillboardColor(icao24, info)),
|
||||
rotationMode: 'course',
|
||||
};
|
||||
// A ground station's mast stands upright.
|
||||
if (!cockpitDot && info?.klass === 'station') {
|
||||
look.rotationMode = 'screen';
|
||||
look.rotation = 0;
|
||||
}
|
||||
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
|
||||
icons.update(icao24, look);
|
||||
// An airborne helicopter drawn as its glyph turns its rotor.
|
||||
const frame = cockpitDot
|
||||
? undefined
|
||||
: _rotorFrameOf(icao24, info, Date.now());
|
||||
if (frame === undefined || !rotorTurns(_rotorState(info))) {
|
||||
// A tracked helicopter that lands shows the still frame at once.
|
||||
if (rotors.delete(icao24) && tracked)
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
} else rotors.set(icao24, { drawn: frame, checked: frame });
|
||||
}
|
||||
|
||||
/** Whether any airborne helicopter's rotor turns (`_turnRotors` has work). */
|
||||
function _rotorsTurning() {
|
||||
return rotors.size > 0;
|
||||
}
|
||||
|
||||
/** Add a row for a new contact, hidden while it is the tracked one. */
|
||||
@@ -990,7 +1139,9 @@ export function createAircraftIcons({
|
||||
/** Drop a contact and everything the layer keeps for it. */
|
||||
function _forgetContact(icao24) {
|
||||
state._icons?.remove(icao24);
|
||||
rotors.delete(icao24);
|
||||
planFrom.delete(icao24);
|
||||
easeEnds.delete(icao24);
|
||||
parts.rendering._releaseModel(icao24);
|
||||
state.records.forget(icao24);
|
||||
// The host-supplied placement, if any, forgets it as well.
|
||||
@@ -1025,6 +1176,8 @@ export function createAircraftIcons({
|
||||
_focusIcons,
|
||||
_applyIconPresentation,
|
||||
_fleetLook,
|
||||
_turnRotors,
|
||||
_rotorsTurning,
|
||||
_addIcon,
|
||||
_forgetContact,
|
||||
_iconIds,
|
||||
|
||||
@@ -6,10 +6,12 @@ import {
|
||||
createContactIcons,
|
||||
floorCoastArc,
|
||||
} from './aircraftIconLayer.js';
|
||||
import { COAST_FLOOR_LIFT_M } from './motionModel.js';
|
||||
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
|
||||
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { createDisplayDelay } from './displayDelay.js';
|
||||
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
|
||||
import { ROTOR_STILL_FRAME } from './rotorFrames.js';
|
||||
|
||||
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
|
||||
|
||||
@@ -199,3 +201,283 @@ test('a coast over known ground that never rises is planned once', () => {
|
||||
'held on the ground where the coast stopped',
|
||||
);
|
||||
});
|
||||
|
||||
test('only airborne helicopters in view turn their rotor, written when the frame steps', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const here = fromDegrees(0, 30, 300);
|
||||
const away = fromDegrees(90, 30, 300);
|
||||
const records = new Map([
|
||||
['h1', { klass: 'helicopter', onGround: false }],
|
||||
['h2', { klass: 'helicopter', onGround: true }],
|
||||
['p1', { klass: 'airliner', onGround: false }],
|
||||
['h3', { klass: 'helicopter', onGround: false }],
|
||||
]);
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(),
|
||||
_cockpitNearContacts: new Set(),
|
||||
records: { data: records, missingPolls: new Map() },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
rendering: {
|
||||
_iconKind: (_id, klass) => klass,
|
||||
_fleetBillboardColor: () => [1, 1, 1, 1],
|
||||
_fleetBillboardScale: () => 1,
|
||||
},
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
});
|
||||
for (const id of records.keys()) {
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: id === 'h3' ? away : here,
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: Infinity },
|
||||
);
|
||||
icons._applyIconPresentation(id);
|
||||
}
|
||||
const image = (id) => state._icons.item(id).image;
|
||||
// The grounded helicopter holds the still frame.
|
||||
assert.equal(
|
||||
image('h2'),
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
const h3Before = image('h3');
|
||||
const writes = new Map();
|
||||
const update = state._icons.update;
|
||||
state._icons.update = (id, patch, options) => {
|
||||
writes.set(id, (writes.get(id) ?? 0) + 1);
|
||||
return update(id, patch, options);
|
||||
};
|
||||
// The fleet pass, every 80 ms for a second; h3 is out of view.
|
||||
const inView = (p) => Math.abs(p.x - here.x) < 1;
|
||||
const seen = new Set();
|
||||
for (let step = 0; step <= 12; step++) {
|
||||
if (step) t.mock.timers.tick(80);
|
||||
icons._turnRotors(Date.now(), Date.now(), inView);
|
||||
seen.add(image('h1'));
|
||||
}
|
||||
// Through every frame, written only on the steps its frame changed.
|
||||
assert.equal(seen.size, 3);
|
||||
for (const frame of [0, 1, 2])
|
||||
assert.ok(seen.has(aircraftIcon('helicopter', FLEET_ICON_PX, frame)));
|
||||
assert.ok(
|
||||
writes.get('h1') >= 8 && writes.get('h1') <= 11,
|
||||
`${writes.get('h1')} writes`,
|
||||
);
|
||||
assert.equal(writes.get('h2') ?? 0, 0, 'grounded: frozen');
|
||||
assert.equal(writes.get('p1') ?? 0, 0, 'not a helicopter');
|
||||
assert.equal(writes.get('h3') ?? 0, 0, 'out of view');
|
||||
assert.equal(image('h3'), h3Before);
|
||||
// Landing freezes it on the still frame.
|
||||
records.get('h1').onGround = true;
|
||||
icons._applyIconPresentation('h1');
|
||||
const landed = writes.get('h1');
|
||||
t.mock.timers.tick(400);
|
||||
icons._turnRotors(Date.now(), Date.now(), inView);
|
||||
assert.equal(writes.get('h1'), landed);
|
||||
assert.equal(
|
||||
image('h1'),
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
});
|
||||
|
||||
/** An icon layer over helicopters `ids`, all at `here`, for the rotor tests. */
|
||||
function rotorFixture(records, positions, tracking = {}) {
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(),
|
||||
_cockpitNearContacts: new Set(),
|
||||
records: { data: records, missingPolls: new Map() },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
rendering: {
|
||||
_iconKind: (_id, klass) => klass,
|
||||
_fleetBillboardColor: () => [1, 1, 1, 1],
|
||||
_fleetBillboardScale: () => 1,
|
||||
},
|
||||
tracking,
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
});
|
||||
for (const id of records.keys()) {
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: positions[id],
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: Infinity },
|
||||
);
|
||||
icons._applyIconPresentation(id);
|
||||
}
|
||||
return { state, icons };
|
||||
}
|
||||
|
||||
test('a tracked helicopter that lands shows the still frame at once', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
|
||||
let synced = 0;
|
||||
const { state, icons } = rotorFixture(
|
||||
records,
|
||||
{ h1: fromDegrees(0, 30, 300) },
|
||||
{ _syncTrackedBillboardImage: () => synced++ },
|
||||
);
|
||||
state._trackedIcao = 'h1';
|
||||
assert.equal(icons._rotorsTurning(), true);
|
||||
records.get('h1').onGround = true;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(synced, 1, 'the tracked billboard is given its images again');
|
||||
assert.equal(icons._rotorsTurning(), false);
|
||||
assert.equal(
|
||||
icons._fleetLook('h1').image,
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
// Taxiing faster than 1 m/s, its rotor turns again, as the model's does.
|
||||
records.get('h1').velocity = 5;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(icons._rotorsTurning(), true);
|
||||
records.get('h1').velocity = 0;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(synced, 2);
|
||||
assert.equal(icons._rotorsTurning(), false);
|
||||
// An untracked one landing does not touch the tracked billboard.
|
||||
records.get('h1').onGround = false;
|
||||
icons._applyIconPresentation('h1');
|
||||
state._trackedIcao = null;
|
||||
records.get('h1').onGround = true;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(synced, 2);
|
||||
});
|
||||
|
||||
test('a helicopter out of view is judged once per rotor frame, not every pass', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const records = new Map();
|
||||
const positions = {};
|
||||
for (let i = 0; i < 300; i++) {
|
||||
const id = `h${i}`;
|
||||
records.set(id, { klass: 'helicopter', onGround: false });
|
||||
positions[id] = fromDegrees(90, 30, 300);
|
||||
}
|
||||
const { state, icons } = rotorFixture(records, positions);
|
||||
let judged = 0;
|
||||
const inView = () => {
|
||||
judged++;
|
||||
return false;
|
||||
};
|
||||
const writes = [];
|
||||
const update = state._icons.update;
|
||||
state._icons.update = (id, ...rest) => {
|
||||
writes.push(id);
|
||||
return update(id, ...rest);
|
||||
};
|
||||
// Passes 10 ms apart for 2 s: 200 passes over 300 helicopters, all out of
|
||||
// view. Each is judged at most once per frame step (20 steps), and not on
|
||||
// a step back onto the frame it is drawn at.
|
||||
for (let pass = 0; pass < 200; pass++) {
|
||||
t.mock.timers.tick(10);
|
||||
icons._turnRotors(Date.now(), Date.now(), inView);
|
||||
}
|
||||
assert.ok(judged <= 300 * 21, `${judged} judgements`);
|
||||
assert.ok(judged >= 300 * 10, `${judged} judgements`);
|
||||
assert.equal(writes.length, 0, 'none in view: no image written');
|
||||
});
|
||||
|
||||
test('back at live, a placed contact eases from where it is drawn over a recovery, nose along the way', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const drawnAt = fromDegrees(0, 30, 3_000);
|
||||
const SPEED = 200;
|
||||
// The placement has it 2 km east of where it is drawn, flying east.
|
||||
const placedAt = (wallMs) => {
|
||||
const east = 2_000 + (SPEED * (wallMs - WORLD_MS)) / 1000;
|
||||
return fromDegrees(east / (111_320 * Math.cos(Math.PI / 6)), 30, 3_000);
|
||||
};
|
||||
const plan = (handover, keep = {}) => {
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map([['c', [{ epochMs: WORLD_MS }]]]),
|
||||
records: { data: new Map([['c', {}]]) },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
placeAt: (_id, wallMs, _info, _history, out) => {
|
||||
Object.assign(out, placedAt(wallMs));
|
||||
return { courseDeg: 90, speedMps: SPEED };
|
||||
},
|
||||
});
|
||||
state._icons.put(
|
||||
{
|
||||
id: 'c',
|
||||
pos: drawnAt,
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
course: 0,
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: -Infinity },
|
||||
);
|
||||
icons._planIcon('c', handover ? { handover: true } : undefined);
|
||||
keep.icons = icons;
|
||||
return state._icons;
|
||||
};
|
||||
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
|
||||
const eased = plan(true);
|
||||
const end = eased.expires('c');
|
||||
assert.equal(end, WORLD_MS + recoveryMs(2_000, SPEED));
|
||||
assert.ok(end - WORLD_MS > 1_000, 'longer than a placed plan');
|
||||
assert.ok(metres(eased.position('c', WORLD_MS, {}), drawnAt) < 1);
|
||||
assert.ok(metres(eased.position('c', end, {}), placedAt(end)) < 1);
|
||||
// The nose points along the way from where it is drawn to where it goes.
|
||||
assert.ok(Math.abs(eased.course('c', WORLD_MS) - 90) < 1);
|
||||
|
||||
const plain = plan(false);
|
||||
assert.ok(
|
||||
metres(plain.position('c', WORLD_MS, {}), placedAt(WORLD_MS)) < 1,
|
||||
'without the handover it is drawn where it is placed',
|
||||
);
|
||||
|
||||
// The next answer comes 15 s in, the ease still running: it eases on from
|
||||
// where it is drawn then, not cut to where it is placed.
|
||||
const keep = {};
|
||||
const easing = plan(true, keep);
|
||||
const firstEnd = easing.expires('c');
|
||||
assert.ok(firstEnd - WORLD_MS > 15_000, 'an ease longer than a poll');
|
||||
t.mock.timers.tick(15_000);
|
||||
const at = Date.now();
|
||||
const drawnThen = easing.position('c', at, {});
|
||||
keep.icons._planIcon('c');
|
||||
assert.ok(metres(easing.position('c', at, {}), drawnThen) < 1);
|
||||
const reEnd = easing.expires('c');
|
||||
assert.ok(reEnd > at + 1_000, 'eases on');
|
||||
assert.ok(metres(easing.position('c', reEnd, {}), placedAt(reEnd)) < 1);
|
||||
// Once it has caught up, the next answer draws it where it is placed.
|
||||
t.mock.timers.tick(reEnd - at + 1);
|
||||
keep.icons._planIcon('c');
|
||||
assert.ok(
|
||||
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
|
||||
);
|
||||
});
|
||||
+115
-28
@@ -8,9 +8,9 @@
|
||||
* width/height 20 (24 tracked) in flights.js / militaryFlights.js, so Cesium
|
||||
* DOWN-samples this larger, higher-precision source to the same on-screen
|
||||
* footprint — crisp anti-aliased edges instead of an upscaled 32px bitmap. The
|
||||
* on-screen size is unchanged and CLASS_SCALE_2D is untouched (no scale
|
||||
* compensation needed: the billboard's explicit width/height, not the SVG's,
|
||||
* sets the pixel size — the intrinsic SVG size only controls raster fidelity).
|
||||
* on-screen size is unchanged (the billboard's explicit width/height, not the
|
||||
* SVG's, sets the pixel size — the intrinsic SVG size only controls raster
|
||||
* fidelity).
|
||||
*
|
||||
* All glyphs are nose-up (nose toward -Y at rotation 0; the screen-projected
|
||||
* rotation pipeline in iconOrientation.js spins the whole glyph). Fill is white
|
||||
@@ -23,12 +23,19 @@
|
||||
* quadjet/glider use the "bold" chart-symbol redraw; light/fastjet keep the
|
||||
* original drawings. Raster fidelity doubled (192px source, same 96 coords).
|
||||
*
|
||||
* The helicopter is a top-down body under a four-blade rotor drawn in three
|
||||
* frames (`aircraftIcon('helicopter', px, frame)`, turned by
|
||||
* `rotorFrames.js`). Two kinds are not aircraft: `vehicle`, one sprite for
|
||||
* every airport vehicle, and `station`, a mast for ground stations, drawn
|
||||
* upright.
|
||||
*
|
||||
* Silhouette language follows skylight's type-aware glyphs (MIT,
|
||||
* https://github.com/cpaczek/skylight): slender fuselages, swept wings for
|
||||
* jets, long high-aspect wings for the glider, straight wings + prop discs for
|
||||
* props, a rotor disc + tail boom + tail-rotor for the helicopter, and a delta
|
||||
* for the fast jet. Each class has a DISTINCT planform so it reads at ~20px by
|
||||
* shape, not just by footprint size.
|
||||
* shape alone: every glyph is fitted to the same extent, so none is bigger
|
||||
* than another.
|
||||
*/
|
||||
|
||||
const VIEW = 96;
|
||||
@@ -130,23 +137,6 @@ const BODIES = {
|
||||
L -3,-25 C -3,-29 -2.4,-33 0,-35 Z" fill="white" ${STROKE_BOLD}/>
|
||||
<rect x="-10.5" y="32.5" width="21" height="5" rx="1.5" fill="white" ${STROKE_BOLD}/>`,
|
||||
|
||||
// ── Helicopter: a SOLID translucent main-rotor disc (survives downscale as an
|
||||
// obvious circle, unlike a thin ring) with a bold two-blade cross, a
|
||||
// teardrop cabin, a tail boom, and a tail rotor. Unmistakable "disc on top"
|
||||
// silhouette that never reads as a fixed-wing.
|
||||
helicopter: `
|
||||
<circle cx="0" cy="-6" r="31" fill="white" fill-opacity="0.22"/>
|
||||
<g transform="rotate(45 0 -6)">
|
||||
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9"/>
|
||||
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9" transform="rotate(90 0 -6)"/>
|
||||
</g>
|
||||
<path d="M0,-22 C 8,-20 10.5,-13 10.5,-6 C 10.5,2 7.5,7 0,8.5
|
||||
C -7.5,7 -10.5,2 -10.5,-6 C -10.5,-13 -8,-20 0,-22 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-2.6,8 L 2.6,8 L 1.8,32 L -1.8,32 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-8,27 L 8,27 L 8,30.6 L -8,30.6 Z" fill="white"/>
|
||||
<circle cx="5.6" cy="35" r="6" fill="white" fill-opacity="0.6"/>
|
||||
<circle cx="5.6" cy="35" r="2.1" fill="white"/>`,
|
||||
|
||||
// ── Fast jet: sharp delta/cropped-delta with a pointed nose, LERX root
|
||||
// blend, and twin tail fins. Aggressive, all-wing.
|
||||
fastjet: `
|
||||
@@ -236,6 +226,87 @@ const BODIES = {
|
||||
L -1.6,30 L -13,36 L -13,32 L -2.1,24
|
||||
L -2.3,0 L -43,-2.5 L -43,-7 L -2.4,-12
|
||||
L -4.4,-30 C -4.6,-35 -3.6,-40 0,-40 Z" fill="white" ${STROKE}/>`,
|
||||
|
||||
// ── Airport vehicle (type ZVEH, emitter C1/C2): one service van seen from
|
||||
// above, front up, for every kind (fire truck, tug, car, de-icer). A
|
||||
// boxy body, a dark windscreen band and a roof light bar; the layer
|
||||
// tints it amber so it reads apart from aircraft.
|
||||
vehicle: `
|
||||
<path d="M-12,-39 L 12,-39 L 15,-36 L 15,38 L 13,40 L -13,40 L -15,38
|
||||
L -15,-36 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-18.5,-25 h4 v3 h-4 Z M14.5,-25 h4 v3 h-4 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-13,-32 L 13,-32 L 12,-21 L -12,-21 Z" fill="rgba(0,0,0,0.62)"/>
|
||||
<rect x="-10" y="-13" width="20" height="5" rx="1.5" fill="rgba(0,0,0,0.45)"/>`,
|
||||
|
||||
// ── Ground station or obstacle (type GRND, emitter C3–C5): a radio mast
|
||||
// with two pairs of signal arcs, drawn upright on screen, never turned.
|
||||
station: `
|
||||
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
|
||||
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
|
||||
fill="none" stroke="rgba(0,0,0,0.32)" stroke-width="5" stroke-linecap="round"/>
|
||||
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
|
||||
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
|
||||
fill="none" stroke="white" stroke-width="3.4" stroke-linecap="round"/>
|
||||
<circle cx="0" cy="-30" r="4.5" fill="white" ${STROKE}/>
|
||||
<path d="M-2.5,-25 L 2.5,-25 L 7,34 L 13,34 L 13,38 L -13,38 L -13,34
|
||||
L -7,34 Z" fill="white" ${STROKE}/>`,
|
||||
};
|
||||
|
||||
/**
|
||||
* The helicopter, seen from above: a cabin, tail boom and tail plane under a
|
||||
* four-blade main rotor. The rotor turns in {@link ROTOR_FRAMES} frames 30°
|
||||
* apart; four blades repeat every 90°, so the third frame steps back onto
|
||||
* the first and the loop is seamless. The middle frame (blades as an X) is
|
||||
* the still one.
|
||||
*/
|
||||
const HELI_ROTOR_CENTRE_Y = -11.2;
|
||||
const HELI_DISC = `<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="32.8" fill="white" fill-opacity="0.22"/>`;
|
||||
const HELI_BODY = `
|
||||
<path d="M0,-33.4 L -2.3,-32.1 L -4.2,-28 L -4.3,-30.6 L -6.2,-30.6
|
||||
L -6.2,0.2 L -4.3,0.2 L -4.2,-3.1 L -1.9,7.9 L -1.7,18.9
|
||||
L -7.4,19.2 L -7.8,24 L -2.9,24.4 L -3.2,35.6 L -1.2,36
|
||||
L 0,34.3 L 1.2,36 L 3.2,35.6 L 2.9,24.4 L 7.8,24 L 7.4,19.2
|
||||
L 1.7,18.9 L 1.9,7.9 L 4.2,-3.1 L 4.3,0.2 L 6.2,0.2 L 6.2,-30.6
|
||||
L 4.3,-30.6 L 4.2,-28 L 2.3,-32.1 Z" fill="white" ${STROKE}/>
|
||||
<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="3.2" fill="white" ${STROKE}/>`;
|
||||
/** Main-rotor blade angle of each frame, degrees clockwise. */
|
||||
const ROTOR_ANGLES_DEG = [15, 45, 75];
|
||||
/** How many rotor frames the helicopter turns through. */
|
||||
export const ROTOR_FRAMES = ROTOR_ANGLES_DEG.length;
|
||||
/** The frame a helicopter holds when its rotor does not turn. */
|
||||
export const ROTOR_STILL_FRAME = 1;
|
||||
|
||||
/** One rotor frame: the disc, two crossed blades at `angle`, the body over them. */
|
||||
function helicopterBody(frame) {
|
||||
const angle = ROTOR_ANGLES_DEG[frame] ?? ROTOR_ANGLES_DEG[ROTOR_STILL_FRAME];
|
||||
const blade = (deg) =>
|
||||
`<rect x="-32.2" y="${HELI_ROTOR_CENTRE_Y - 2.2}" width="64.4" height="4.4" rx="2.2" fill="white" fill-opacity="0.92" stroke="rgba(0,0,0,0.25)" stroke-width="0.8" transform="rotate(${deg} 0 ${HELI_ROTOR_CENTRE_Y})"/>`;
|
||||
return `${HELI_DISC}${blade(angle)}${blade(angle + 90)}${HELI_BODY}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every sprite draws at one size. The bodies were drawn at different spans
|
||||
* (a light aircraft's half-extent is 32.8 units, a quadjet's 47), so each is
|
||||
* scaled until its farthest painted edge, stroke included, sits
|
||||
* {@link GLYPH_HALF_EXTENT} units from the centre. Values are each body's
|
||||
* measured half-extent; aircraftIcons.test.mjs re-measures the rasters.
|
||||
*/
|
||||
const GLYPH_HALF_EXTENT = 44;
|
||||
const BODY_HALF_EXTENT = {
|
||||
airliner: 42.7,
|
||||
widebody: 45.7,
|
||||
quadjet: 47.0,
|
||||
turboprop: 40.7,
|
||||
light: 32.8,
|
||||
glider: 46.0,
|
||||
fastjet: 44.7,
|
||||
bizjet: 42.7,
|
||||
uav: 43.7,
|
||||
helicopter: 44.0,
|
||||
vehicle: 40.7,
|
||||
station: 47.1,
|
||||
tr3b: 40.8,
|
||||
tr3bHot: 42.3,
|
||||
};
|
||||
|
||||
const _iconCache = new Map();
|
||||
@@ -259,16 +330,32 @@ export const FLEET_ICON_PX = FLEET_RASTER_PX;
|
||||
* it stays crisp at its biggest on-screen sizes. */
|
||||
const TRACKED_RASTER_PX = 192;
|
||||
|
||||
/** Data URI for a class silhouette (lazily built, cached per kind+size).
|
||||
* Default size serves the fleet; pass `aircraftIcon(kind, TRACKED_ICON_PX)`
|
||||
* (re-exported below) for the tracked billboard. */
|
||||
/** Raster size of the tracked glyph and every glyph's near image. */
|
||||
export const TRACKED_ICON_PX = TRACKED_RASTER_PX;
|
||||
export function aircraftIcon(kind, px = FLEET_RASTER_PX) {
|
||||
const k = BODIES[kind] ? kind : 'airliner';
|
||||
const key = `${k}@${px}`;
|
||||
/**
|
||||
* Data URI for a class silhouette (lazily built, cached per kind, size and
|
||||
* frame). The default size serves the fleet; pass
|
||||
* `aircraftIcon(kind, TRACKED_ICON_PX)` for the near image.
|
||||
* @param {string} kind A `classifyAircraft()` class, or a TR-3B kind.
|
||||
* @param {number} [px] Raster size.
|
||||
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
|
||||
* (the still frame by default); other kinds have one image.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function aircraftIcon(kind, px = FLEET_RASTER_PX, frame) {
|
||||
const heli = kind === 'helicopter';
|
||||
const k = heli || BODIES[kind] ? kind : 'airliner';
|
||||
const f = heli
|
||||
? Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
|
||||
? frame
|
||||
: ROTOR_STILL_FRAME
|
||||
: 0;
|
||||
const key = `${k}@${px}#${f}`;
|
||||
let uri = _iconCache.get(key);
|
||||
if (!uri) {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C})">${BODIES[k]}</g></svg>`;
|
||||
const body = heli ? helicopterBody(f) : BODIES[k];
|
||||
const fit = +(GLYPH_HALF_EXTENT / BODY_HALF_EXTENT[k]).toFixed(4);
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C}) scale(${fit})">${body}</g></svg>`;
|
||||
uri = 'data:image/svg+xml;base64,' + _b64(svg);
|
||||
_iconCache.set(key, uri);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// src/data/aircraftIcons.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import sharp from 'sharp';
|
||||
|
||||
import { aircraftIcon, ROTOR_FRAMES } from './aircraftIcons.js';
|
||||
|
||||
const KINDS = [
|
||||
'airliner',
|
||||
'widebody',
|
||||
'quadjet',
|
||||
'turboprop',
|
||||
'light',
|
||||
'glider',
|
||||
'fastjet',
|
||||
'bizjet',
|
||||
'uav',
|
||||
'helicopter',
|
||||
'vehicle',
|
||||
'station',
|
||||
'tr3b',
|
||||
'tr3bHot',
|
||||
];
|
||||
const PX = 480;
|
||||
|
||||
/** Farthest painted pixel from the centre, in the 96-unit glyph space. */
|
||||
async function halfExtent(uri) {
|
||||
const svg = Buffer.from(uri.split(',')[1], 'base64');
|
||||
const { data, info } = await sharp(svg)
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
let half = 0;
|
||||
const c = info.width / 2;
|
||||
for (let y = 0; y < info.height; y++) {
|
||||
for (let x = 0; x < info.width; x++) {
|
||||
if (data[(y * info.width + x) * 4 + 3] <= 8) continue;
|
||||
half = Math.max(half, c - x, x + 1 - c, c - y, y + 1 - c);
|
||||
}
|
||||
}
|
||||
return (half * 96) / info.width;
|
||||
}
|
||||
|
||||
test('every sprite fills the same extent, whatever its class', async () => {
|
||||
const extents = {};
|
||||
for (const kind of KINDS) {
|
||||
extents[kind] = await halfExtent(aircraftIcon(kind, PX));
|
||||
}
|
||||
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
|
||||
extents[`helicopter#${frame}`] = await halfExtent(
|
||||
aircraftIcon('helicopter', PX, frame),
|
||||
);
|
||||
}
|
||||
for (const [kind, half] of Object.entries(extents)) {
|
||||
assert.ok(Math.abs(half - 44) <= 0.6, `${kind}: ${half.toFixed(2)}`);
|
||||
}
|
||||
});
|
||||
@@ -14,7 +14,8 @@ import {
|
||||
showModel,
|
||||
} from './modelRecord.js';
|
||||
import { modelDrawnScale } from './modelVisualAnchor.js';
|
||||
import { fleetModelSet } from './fleetModels.js';
|
||||
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
|
||||
import { aircraftLayerPartState } from './modelPartDrivers.js';
|
||||
import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import {
|
||||
@@ -341,6 +342,54 @@ export function createAircraftModels({
|
||||
record.tint = [base[0], base[1], base[2], alpha];
|
||||
}
|
||||
|
||||
/** A finite number of the first of `values` that is one, else null. */
|
||||
const _finite = (...values) =>
|
||||
values.find((v) => typeof v === 'number' && Number.isFinite(v)) ?? null;
|
||||
|
||||
/**
|
||||
* How high an aircraft flies above the ground under it: its render
|
||||
* altitude over the cached ground floor there; null where that floor is
|
||||
* not known (the gear then follows the approach rule instead).
|
||||
*/
|
||||
function _heightAboveGround(meta) {
|
||||
const altitude = _finite(meta.renderAltitudeM);
|
||||
const floor =
|
||||
Number.isFinite(meta.rawLat) && Number.isFinite(meta.rawLon)
|
||||
? services.groundFloor?.cachedGroundFloor?.(meta.rawLat, meta.rawLon)
|
||||
: null;
|
||||
return altitude !== null && Number.isFinite(floor)
|
||||
? altitude - floor
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The moving parts a contact's model is posed with, from its record
|
||||
* (`aircraftLayerPartState`): gear, doors and flaps by its height and climb,
|
||||
* fans, propellers and rotors while it flies or taxis. An airport vehicle
|
||||
* is a road vehicle (`groundVehiclePartState`): its wheels roll with its
|
||||
* speed. Undefined for a model without parts.
|
||||
*/
|
||||
function _partsOf(meta, spec) {
|
||||
if (!meta) return undefined;
|
||||
const table = fleetPartTable(fleetModelSet(), spec?.model);
|
||||
if (!table) return undefined;
|
||||
return aircraftLayerPartState(table, {
|
||||
klass: meta.klass,
|
||||
onGround: meta.onGround === true,
|
||||
heightAboveGroundM: _heightAboveGround(meta),
|
||||
altitudeM: _finite(meta.altitude, meta.altitudeM),
|
||||
verticalRateMps: _finite(meta.verticalRate, meta.verticalRateMps),
|
||||
speedMps: _finite(meta.velocity, meta.speedMps),
|
||||
});
|
||||
}
|
||||
|
||||
/** Pose a record's parts as its contact's record says, and key them for `_send`. */
|
||||
function _poseParts(record, meta, spec) {
|
||||
const pose = _partsOf(meta, spec);
|
||||
record.parts = pose;
|
||||
record.partsKey = pose ? JSON.stringify(pose) : '';
|
||||
}
|
||||
|
||||
/** The record's item, as its set draws it. */
|
||||
function _itemOf(id, record) {
|
||||
return {
|
||||
@@ -358,6 +407,7 @@ export function createAircraftModels({
|
||||
// the IR boost draws it flat white.
|
||||
colorBlend: aircraftModelBlend(state._irBoost === true),
|
||||
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
|
||||
...(record.parts ? { parts: record.parts } : {}),
|
||||
show: record.show,
|
||||
};
|
||||
}
|
||||
@@ -367,7 +417,7 @@ export function createAircraftModels({
|
||||
if (!set) return;
|
||||
const p = record.position;
|
||||
const t = record.tint ?? WHITE;
|
||||
const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}`;
|
||||
const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}|${record.partsKey ?? ''}`;
|
||||
if (key === record.sent) return;
|
||||
record.sent = key;
|
||||
const item = _itemOf(id, record);
|
||||
@@ -426,6 +476,7 @@ export function createAircraftModels({
|
||||
// Placed BEFORE the readiness test on purpose: a model can turn ready
|
||||
// between ticks, and its first drawn frame must be at this placement.
|
||||
placeModel(record, displayPos, _modelHeading(course, meta));
|
||||
_poseParts(record, meta, spec);
|
||||
if (!record.ready) {
|
||||
showModel(record, false); // not loaded yet → keep the 2D icon, no half-model flash
|
||||
_send(set, icao24, record, spec, out);
|
||||
@@ -766,6 +817,7 @@ export function createAircraftModels({
|
||||
displayPos,
|
||||
_modelHeading(parts.motion._trackedDisplayCourse(), meta),
|
||||
);
|
||||
_poseParts(record, meta, spec);
|
||||
showModel(record, record.ready);
|
||||
_send(state._modelSets.tracked, icao24, record, spec);
|
||||
if (record.ready) _releaseTrackedFleetModel();
|
||||
@@ -841,6 +893,13 @@ export function createAircraftModels({
|
||||
afterReplan(renderTime, t, nowMs, pose?.position ?? null);
|
||||
const focusTarget = getFocusTarget();
|
||||
parts.icons._focusIcons(t, nowMs, focusTarget);
|
||||
// Airborne helicopters in view step their rotor frame (none: no work).
|
||||
if (parts.icons._rotorsTurning?.())
|
||||
parts.icons._turnRotors(
|
||||
Date.now(),
|
||||
t,
|
||||
pose ? (position) => inView(pose, position) : null,
|
||||
);
|
||||
|
||||
// 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling.
|
||||
// Drop all models the moment we leave it (toggled off / zoomed out) so icons resume.
|
||||
|
||||
@@ -97,7 +97,7 @@ for (const layer of LAYERS) {
|
||||
// `_iconKind` is identity for every unconverted contact (see
|
||||
// tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the
|
||||
// operator explicitly converted into a TR-3B.
|
||||
assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?\)/,
|
||||
assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?(?:frame,?\s*)?\)/,
|
||||
'near contacts and model fallbacks retain the class-derived aircraft silhouette');
|
||||
assert.match(source, /color: rgba\(rendering\._cockpitContactColor\(icao24, info\)\),\s*rotationMode: 'screen',/,
|
||||
'far dots are reset to a rotation-free presentation');
|
||||
|
||||
@@ -1285,6 +1285,8 @@ const AIRCRAFT_CLASS_NAMES = {
|
||||
turboprop: msg('Turboprops'),
|
||||
fastjet: msg('Fast jets'),
|
||||
quadjet: msg('Four-engine jets'),
|
||||
vehicle: msg('Airport vehicles'),
|
||||
station: msg('Ground stations / obstacles'),
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { selectModelEligible } from './modelEligibility.js';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
|
||||
import { fleetModelSet } from './fleetModels.js';
|
||||
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
|
||||
import { findCamera, findDraw } from '../render/rendererOf.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../geo/horizon.js';
|
||||
@@ -115,6 +115,10 @@ let instances = 0;
|
||||
* cap, capAll, addM, addAllM, keepM, keepAllM, intervalMs}`.
|
||||
* @param {(url: string) => string} [options.resolveAsset]
|
||||
* @param {boolean} [options.waterline] Clip each model at its waterline.
|
||||
* @param {(item: object, table: object) => object|undefined} [options.partState]
|
||||
* The moving parts a vehicle's model is posed with (`ModelItem.parts`),
|
||||
* from its item and its model's part table (`modelPartDrivers.js`); asked
|
||||
* only for a model that has a part table.
|
||||
* @param {object} [options.draw] Stands in for the viewer's draw port (tests).
|
||||
* @returns {object}
|
||||
*/
|
||||
@@ -124,6 +128,7 @@ export function createFleetModelLayer({
|
||||
policy,
|
||||
waterline = false,
|
||||
resolveAsset = (url) => url,
|
||||
partState = null,
|
||||
draw,
|
||||
}) {
|
||||
const port = draw ?? findDraw(viewer);
|
||||
@@ -230,8 +235,15 @@ export function createFleetModelLayer({
|
||||
return fromDegrees(at.lon, at.lat, at.height + lift);
|
||||
}
|
||||
|
||||
/** The part state an item's model is posed with, or undefined. */
|
||||
function partsOf(item) {
|
||||
if (!partState) return undefined;
|
||||
const table = fleetPartTable(fleetModelSet(), item.spec?.model);
|
||||
return table ? partState(item, table) : undefined;
|
||||
}
|
||||
|
||||
/** The draw item for an admitted model, as the set draws it, at `at`. */
|
||||
function itemOf(id, record, item, show, boost, at = placement(item)) {
|
||||
function itemOf(id, record, item, show, boost, at, parts) {
|
||||
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
|
||||
return {
|
||||
id,
|
||||
@@ -260,6 +272,7 @@ export function createFleetModelLayer({
|
||||
: { shading: 'pbr' }),
|
||||
...(mask ? { maskColor: mask } : {}),
|
||||
...(waterline ? { clip: 'belowOrigin' } : {}),
|
||||
...(parts ? { parts } : {}),
|
||||
meta: item.pickId ?? id,
|
||||
show,
|
||||
};
|
||||
@@ -276,6 +289,8 @@ export function createFleetModelLayer({
|
||||
const heading = item.headingDeg || 0;
|
||||
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
|
||||
const meta = item.pickId ?? id;
|
||||
const parts = partsOf(item);
|
||||
const partsKey = parts ? JSON.stringify(parts) : '';
|
||||
const sent = record.sent;
|
||||
if (
|
||||
sent !== null &&
|
||||
@@ -287,7 +302,8 @@ export function createFleetModelLayer({
|
||||
sameColor(sent.mask, mask) &&
|
||||
sent.boost === boost &&
|
||||
sent.show === show &&
|
||||
sent.meta === meta
|
||||
sent.meta === meta &&
|
||||
sent.partsKey === partsKey
|
||||
)
|
||||
return null;
|
||||
const next = (record.sent ??= {});
|
||||
@@ -301,7 +317,8 @@ export function createFleetModelLayer({
|
||||
next.boost = boost;
|
||||
next.show = show;
|
||||
next.meta = meta;
|
||||
return itemOf(id, record, item, show, boost, at);
|
||||
next.partsKey = partsKey;
|
||||
return itemOf(id, record, item, show, boost, at, parts);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
*/
|
||||
|
||||
import { classifyAircraft } from './aircraftClass.js';
|
||||
import { readPartTable } from '../render/modelParts.js';
|
||||
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
|
||||
import { isAidToNavigation } from './vesselTypes.js';
|
||||
|
||||
@@ -527,6 +528,34 @@ export function namedFleetModels(types) {
|
||||
]);
|
||||
}
|
||||
|
||||
/** Each loaded set's part tables by model name (null for a model without one). */
|
||||
const partTables = new WeakMap();
|
||||
|
||||
/**
|
||||
* The part table of model `name` in a loaded set, read once from its GLB:
|
||||
* which moving parts it has (`render/modelParts.js`); null for a model
|
||||
* without one, or whose GLB did not load.
|
||||
* @param {{bytes?: Map<string, Uint8Array>}|null|undefined} set
|
||||
* @param {string|null|undefined} name
|
||||
* @returns {import('../render/modelParts').PartTable|null}
|
||||
*/
|
||||
export function fleetPartTable(set, name) {
|
||||
const bytes = name ? set?.bytes?.get(name) : undefined;
|
||||
if (!bytes) return null;
|
||||
let tables = partTables.get(set);
|
||||
if (!tables) partTables.set(set, (tables = new Map()));
|
||||
if (!tables.has(name)) {
|
||||
let table = null;
|
||||
try {
|
||||
table = readPartTable(bytes);
|
||||
} catch {
|
||||
// A malformed table: the model draws whole.
|
||||
}
|
||||
tables.set(name, table);
|
||||
}
|
||||
return tables.get(name);
|
||||
}
|
||||
|
||||
let loading = null;
|
||||
let loaded = null;
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* @module modelPartDrivers
|
||||
* @description What the live layers ask of a fleet model's moving parts
|
||||
* (`ModelItem.parts`), from a vehicle's own record: each a pure function of
|
||||
* the model's part table and what the record says, so the same record poses
|
||||
* the same parts at any time. A model without a part table gets none, and a
|
||||
* renderer that does not pose parts draws the model whole, at rest.
|
||||
*
|
||||
* Which parts each rule drives is read from the table by kind and name:
|
||||
*
|
||||
* - **Aircraft and helicopters** ({@link aircraftPartState}). Spin parts
|
||||
* named `fan…`, `prop…` and `rotor…` turn while the aircraft is airborne,
|
||||
* or on the ground moving faster than {@link MOVING_MPS}. Hinge parts named
|
||||
* `gear…` are down on the ground; in the air they come down between
|
||||
* {@link GEAR_APPROACH_M} metres above the ground when descending faster
|
||||
* than {@link DESCENDING_MPS} (an approach), and otherwise are down below
|
||||
* {@link GEAR_TAKEOFF_M}`[0]` and up above `[1]` (after take-off), in
|
||||
* between in proportion. Without a height above the ground (no ground
|
||||
* height known under it), the gear is down while it descends faster than
|
||||
* {@link DESCENDING_MPS} slower than {@link APPROACH_MPS} below
|
||||
* {@link APPROACH_CEILING_M} (an approach: the highest runways are about
|
||||
* 4,400 m up), and up otherwise. Their doors (`door…`) open over the first
|
||||
* quarter of the gear's travel and stay open while it is out; flaps
|
||||
* (`flap…`) follow the gear in the air and are up on the ground.
|
||||
* - **Vessels** ({@link vesselPartState}): spin parts named `radar…` sweep
|
||||
* while the vessel is under way, faster than {@link UNDER_WAY_MPS}.
|
||||
* - **Road and rail vehicles** ({@link groundVehiclePartState}): spin parts
|
||||
* named `axle…` roll with the vehicle's speed (their pivot's height is the
|
||||
* wheel's radius), and slide parts named `doors…` are open while the
|
||||
* vehicle is stopped at a stop.
|
||||
*
|
||||
* Fractions and speeds are rounded ({@link DEPLOY_STEP}, {@link SPEED_STEP_MPS})
|
||||
* so a record that barely changes asks for the same state.
|
||||
*/
|
||||
|
||||
/** Ground speed (m/s) above which a grounded aircraft's engines turn. */
|
||||
export const MOVING_MPS = 1;
|
||||
/** Vertical rate (m/s, negative down) below which an aircraft is descending. */
|
||||
export const DESCENDING_MPS = -1;
|
||||
/** Heights above the ground (m) over which the gear comes down on approach: up at the first, down at the second. */
|
||||
export const GEAR_APPROACH_M = Object.freeze([750, 600]);
|
||||
/** Heights above the ground (m) over which the gear goes up otherwise: down at the first, up at the second. */
|
||||
export const GEAR_TAKEOFF_M = Object.freeze([100, 300]);
|
||||
/** Ground speed (m/s) under which a descending aircraft is on approach, where no ground height is known (about 165 kt). */
|
||||
export const APPROACH_MPS = 85;
|
||||
/** Altitude (m) under which a descending aircraft may be on approach, where no ground height is known. */
|
||||
export const APPROACH_CEILING_M = 5000;
|
||||
/** Speed (m/s) above which a vessel is under way. */
|
||||
export const UNDER_WAY_MPS = 0.5;
|
||||
/** Speed (m/s) under which a vehicle at a stop is stopped there. */
|
||||
export const STOPPED_MPS = 0.5;
|
||||
/** Deploy fractions are rounded to this step. */
|
||||
export const DEPLOY_STEP = 1 / 32;
|
||||
/** Speeds are rounded to this step (m/s) before they turn wheels. */
|
||||
export const SPEED_STEP_MPS = 0.5;
|
||||
|
||||
/** Degrees a second each spinning part turns at, by name. */
|
||||
export const SPIN_RATES_DPS = Object.freeze({
|
||||
rotor_tail: 3000,
|
||||
rotor: 1080,
|
||||
prop: 1500,
|
||||
fan: 900,
|
||||
radar: 144,
|
||||
});
|
||||
|
||||
/** A wheel's radius (m) where its axle's pivot does not say. */
|
||||
const DEFAULT_WHEEL_RADIUS_M = 0.4;
|
||||
|
||||
const RADIANS_TO_DEGREES = 180 / Math.PI;
|
||||
|
||||
/** `value` rounded to `step`. */
|
||||
const rounded = (value, step) => Math.round(value / step) * step;
|
||||
|
||||
/** 0..1 between `from` (0) and `to` (1), linear, clamped. */
|
||||
function ramp(value, from, to) {
|
||||
const t = (value - from) / (to - from);
|
||||
return Math.min(1, Math.max(0, t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an aircraft's engines and rotors turn: airborne, or on the ground
|
||||
* moving faster than {@link MOVING_MPS}. The rotor sprite (`rotorFrames.js`)
|
||||
* follows the same rule as the model's spinning parts.
|
||||
* @param {{onGround?: boolean, speedMps?: number|null}} aircraft
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function enginesTurn({ onGround, speedMps }) {
|
||||
return (
|
||||
!onGround ||
|
||||
(typeof speedMps === 'number' &&
|
||||
Number.isFinite(speedMps) &&
|
||||
speedMps > MOVING_MPS)
|
||||
);
|
||||
}
|
||||
|
||||
/** A spin part's rate by its name, or 0 for a name not listed. */
|
||||
function spinRate(name) {
|
||||
if (name === 'rotor_tail') return SPIN_RATES_DPS.rotor_tail;
|
||||
for (const prefix of ['rotor', 'prop', 'fan', 'radar'])
|
||||
if (name.startsWith(prefix)) return SPIN_RATES_DPS[prefix];
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Each part of `kind` whose name starts with one of `prefixes`. */
|
||||
function* partsOf(table, kind, prefixes) {
|
||||
for (const part of table?.parts ?? [])
|
||||
if (part.kind === kind && prefixes.some((p) => part.name.startsWith(p)))
|
||||
yield part;
|
||||
}
|
||||
|
||||
/** A state with only the members that name a part; undefined for none. */
|
||||
function stateOf(spin, deploy) {
|
||||
const out = {};
|
||||
if (Object.keys(spin).length) out.spin = spin;
|
||||
if (Object.keys(deploy).length) out.deploy = deploy;
|
||||
return out.spin || out.deploy ? out : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far an aircraft's gear is down, 0 (up) to 1 (down), by the rule in the
|
||||
* module comment.
|
||||
* @param {{onGround?: boolean, heightAboveGroundM?: number|null,
|
||||
* altitudeM?: number|null, verticalRateMps?: number|null,
|
||||
* speedMps?: number|null}} aircraft
|
||||
* @returns {number}
|
||||
*/
|
||||
export function gearDown({
|
||||
onGround,
|
||||
heightAboveGroundM,
|
||||
altitudeM,
|
||||
verticalRateMps,
|
||||
speedMps,
|
||||
}) {
|
||||
if (onGround) return 1;
|
||||
const known = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
const descending = known(verticalRateMps) && verticalRateMps < DESCENDING_MPS;
|
||||
const h = heightAboveGroundM;
|
||||
if (!known(h))
|
||||
return descending &&
|
||||
known(speedMps) &&
|
||||
speedMps < APPROACH_MPS &&
|
||||
(!known(altitudeM) || altitudeM < APPROACH_CEILING_M)
|
||||
? 1
|
||||
: 0;
|
||||
const down = descending
|
||||
? Math.max(
|
||||
ramp(h, GEAR_APPROACH_M[0], GEAR_APPROACH_M[1]),
|
||||
ramp(h, GEAR_TAKEOFF_M[1], GEAR_TAKEOFF_M[0]),
|
||||
)
|
||||
: ramp(h, GEAR_TAKEOFF_M[1], GEAR_TAKEOFF_M[0]);
|
||||
return rounded(down, DEPLOY_STEP);
|
||||
}
|
||||
|
||||
/**
|
||||
* An aircraft's or helicopter's part state, by the rule in the module
|
||||
* comment; undefined when its model has no part the rule drives.
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{onGround?: boolean, heightAboveGroundM?: number|null,
|
||||
* altitudeM?: number|null, verticalRateMps?: number|null,
|
||||
* speedMps?: number|null}} aircraft
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function aircraftPartState(table, aircraft) {
|
||||
if (!table) return undefined;
|
||||
const spin = {};
|
||||
const deploy = {};
|
||||
if (enginesTurn(aircraft))
|
||||
for (const part of partsOf(table, 'spin', ['fan', 'prop', 'rotor']))
|
||||
spin[part.name] = spinRate(part.name);
|
||||
const gear = gearDown(aircraft);
|
||||
const doors = Math.min(1, rounded(gear * 4, DEPLOY_STEP));
|
||||
for (const part of partsOf(table, 'hinge', ['gear']))
|
||||
deploy[part.name] = gear;
|
||||
for (const part of partsOf(table, 'hinge', ['door']))
|
||||
deploy[part.name] = doors;
|
||||
for (const part of partsOf(table, 'hinge', ['flap']))
|
||||
deploy[part.name] = aircraft.onGround ? 0 : gear;
|
||||
return stateOf(spin, deploy);
|
||||
}
|
||||
|
||||
/**
|
||||
* The part state of a contact in an aircraft layer: an airport vehicle
|
||||
* (class `vehicle`) is a road vehicle ({@link groundVehiclePartState}, its
|
||||
* wheels rolling with its speed, never at a stop), every other contact an
|
||||
* aircraft ({@link aircraftPartState}).
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{klass?: string|null, onGround?: boolean,
|
||||
* heightAboveGroundM?: number|null, altitudeM?: number|null,
|
||||
* verticalRateMps?: number|null, speedMps?: number|null}} contact
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function aircraftLayerPartState(table, contact) {
|
||||
return contact.klass === 'vehicle'
|
||||
? groundVehiclePartState(table, { speedMps: contact.speedMps })
|
||||
: aircraftPartState(table, contact);
|
||||
}
|
||||
|
||||
/**
|
||||
* A vessel's part state, by the rule in the module comment; undefined when
|
||||
* it is not under way or its model has no radar.
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{speedMps?: number|null}} vessel
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function vesselPartState(table, { speedMps }) {
|
||||
if (!table || !(typeof speedMps === 'number' && speedMps > UNDER_WAY_MPS))
|
||||
return undefined;
|
||||
const spin = {};
|
||||
for (const part of partsOf(table, 'spin', ['radar']))
|
||||
spin[part.name] = SPIN_RATES_DPS.radar;
|
||||
return stateOf(spin, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* A road or rail vehicle's part state, by the rule in the module comment;
|
||||
* undefined when it neither moves nor stands at a stop, or its model has no
|
||||
* part the rule drives.
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{speedMps?: number|null, atStop?: boolean}} vehicle
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function groundVehiclePartState(table, { speedMps, atStop }) {
|
||||
if (!table) return undefined;
|
||||
const speed =
|
||||
typeof speedMps === 'number' && Number.isFinite(speedMps)
|
||||
? rounded(Math.max(0, speedMps), SPEED_STEP_MPS)
|
||||
: 0;
|
||||
const spin = {};
|
||||
const deploy = {};
|
||||
if (speed > 0)
|
||||
for (const part of partsOf(table, 'spin', ['axle'])) {
|
||||
const radius =
|
||||
part.pivot[1] > 0.05 ? part.pivot[1] : DEFAULT_WHEEL_RADIUS_M;
|
||||
// Rolling forward (−X) on the ground turns a wheel about +Z (its left).
|
||||
const sign = Math.sign(part.axis?.[2] ?? 0);
|
||||
if (sign !== 0)
|
||||
spin[part.name] = (sign * speed * RADIANS_TO_DEGREES) / radius;
|
||||
}
|
||||
if (atStop && speed < STOPPED_MPS)
|
||||
for (const part of partsOf(table, 'slide', ['doors']))
|
||||
deploy[part.name] = 1;
|
||||
return stateOf(spin, deploy);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import {
|
||||
aircraftLayerPartState,
|
||||
aircraftPartState,
|
||||
enginesTurn,
|
||||
gearDown,
|
||||
groundVehiclePartState,
|
||||
SPIN_RATES_DPS,
|
||||
vesselPartState,
|
||||
} from './modelPartDrivers.js';
|
||||
import { fleetPartTable } from './fleetModels.js';
|
||||
import { partTableOf } from '../render/modelParts.js';
|
||||
import { partsModelGlb } from '../render/conformance/partsModel.js';
|
||||
|
||||
const AIRLINER = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'flap_right', kind: 'hinge', axis: [0, 0, -1], limits: [0, 40] },
|
||||
{ name: 'engine_right', kind: 'marker' },
|
||||
{
|
||||
name: 'fan_right',
|
||||
kind: 'spin',
|
||||
parent: 'engine_right',
|
||||
axis: [1, 0, 0],
|
||||
},
|
||||
{ name: 'gear_nose', kind: 'hinge', axis: [0, 0, 1], limits: [90, 0] },
|
||||
{
|
||||
name: 'door_nose_right',
|
||||
kind: 'hinge',
|
||||
axis: [1, 0, 0],
|
||||
limits: [0, 90],
|
||||
},
|
||||
{ name: 'gear_right', kind: 'hinge', axis: [-1, 0, 0], limits: [90, 0] },
|
||||
],
|
||||
});
|
||||
|
||||
const HELICOPTER = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'rotor_main', kind: 'spin', axis: [0, 1, 0] },
|
||||
{ name: 'rotor_tail', kind: 'spin', axis: [0, 0, -1] },
|
||||
{ name: 'skids', kind: 'marker' },
|
||||
],
|
||||
});
|
||||
|
||||
const TRAWLER = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'radar', kind: 'spin', pivot: [-4, 10, 0], axis: [0, 1, 0] },
|
||||
{ name: 'bridge', kind: 'marker' },
|
||||
],
|
||||
});
|
||||
|
||||
const BUS = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{
|
||||
name: 'doors_right',
|
||||
kind: 'slide',
|
||||
pivot: [-4.75, 0.35, -1.3],
|
||||
axis: [1, 0, 0],
|
||||
limits: [0, 1.08],
|
||||
},
|
||||
{ name: 'axle_1', kind: 'spin', pivot: [-3.3, 0.5, 0], axis: [0, 0, -1] },
|
||||
{ name: 'axle_2', kind: 'spin', pivot: [2.6, 0.5, 0], axis: [0, 0, -1] },
|
||||
],
|
||||
});
|
||||
|
||||
test('the gear is down on the ground and up in cruise', () => {
|
||||
assert.equal(gearDown({ onGround: true }), 1);
|
||||
assert.equal(gearDown({ heightAboveGroundM: 10000, verticalRateMps: 0 }), 0);
|
||||
assert.equal(
|
||||
gearDown({ heightAboveGroundM: 10000, verticalRateMps: -10 }),
|
||||
0,
|
||||
);
|
||||
// No height known: up.
|
||||
assert.equal(gearDown({ heightAboveGroundM: null }), 0);
|
||||
});
|
||||
|
||||
test('without a ground height, the gear is down on approach: descending, slow and low', () => {
|
||||
// Denver: 1,650 m up, the ground under it unknown.
|
||||
const at = (fields) => gearDown({ heightAboveGroundM: null, ...fields });
|
||||
assert.equal(at({ altitudeM: 2000, verticalRateMps: -4, speedMps: 70 }), 1);
|
||||
// Climbing out, cruising, or descending fast: up.
|
||||
assert.equal(at({ altitudeM: 2000, verticalRateMps: 8, speedMps: 70 }), 0);
|
||||
assert.equal(at({ altitudeM: 11000, verticalRateMps: -4, speedMps: 70 }), 0);
|
||||
assert.equal(at({ altitudeM: 3000, verticalRateMps: -8, speedMps: 140 }), 0);
|
||||
// Without a speed it cannot tell: up.
|
||||
assert.equal(at({ altitudeM: 2000, verticalRateMps: -4 }), 0);
|
||||
});
|
||||
|
||||
test('on approach the gear comes down between 750 and 600 m above the ground', () => {
|
||||
const at = (h) => gearDown({ heightAboveGroundM: h, verticalRateMps: -4 });
|
||||
assert.equal(at(800), 0);
|
||||
assert.equal(at(675), 0.5);
|
||||
assert.equal(at(600), 1);
|
||||
assert.equal(at(50), 1);
|
||||
});
|
||||
|
||||
test('climbing or level, the gear goes up between 100 and 300 m', () => {
|
||||
const at = (h) => gearDown({ heightAboveGroundM: h, verticalRateMps: 8 });
|
||||
assert.equal(at(50), 1);
|
||||
assert.equal(at(200), 0.5);
|
||||
assert.equal(at(300), 0);
|
||||
assert.equal(at(700), 0);
|
||||
// Level at 700 m: up; descending through it: up until the approach band.
|
||||
assert.equal(gearDown({ heightAboveGroundM: 700, verticalRateMps: 0 }), 0);
|
||||
});
|
||||
|
||||
test('an airliner in cruise spins its fans, gear, doors and flaps up', () => {
|
||||
const state = aircraftPartState(AIRLINER, {
|
||||
onGround: false,
|
||||
heightAboveGroundM: 11000,
|
||||
verticalRateMps: 0,
|
||||
speedMps: 230,
|
||||
});
|
||||
assert.deepEqual(state, {
|
||||
spin: { fan_right: SPIN_RATES_DPS.fan },
|
||||
deploy: {
|
||||
flap_right: 0,
|
||||
gear_nose: 0,
|
||||
door_nose_right: 0,
|
||||
gear_right: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('an airliner on final has gear, doors and flaps down', () => {
|
||||
const state = aircraftPartState(AIRLINER, {
|
||||
onGround: false,
|
||||
heightAboveGroundM: 300,
|
||||
verticalRateMps: -4,
|
||||
speedMps: 70,
|
||||
});
|
||||
assert.deepEqual(state.deploy, {
|
||||
flap_right: 1,
|
||||
gear_nose: 1,
|
||||
door_nose_right: 1,
|
||||
gear_right: 1,
|
||||
});
|
||||
// The doors open over the first quarter of the gear's travel.
|
||||
const coming = aircraftPartState(AIRLINER, {
|
||||
heightAboveGroundM: 745,
|
||||
verticalRateMps: -4,
|
||||
});
|
||||
assert.ok(coming.deploy.gear_nose > 0 && coming.deploy.gear_nose < 0.25);
|
||||
assert.ok(coming.deploy.door_nose_right > coming.deploy.gear_nose);
|
||||
});
|
||||
|
||||
test('parked, its engines stop; taxiing, they turn; its flaps are up on the ground', () => {
|
||||
const parked = aircraftPartState(AIRLINER, { onGround: true, speedMps: 0 });
|
||||
assert.equal(parked.spin, undefined);
|
||||
assert.equal(parked.deploy.gear_nose, 1);
|
||||
assert.equal(parked.deploy.flap_right, 0);
|
||||
const taxiing = aircraftPartState(AIRLINER, { onGround: true, speedMps: 8 });
|
||||
assert.equal(taxiing.spin.fan_right, SPIN_RATES_DPS.fan);
|
||||
});
|
||||
|
||||
test('a helicopter’s rotors turn in the air and stop on the ground', () => {
|
||||
const flying = aircraftPartState(HELICOPTER, {
|
||||
onGround: false,
|
||||
heightAboveGroundM: 300,
|
||||
});
|
||||
assert.deepEqual(flying, {
|
||||
spin: {
|
||||
rotor_main: SPIN_RATES_DPS.rotor,
|
||||
rotor_tail: SPIN_RATES_DPS.rotor_tail,
|
||||
},
|
||||
});
|
||||
assert.equal(
|
||||
aircraftPartState(HELICOPTER, { onGround: true, speedMps: 0 }),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test('a vessel’s radar sweeps while it is under way', () => {
|
||||
assert.deepEqual(vesselPartState(TRAWLER, { speedMps: 4 }), {
|
||||
spin: { radar: SPIN_RATES_DPS.radar },
|
||||
});
|
||||
assert.equal(vesselPartState(TRAWLER, { speedMps: 0.2 }), undefined);
|
||||
assert.equal(vesselPartState(TRAWLER, { speedMps: null }), undefined);
|
||||
// A model without a radar, or without a table, gets nothing.
|
||||
assert.equal(vesselPartState(HELICOPTER, { speedMps: 4 }), undefined);
|
||||
assert.equal(vesselPartState(null, { speedMps: 4 }), undefined);
|
||||
});
|
||||
|
||||
test('a bus’s wheels roll with its speed, top forward; its doors open at a stop', () => {
|
||||
const moving = groundVehiclePartState(BUS, { speedMps: 10 });
|
||||
// 10 m/s on 0.5 m wheels: 20 rad/s, about +Z (its left), the top rolling forward.
|
||||
const rate = -(10 / 0.5) * (180 / Math.PI);
|
||||
assert.ok(Math.abs(moving.spin.axle_1 - rate) < 1e-9);
|
||||
assert.equal(moving.deploy, undefined);
|
||||
const stopped = groundVehiclePartState(BUS, { speedMps: 0, atStop: true });
|
||||
assert.deepEqual(stopped, { deploy: { doors_right: 1 } });
|
||||
assert.equal(
|
||||
groundVehiclePartState(BUS, { speedMps: 0, atStop: false }),
|
||||
undefined,
|
||||
);
|
||||
// Speeds are rounded: 10.1 m/s turns the wheels as 10 does.
|
||||
assert.deepEqual(groundVehiclePartState(BUS, { speedMps: 10.1 }), moving);
|
||||
});
|
||||
|
||||
test('an airport vehicle rolls its wheels and never holds its doors open; an aircraft is posed as one', () => {
|
||||
// A van: wheels roll with its speed.
|
||||
const rolling = aircraftLayerPartState(BUS, {
|
||||
klass: 'vehicle',
|
||||
onGround: true,
|
||||
speedMps: 10,
|
||||
});
|
||||
assert.deepEqual(rolling, groundVehiclePartState(BUS, { speedMps: 10 }));
|
||||
assert.ok(rolling.spin.axle_1 !== 0);
|
||||
// Stopped on the apron it is not at a stop: its doors stay shut.
|
||||
assert.equal(
|
||||
aircraftLayerPartState(BUS, {
|
||||
klass: 'vehicle',
|
||||
onGround: true,
|
||||
speedMps: 0,
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
// Every other class is an aircraft.
|
||||
const flying = {
|
||||
klass: 'helicopter',
|
||||
onGround: false,
|
||||
heightAboveGroundM: 300,
|
||||
};
|
||||
assert.deepEqual(
|
||||
aircraftLayerPartState(HELICOPTER, flying),
|
||||
aircraftPartState(HELICOPTER, flying),
|
||||
);
|
||||
});
|
||||
|
||||
test('engines and rotors turn in the air, or on the ground faster than 1 m/s', () => {
|
||||
assert.equal(enginesTurn({ onGround: false }), true);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: 0 }), false);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: 1 }), false);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: 1.5 }), true);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: null }), false);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: Number.NaN }), false);
|
||||
});
|
||||
|
||||
test('a model of a loaded set has its part table, read once', () => {
|
||||
const set = { bytes: new Map([['pod', partsModelGlb()]]) };
|
||||
const table = fleetPartTable(set, 'pod');
|
||||
assert.deepEqual(
|
||||
table.parts.map((p) => p.name),
|
||||
['body', 'pod', 'ram', 'arm'],
|
||||
);
|
||||
assert.equal(fleetPartTable(set, 'pod'), table);
|
||||
assert.equal(fleetPartTable(set, 'missing'), null);
|
||||
assert.equal(fleetPartTable(null, 'pod'), null);
|
||||
// A model without a table has none.
|
||||
const plain = { bytes: new Map([['x', new Uint8Array(4)]]) };
|
||||
assert.equal(fleetPartTable(plain, 'x'), null);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @module rotorFrames
|
||||
* @description Which rotor frame a helicopter icon shows at a time
|
||||
* (`aircraftIcon('helicopter', px, frame)`). The frames step at
|
||||
* {@link ROTOR_FPS}; each contact starts at its own phase, taken from its
|
||||
* id, so helicopters flying together do not change frame in step. The
|
||||
* rotor turns as the 3D model's does (`enginesTurn`): airborne, or on the
|
||||
* ground moving faster than 1 m/s; otherwise it holds the still frame.
|
||||
*/
|
||||
|
||||
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './aircraftIcons.js';
|
||||
import { enginesTurn } from './modelPartDrivers.js';
|
||||
|
||||
export { ROTOR_FRAMES, ROTOR_STILL_FRAME };
|
||||
|
||||
/** Rotor frames shown per second. */
|
||||
export const ROTOR_FPS = 10;
|
||||
|
||||
/** Phase by id: hashing each id once, as many as the helicopters seen. */
|
||||
const phases = new Map();
|
||||
const PHASES_MAX = 4096;
|
||||
|
||||
/**
|
||||
* A contact's phase, 0 (inclusive) to 1, the same for the same id every
|
||||
* time (FNV-1a over its characters, mixed).
|
||||
* @param {string} id
|
||||
* @returns {number}
|
||||
*/
|
||||
export function rotorPhase(id) {
|
||||
const key = String(id ?? '');
|
||||
let phase = phases.get(key);
|
||||
if (phase !== undefined) return phase;
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
hash ^= key.charCodeAt(i);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
// Mixed (MurmurHash3's finaliser), so ids differing in their last
|
||||
// characters, as ICAO addresses do, spread over the whole range.
|
||||
hash ^= hash >>> 16;
|
||||
hash = Math.imul(hash, 0x85ebca6b);
|
||||
hash ^= hash >>> 13;
|
||||
hash = Math.imul(hash, 0xc2b2ae35);
|
||||
hash ^= hash >>> 16;
|
||||
phase = (hash >>> 0) / 0x100000000;
|
||||
if (phases.size >= PHASES_MAX) phases.clear();
|
||||
phases.set(key, phase);
|
||||
return phase;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a helicopter's rotor turns: airborne, or taxiing (`enginesTurn`).
|
||||
* @param {{onGround?: boolean, speedMps?: number|null}} [state]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function rotorTurns({ onGround = false, speedMps = null } = {}) {
|
||||
return enginesTurn({ onGround, speedMps });
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotor frame a helicopter shows at `nowMs`: the still frame while its
|
||||
* rotor does not turn ({@link rotorTurns}), else stepping through the frames
|
||||
* at `ROTOR_FPS` from its phase.
|
||||
* @param {string} id
|
||||
* @param {number} nowMs Epoch ms (any steady clock).
|
||||
* @param {{onGround?: boolean, speedMps?: number|null}} [state] Ground speed in m/s.
|
||||
* @returns {number} 0 to `ROTOR_FRAMES - 1`.
|
||||
*/
|
||||
export function rotorFrame(id, nowMs, state = {}) {
|
||||
if (!rotorTurns(state) || !Number.isFinite(nowMs)) return ROTOR_STILL_FRAME;
|
||||
const step = Math.floor(
|
||||
(nowMs / 1000) * ROTOR_FPS + rotorPhase(id) * ROTOR_FRAMES,
|
||||
);
|
||||
return ((step % ROTOR_FRAMES) + ROTOR_FRAMES) % ROTOR_FRAMES;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { aircraftPartState } from './modelPartDrivers.js';
|
||||
import { partTableOf } from '../render/modelParts.js';
|
||||
import {
|
||||
ROTOR_FPS,
|
||||
ROTOR_FRAMES,
|
||||
ROTOR_STILL_FRAME,
|
||||
rotorFrame,
|
||||
rotorPhase,
|
||||
rotorTurns,
|
||||
} from './rotorFrames.js';
|
||||
import { aircraftIcon } from './aircraftIcons.js';
|
||||
|
||||
const svg = (uri) =>
|
||||
Buffer.from(uri.slice(uri.indexOf(',') + 1), 'base64').toString('utf8');
|
||||
|
||||
test('the helicopter has three rotor frames, each its own image', () => {
|
||||
assert.equal(ROTOR_FRAMES, 3);
|
||||
const frames = [0, 1, 2].map((frame) =>
|
||||
aircraftIcon('helicopter', 64, frame),
|
||||
);
|
||||
assert.equal(new Set(frames).size, 3);
|
||||
// Frames 30° apart on a four-blade rotor: the third steps back onto the
|
||||
// first, a seamless loop.
|
||||
assert.match(svg(frames[0]), /rotate\(15 0 -11\.2\)/);
|
||||
assert.match(svg(frames[1]), /rotate\(45 0 -11\.2\)/);
|
||||
assert.match(svg(frames[2]), /rotate\(75 0 -11\.2\)/);
|
||||
// No frame, or one out of range, is the still frame.
|
||||
assert.equal(aircraftIcon('helicopter', 64), frames[ROTOR_STILL_FRAME]);
|
||||
assert.equal(aircraftIcon('helicopter', 64, 7), frames[ROTOR_STILL_FRAME]);
|
||||
// Other kinds have one image whatever the frame.
|
||||
assert.equal(aircraftIcon('airliner', 64, 2), aircraftIcon('airliner', 64));
|
||||
});
|
||||
|
||||
test('frames step at the rotor rate through every frame in order', () => {
|
||||
const id = 'abc123';
|
||||
const stepMs = 1000 / ROTOR_FPS;
|
||||
const start = 1_700_000_000_000;
|
||||
const seen = [];
|
||||
for (let i = 0; i < 9; i++) seen.push(rotorFrame(id, start + i * stepMs + 1));
|
||||
for (let i = 1; i < seen.length; i++)
|
||||
assert.equal(seen[i], (seen[i - 1] + 1) % ROTOR_FRAMES, seen.join(','));
|
||||
// Within one step it holds.
|
||||
const at = start + 5 * stepMs + 1;
|
||||
const held = rotorFrame(id, at);
|
||||
for (let ms = 0; ms < stepMs; ms += 10) {
|
||||
const frame = rotorFrame(id, at + ms);
|
||||
assert.ok(frame === held || frame === (held + 1) % ROTOR_FRAMES);
|
||||
}
|
||||
});
|
||||
|
||||
test('each contact has its own phase, so a group does not change in step', () => {
|
||||
assert.equal(rotorPhase('abc123'), rotorPhase('abc123'));
|
||||
const ids = Array.from(
|
||||
{ length: 24 },
|
||||
(_, i) => `a${i.toString(16).padStart(5, '0')}`,
|
||||
);
|
||||
const phases = ids.map(rotorPhase);
|
||||
for (const phase of phases) assert.ok(phase >= 0 && phase < 1);
|
||||
assert.ok(new Set(phases).size > 20, 'phases differ by contact');
|
||||
// At one instant the group shows every frame, not one.
|
||||
const at = 1_700_000_000_000;
|
||||
const frames = new Set(ids.map((id) => rotorFrame(id, at)));
|
||||
assert.equal(frames.size, ROTOR_FRAMES);
|
||||
});
|
||||
|
||||
test('the rotor sprite turns exactly when the model’s rotor does: in the air, or taxiing', () => {
|
||||
const table = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'rotor_main', kind: 'spin', axis: [0, 1, 0] },
|
||||
],
|
||||
});
|
||||
const stepMs = 1000 / ROTOR_FPS;
|
||||
for (const state of [
|
||||
{ onGround: false },
|
||||
{ onGround: true, speedMps: 0 },
|
||||
{ onGround: true, speedMps: 1 },
|
||||
{ onGround: true, speedMps: 3 },
|
||||
{ onGround: true, speedMps: null },
|
||||
]) {
|
||||
const modelSpins = aircraftPartState(table, state)?.spin?.rotor_main > 0;
|
||||
assert.equal(rotorTurns(state), modelSpins, JSON.stringify(state));
|
||||
const frames = new Set(
|
||||
[0, 1, 2, 3].map((i) =>
|
||||
rotorFrame('abc123', 1_700_000_000_000 + i * stepMs + 1, state),
|
||||
),
|
||||
);
|
||||
assert.equal(frames.size, modelSpins ? ROTOR_FRAMES : 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('a helicopter on the ground holds the still frame', () => {
|
||||
const stepMs = 1000 / ROTOR_FPS;
|
||||
for (let i = 0; i < 6; i++)
|
||||
assert.equal(
|
||||
rotorFrame('abc123', 1_700_000_000_000 + i * stepMs, { onGround: true }),
|
||||
ROTOR_STILL_FRAME,
|
||||
);
|
||||
assert.equal(rotorFrame('abc123', Number.NaN), ROTOR_STILL_FRAME);
|
||||
});
|
||||
@@ -38,6 +38,29 @@ function courseBetween(from, to) {
|
||||
return (toDegrees(Math.atan2(y, x)) + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where in `fixes` (in time order) the fixes to make begin: the last at or
|
||||
* before the newest a contact holds, so the held run goes on into the new
|
||||
* one and its seam is made again from the new run (its course heads where
|
||||
* the new run goes, at the new record's height), and those after it. 0
|
||||
* unless `history` is its own fixes around a time (`timeline` entries) and
|
||||
* `fixes` starts at or before the newest of them and reaches it.
|
||||
* @param {object[]|undefined} history
|
||||
* @param {Array<{atMs: number}>} fixes
|
||||
* @returns {number}
|
||||
*/
|
||||
function heldThrough(history, fixes) {
|
||||
const newest = history?.[history.length - 1];
|
||||
if (!newest || history[0].timeline !== true || newest.timeline !== true)
|
||||
return 0;
|
||||
const heldMs = newest.epochMs;
|
||||
if (!(fixes[0].atMs <= heldMs && fixes[fixes.length - 1].atMs >= heldMs))
|
||||
return 0;
|
||||
let index = 0;
|
||||
while (index < fixes.length && fixes[index].atMs <= heldMs) index++;
|
||||
return index - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* An aircraft's motion history with the fixes its record carries at a time
|
||||
* (`observation.fixes`, see src/time/timelineFixes.js) merged in, so the
|
||||
@@ -65,7 +88,12 @@ export function mergeAircraftTimelineFixes(
|
||||
const baroM = Number.isFinite(observation.baroAltitudeM)
|
||||
? observation.baroAltitudeM
|
||||
: null;
|
||||
const entries = fixes.map((fix, index) => {
|
||||
// Playing on, the next snapshot's fixes mostly repeat those held: when its
|
||||
// run reaches back into the held fixes, those stay as they are and only
|
||||
// the seam and the fixes past it are made and added.
|
||||
const from = heldThrough(history, fixes);
|
||||
const entries = fixes.slice(from).map((fix, offset) => {
|
||||
const index = from + offset;
|
||||
const course =
|
||||
index + 1 < fixes.length
|
||||
? courseBetween(fix, fixes[index + 1])
|
||||
|
||||
@@ -145,3 +145,85 @@ test("a tracked trail takes the fixes after its newest point, up to the snapshot
|
||||
);
|
||||
assert.equal(historyAfterTrail(history, [], 120_000).length, 3);
|
||||
});
|
||||
|
||||
test('playing on, the fixes a contact holds stay as they are and only the seam and newer ones are made', () => {
|
||||
const held = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 1), fix(120_000, 2)] },
|
||||
META,
|
||||
100,
|
||||
60_000,
|
||||
);
|
||||
const kept = held.map((entry) => entry);
|
||||
// The next snapshot's run reaches back into the held fixes, a little
|
||||
// differently picked: those held stay, the newer are added after them.
|
||||
const next = mergeAircraftTimelineFixes(
|
||||
held,
|
||||
{
|
||||
fixes: [
|
||||
fix(30_000, 0.6),
|
||||
fix(90_000, 1.6),
|
||||
fix(120_000, 2.1),
|
||||
fix(180_000, 3),
|
||||
fix(240_000, 4),
|
||||
],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
next.map((entry) => entry.epochMs),
|
||||
[0, 60_000, 120_000, 180_000, 240_000],
|
||||
);
|
||||
for (const [k, entry] of kept.slice(0, -1).entries())
|
||||
assert.equal(next[k], entry, 'a held entry is kept, not made again');
|
||||
// The seam is made again from the new run: its course heads where the
|
||||
// new run goes, so the course and height do not step there.
|
||||
assert.notEqual(next[2], kept[2]);
|
||||
const lat = (entry) =>
|
||||
Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(entry.position).latitude,
|
||||
);
|
||||
assert.ok(Math.abs(lat(next[2]) - 2.1) < 1e-9);
|
||||
assert.ok(Math.abs(lat(next[3]) - 3) < 1e-9);
|
||||
// Each new fix heads where the track goes next, read from the new run.
|
||||
assert.ok(
|
||||
Math.abs(next[3].track) < 1e-6 || Math.abs(next[3].track - 360) < 1e-6,
|
||||
);
|
||||
});
|
||||
|
||||
test('a run that starts after the held fixes, or a history not of its own fixes, is merged whole', () => {
|
||||
const held = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 1)] },
|
||||
META,
|
||||
100,
|
||||
0,
|
||||
);
|
||||
const later = mergeAircraftTimelineFixes(
|
||||
held,
|
||||
{ fixes: [fix(120_000, 2), fix(180_000, 3)] },
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
later.map((entry) => entry.epochMs),
|
||||
[0, 60_000, 120_000, 180_000],
|
||||
);
|
||||
// A run reaching back over the held fixes replaces them, as before, when
|
||||
// the history holds a live report.
|
||||
const report = { ...held[1], timeline: undefined };
|
||||
const mixed = mergeAircraftTimelineFixes(
|
||||
[held[0], report],
|
||||
{ fixes: [fix(30_000, 0.5), fix(90_000, 1.5)] },
|
||||
META,
|
||||
100,
|
||||
60_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
mixed.map((entry) => entry.epochMs),
|
||||
[0, 30_000, 90_000],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @module units
|
||||
* @description Unit conversions the layers share.
|
||||
*/
|
||||
|
||||
/** Metres a second in one knot (one nautical mile, 1852 m, an hour). */
|
||||
export const KNOT_MPS = 1852 / 3600;
|
||||
+15
-37
@@ -5,7 +5,11 @@
|
||||
*/
|
||||
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import { normalizeVesselType } from './vesselTypes.js';
|
||||
import {
|
||||
normalizeVesselType,
|
||||
vesselKind,
|
||||
VESSEL_KIND_STYLES,
|
||||
} from './vesselTypes.js';
|
||||
|
||||
export { normalizeVesselType };
|
||||
|
||||
@@ -22,32 +26,7 @@ export const VESSEL_CARD_FADE_DISTANCE_M = 5_000_000;
|
||||
export const VESSEL_CARD_FADE_START_RATIO = 0.7;
|
||||
|
||||
/**
|
||||
* AIS type family → chevron hue + card accent. Single source of truth for
|
||||
* vessel type colors so billboard chevrons and host cards cannot drift apart.
|
||||
*/
|
||||
const TYPE_STYLES = [
|
||||
{ pattern: /tanker/i, css: '#ffb347', accent: '255, 179, 71' },
|
||||
{
|
||||
pattern: /cargo|container|bulk|carrier/i,
|
||||
css: '#39d5ff',
|
||||
accent: '57, 213, 255',
|
||||
},
|
||||
{
|
||||
pattern: /passenger|ferry|cruise/i,
|
||||
css: '#ff7adf',
|
||||
accent: '255, 122, 223',
|
||||
},
|
||||
{ pattern: /fishing/i, css: '#7cff9b', accent: '124, 255, 155' },
|
||||
{
|
||||
pattern: /tug|tow|pilot|supply|service/i,
|
||||
css: '#f7f0a3',
|
||||
accent: '247, 240, 163',
|
||||
},
|
||||
];
|
||||
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
|
||||
|
||||
/**
|
||||
* An aid to navigation's disc and card accent: a bone white apart from every
|
||||
* An aid to navigation's buoy and card accent: a bone white apart from every
|
||||
* ship type's colour.
|
||||
*/
|
||||
export const AID_TO_NAVIGATION_STYLE = Object.freeze({
|
||||
@@ -55,8 +34,8 @@ export const AID_TO_NAVIGATION_STYLE = Object.freeze({
|
||||
accent: '217, 210, 192',
|
||||
});
|
||||
|
||||
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
|
||||
// and tests match on them.
|
||||
// Card text for the type tokens above. The tokens stay English: the vessel
|
||||
// kinds (`vesselKind`) and tests match on them.
|
||||
const TYPE_DISPLAY_KEYS = Object.freeze({
|
||||
FISHING: msg('FISHING'),
|
||||
TOWING: msg('TOWING'),
|
||||
@@ -91,19 +70,18 @@ export function displayVesselType(type) {
|
||||
return key ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/** AIS ship type → CSS hex hue for the billboard chevron. */
|
||||
/**
|
||||
* AIS ship type → CSS hex colour its sprite is tinted with. The sprite and
|
||||
* the card take it from the vessel's kind (`vesselKind`), so they cannot
|
||||
* drift apart.
|
||||
*/
|
||||
export function vesselTypeCss(type) {
|
||||
return styleForType(type).css;
|
||||
return VESSEL_KIND_STYLES[vesselKind(type)].css;
|
||||
}
|
||||
|
||||
/** AIS ship type → "r, g, b" accent string for the host card. */
|
||||
export function accentForVesselType(type) {
|
||||
return styleForType(type).accent;
|
||||
}
|
||||
|
||||
function styleForType(type) {
|
||||
const text = normalizeVesselType(type);
|
||||
return TYPE_STYLES.find((entry) => entry.pattern.test(text)) || DEFAULT_STYLE;
|
||||
return VESSEL_KIND_STYLES[vesselKind(type)].accent;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* @module vesselSprites
|
||||
* @description The map sprites of the vessel layer, as SVG data URIs: one hull
|
||||
* per vessel kind (`vesselKind` in vesselTypes.js), seen from above with its
|
||||
* bow up (north), and one buoy for every aid to navigation, standing upright.
|
||||
*
|
||||
* Every sprite is white with dark detail, drawn on the 96-unit frame of
|
||||
* aircraftIcons.js (centre 48,48). The layer tints it at draw time (the
|
||||
* kind's colour, white while selected), so one image serves every colour and
|
||||
* state, as the aircraft glyphs do: one icon-atlas slot per shape. Hulls
|
||||
* share one length and differ in shape only; widths are exaggerated so they
|
||||
* read at small sizes.
|
||||
*/
|
||||
|
||||
const VIEW = 96;
|
||||
const C = VIEW / 2;
|
||||
|
||||
/** Raster size of every vessel sprite (px): sharp at its largest drawn size. */
|
||||
export const VESSEL_SPRITE_PX = 64;
|
||||
|
||||
/** The hull edge: dark so a light tint still reads on light ground. */
|
||||
const EDGE =
|
||||
'stroke="rgba(4,18,24,0.9)" stroke-width="2.1" stroke-linejoin="round"';
|
||||
/** Superstructure and deck detail: dark, so tinting leaves it dark. */
|
||||
const DETAIL = 'fill="rgba(4,18,24,0.42)"';
|
||||
|
||||
/** Each kind's hull and detail, centred, bow toward −Y. */
|
||||
const HULLS = {
|
||||
// Container ship: fine bow, long parallel sides, square stern; container
|
||||
// rows forward and the bridge aft.
|
||||
cargo: `
|
||||
<path d="M0,-43 C -7,-41 -13,-36 -16.8,-28 L -16.8,37 L -14.7,43 L 14.7,43
|
||||
L 16.8,37 L 16.8,-28 C 13,-36 7,-41 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-13,-26 h26 v5 h-26 Z M-13,-19 h26 v5 h-26 Z M-13,-12 h26 v5 h-26 Z
|
||||
M-13,-5 h26 v5 h-26 Z M-13,2 h26 v5 h-26 Z M-13,9 h26 v5 h-26 Z
|
||||
M-13,16 h26 v5 h-26 Z M-16,26 h32 v4 h-32 Z" ${DETAIL}/>`,
|
||||
|
||||
// Tanker: full bow, a pipe run down the centre line with its manifold
|
||||
// across, the bridge aft.
|
||||
tanker: `
|
||||
<path d="M0,-43 C -8,-42 -15,-37 -17.9,-30 L -17.9,36 L -15.3,43 L 15.3,43
|
||||
L 17.9,36 L 17.9,-30 C 15,-37 8,-42 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-1.3,-34 h2.6 v62 h-2.6 Z M-14,-5.6 h28 v3.2 h-28 Z
|
||||
M-17.4,28.6 h34.8 v5.3 h-34.8 Z" ${DETAIL}/>`,
|
||||
|
||||
// Passenger ship or ferry: a superstructure covering nearly the whole deck.
|
||||
passenger: `
|
||||
<path d="M0,-43 C -6,-41.5 -12,-36 -15.3,-29.6 L -17.1,-28 L -17.1,30.5
|
||||
L -15.6,39 L -14.2,43 L 14.2,43 L 15.6,39 L 17.1,30.5 L 17.1,-28
|
||||
L 15.3,-29.6 C 12,-36 6,-41.5 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-14.6,-27 h29.2 v55 h-29.2 Z" ${DETAIL}/>
|
||||
<path d="M-2.5,6 h5 v8 h-5 Z" fill="white"/>`,
|
||||
|
||||
// High-speed craft: a catamaran, two slim bows and a square stern.
|
||||
highspeed: `
|
||||
<path d="M-17.9,-32.3 L -16.1,-33.1 L -14.7,-39.9 L -13.4,-43 L -12.1,-40.7
|
||||
L -9.9,-32.4 L 9.9,-32.4 L 12.1,-40.7 L 13.4,-43 L 14.7,-39.9
|
||||
L 16.1,-33.1 L 17.9,-32.3 L 17.9,43 L 9.3,43 L 8.3,42.2 L -8.3,42.2
|
||||
L -9.3,43 L -17.9,43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-9.7,-14.6 h19.4 v12.8 h-19.4 Z" ${DETAIL}/>`,
|
||||
|
||||
// Fishing vessel: a narrow hull, the wheelhouse forward and outrigger
|
||||
// booms across amidships.
|
||||
fishing: `
|
||||
<path d="M-24,2.3 h48 v3.2 h-48 Z" fill="white" ${EDGE}/>
|
||||
<path d="M0,-43 C -5,-40 -9.5,-31 -11.7,-24.8 L -13.1,-17.7 L -13.1,30.4
|
||||
L -11.1,41.1 L -9.9,43 L 9.9,43 L 11.1,41.1 L 13.1,30.4 L 13.1,-17.7
|
||||
L 11.7,-24.8 C 9.5,-31 5,-40 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-8.8,-20.4 h17.6 v12.1 h-17.6 Z" ${DETAIL}/>`,
|
||||
|
||||
// Tug, pilot or service boat: short, wide and blunt, the wheelhouse
|
||||
// amidships and two towing bitts aft.
|
||||
tug: `
|
||||
<path d="M-7,-43 L 7,-43 C 14,-40 20,-33 22.5,-22 L 24,-13 L 24,19
|
||||
C 24,28 21,36 17,42 L 16,43 L -16,43 L -17,42 C -21,36 -24,28
|
||||
-24,19 L -24,-13 L -22.5,-22 C -20,-33 -14,-40 -7,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-13.9,-12.9 h27.8 v12.3 h-27.8 Z M-12.4,4.8 h5 v4.3 h-5 Z
|
||||
M7.4,4.8 h5 v4.3 h-5 Z" ${DETAIL}/>`,
|
||||
|
||||
// Sailing boat: a rounded hull with its sail filled to one side.
|
||||
sailing: `
|
||||
<path d="M0,-43 C -6,-40 -12,-31 -15.5,-21 C -18,-13 -19.4,-5 -19.4,3
|
||||
L -19.3,34.2 L -17.1,39.8 L -14.3,43 L 14.3,43 L 17.1,39.8
|
||||
L 19.3,34.2 L 19.4,3 C 19.4,-5 18,-13 15.5,-21 C 12,-31 6,-40 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M0,-30 Q 21.6,-6 2,26 L -1,26 Q 7.8,-4 0,-30 Z" fill="white"
|
||||
stroke="rgba(4,18,24,0.9)" stroke-width="1.4" stroke-linejoin="round"/>
|
||||
<circle cx="0" cy="-12" r="2.6" fill="rgba(4,18,24,0.85)"/>`,
|
||||
|
||||
// Pleasure craft: a motor yacht, fine bow and a long cabin.
|
||||
pleasure: `
|
||||
<path d="M0,-43 C -5,-40 -11,-31 -15.9,-19.8 L -17.9,-12.6 L -17.9,32.7
|
||||
L -17.2,37.6 L -16.2,38.2 L -16.2,43 L 16.2,43 L 16.2,38.2
|
||||
L 17.2,37.6 L 17.9,32.7 L 17.9,-12.6 L 15.9,-19.8 C 11,-31 5,-40 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-15.2,-12.8 h30.4 v34.5 h-30.4 Z" ${DETAIL}/>`,
|
||||
|
||||
// Military, law enforcement or rescue: a patrol boat, sharp bow, a gun
|
||||
// forward of the bridge.
|
||||
military: `
|
||||
<path d="M0,-43 C -4,-41 -9.6,-32 -12.6,-25.2 L -14.8,-17.1 L -15.3,-11.7
|
||||
L -15.1,36.8 L -13.8,41.3 L -12.6,43 L 12.6,43 L 13.8,41.3
|
||||
L 15.3,36.8 L 15.3,-11.7 L 14.8,-17.1 L 12.6,-25.2 C 9.6,-32 4,-41 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-10.2,-13.4 h20.4 v10 h-20.4 Z M-4.2,9.6 h8.4 v6.5 h-8.4 Z" ${DETAIL}/>
|
||||
<circle cx="0" cy="-22" r="3.2" ${DETAIL}/>`,
|
||||
|
||||
// Any other vessel: a plain hull with a deckhouse aft.
|
||||
other: `
|
||||
<path d="M0,-43 C -6,-42 -12,-37 -14.8,-29.9 L -17.4,-23.3 L -17.9,-19.4
|
||||
L -17.9,35.6 L -16.9,39.3 L -14.9,43 L 14.9,43 L 16.9,39.3
|
||||
L 17.9,35.6 L 17.9,-19.4 L 17.4,-23.3 L 14.8,-29.9 C 12,-37 6,-42 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-10.8,8.3 h21.6 v13.1 h-21.6 Z" ${DETAIL}/>`,
|
||||
};
|
||||
|
||||
/**
|
||||
* The buoy every aid to navigation is drawn as, seen from the side: a
|
||||
* flared float with a dark waterline band, a tapering body, a lantern and a
|
||||
* round top-mark, centred on the frame. No halo; it is never turned.
|
||||
*/
|
||||
const BUOY = `
|
||||
<path d="M27.6,36.5 L 26.4,31.5 L 25.2,27.5 L 14.4,23.5 L 11.4,-7.5
|
||||
L 12.6,-7.5 L 12.6,-10.5 L 3.8,-10.5 L 2.9,-17.5 L -2.9,-17.5
|
||||
L -3.8,-10.5 L -12.6,-10.5 L -12.6,-7.5 L -11.4,-7.5 L -14.4,23.5
|
||||
L -25.2,27.5 L -26.4,31.5 L -27.6,36.5 Z" fill="white" ${EDGE}/>
|
||||
<path d="M26.4,31.5 L 27.6,36.5 L -27.6,36.5 L -26.4,31.5 Z
|
||||
M-12.6,-10.5 h25.2 v3 h-25.2 Z" fill="rgba(4,18,24,0.7)"/>
|
||||
<path d="M-1.9,-22 h3.8 v4.5 h-3.8 Z" fill="white" ${EDGE}/>
|
||||
<circle cx="0" cy="-30" r="7" fill="white" ${EDGE}/>`;
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
const b64 = (s) =>
|
||||
typeof btoa === 'function'
|
||||
? btoa(s)
|
||||
: Buffer.from(s, 'utf8').toString('base64');
|
||||
|
||||
function sprite(key, body) {
|
||||
let uri = cache.get(key);
|
||||
if (!uri) {
|
||||
const px = VESSEL_SPRITE_PX;
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C})">${body}</g></svg>`;
|
||||
uri = 'data:image/svg+xml;base64,' + b64(svg);
|
||||
cache.set(key, uri);
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hull sprite of a vessel kind (`other` for one it does not know).
|
||||
* @param {string} kind One of `VESSEL_KINDS`.
|
||||
* @returns {string} SVG data URI.
|
||||
*/
|
||||
export function vesselSprite(kind) {
|
||||
const k = HULLS[kind] ? kind : 'other';
|
||||
return sprite(k, HULLS[k]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The buoy sprite of every aid to navigation.
|
||||
* @returns {string} SVG data URI.
|
||||
*/
|
||||
export function aidSprite() {
|
||||
return sprite('aid', BUOY);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { aidSprite, vesselSprite, VESSEL_SPRITE_PX } from './vesselSprites.js';
|
||||
import { VESSEL_KINDS, VESSEL_KIND_STYLES, vesselKind } from './vesselTypes.js';
|
||||
import { AID_TO_NAVIGATION_STYLE, accentForVesselType, vesselTypeCss } from './vesselLabels.js';
|
||||
|
||||
const svg = (uri) =>
|
||||
Buffer.from(uri.slice(uri.indexOf(',') + 1), 'base64').toString('utf8');
|
||||
|
||||
test('vessel types pick their kind by AIS code or text family', () => {
|
||||
const cases = {
|
||||
cargo: ['70', '79', 'Container Ship', 'Bulk Carrier', 'Ro-Ro Cargo'],
|
||||
tanker: ['80', '89', 'Crude Oil Tanker', 'LNG Carrier', 'LPG'],
|
||||
passenger: ['60', '69', 'Passenger/Ferry', 'Cruise Ship'],
|
||||
highspeed: ['40', '49', 'High-Speed Craft', 'HSC'],
|
||||
fishing: ['30', 'Fishing Vessel', 'Trawler'],
|
||||
tug: ['31', '32', '50', '52', '53', '54', 'Tug', 'Pilot Vessel', 'Supply'],
|
||||
sailing: ['36', 'Sailing Vessel'],
|
||||
pleasure: ['37', 'Pleasure Craft', 'Yacht'],
|
||||
military: ['35', '55', '51', 'Military', 'Law Enforcement', 'Coast Guard', 'SAR'],
|
||||
other: ['0', '20', '33', '34', '58', '90', 'Dredger', '', null, undefined, '255'],
|
||||
};
|
||||
for (const [kind, types] of Object.entries(cases))
|
||||
for (const type of types) assert.equal(vesselKind(type), kind, String(type));
|
||||
assert.deepEqual(new Set(Object.keys(cases)), new Set(VESSEL_KINDS));
|
||||
});
|
||||
|
||||
test('each vessel kind has its own white hull sprite, bow up', () => {
|
||||
const sprites = VESSEL_KINDS.map(vesselSprite);
|
||||
assert.equal(new Set(sprites).size, VESSEL_KINDS.length);
|
||||
for (const uri of sprites) {
|
||||
const text = svg(uri);
|
||||
assert.match(text, new RegExp(`width="${VESSEL_SPRITE_PX}"`));
|
||||
assert.match(text, /viewBox="0 0 96 96"/);
|
||||
// Drawn white for the tint; nothing baked in colour.
|
||||
assert.match(text, /fill="white"/);
|
||||
assert.doesNotMatch(text, /#[0-9a-f]{6}/i);
|
||||
}
|
||||
assert.equal(vesselSprite('unknown'), vesselSprite('other'));
|
||||
});
|
||||
|
||||
test('vessel colours: one per kind, the new kinds apart from the rest', () => {
|
||||
const css = VESSEL_KINDS.map((kind) => VESSEL_KIND_STYLES[kind].css);
|
||||
// Only cargo and other share the default cyan.
|
||||
assert.equal(new Set(css).size, VESSEL_KINDS.length - 1);
|
||||
assert.equal(VESSEL_KIND_STYLES.cargo.css, VESSEL_KIND_STYLES.other.css);
|
||||
for (const kind of ['sailing', 'pleasure', 'military', 'highspeed']) {
|
||||
const own = VESSEL_KIND_STYLES[kind].css;
|
||||
for (const other of VESSEL_KINDS)
|
||||
if (other !== kind) assert.notEqual(own, VESSEL_KIND_STYLES[other].css, `${kind} vs ${other}`);
|
||||
assert.notEqual(own, AID_TO_NAVIGATION_STYLE.css);
|
||||
}
|
||||
// The sprite tint and the card accent are the same colour.
|
||||
for (const [type, kind] of [['36', 'sailing'], ['37', 'pleasure'], ['55', 'military'], ['41', 'highspeed'], ['71', 'cargo']]) {
|
||||
const { css: hex, accent } = VESSEL_KIND_STYLES[kind];
|
||||
assert.equal(vesselTypeCss(type), hex);
|
||||
assert.equal(accentForVesselType(type), accent);
|
||||
const rgb = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join(', ');
|
||||
assert.equal(accent, rgb, kind);
|
||||
}
|
||||
});
|
||||
|
||||
test('an aid to navigation is the one buoy sprite, white with no halo', () => {
|
||||
const text = svg(aidSprite());
|
||||
assert.equal(aidSprite(), aidSprite());
|
||||
assert.ok(!VESSEL_KINDS.map(vesselSprite).includes(aidSprite()));
|
||||
assert.match(text, /fill="white"/);
|
||||
// No light halo stroke around it.
|
||||
assert.doesNotMatch(text, /rgba\(235,240,245/);
|
||||
assert.doesNotMatch(text, /#[0-9a-f]{6}/i);
|
||||
});
|
||||
@@ -46,6 +46,76 @@ export function normalizeVesselType(type) {
|
||||
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
|
||||
}
|
||||
|
||||
/**
|
||||
* The vessel kinds a ship is drawn as, each with its own hull sprite and
|
||||
* colour (`vesselSprites.js`), by the type family its AIS type resolves to
|
||||
* ({@link normalizeVesselType}), in order: the first that matches.
|
||||
*/
|
||||
const VESSEL_KIND_RULES = [
|
||||
['tanker', /tanker|\blng\b|\blpg\b|gas carrier/i],
|
||||
['highspeed', /high[- ]?speed|\bhsc\b/i],
|
||||
['passenger', /passenger|ferry|cruise/i],
|
||||
['cargo', /cargo|container|bulk|carrier|freighter|ro-?ro/i],
|
||||
['fishing', /fishing|trawler/i],
|
||||
[
|
||||
'military',
|
||||
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i,
|
||||
],
|
||||
['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i],
|
||||
['sailing', /sail/i],
|
||||
['pleasure', /pleasure|yacht/i],
|
||||
];
|
||||
|
||||
/** Every vessel kind {@link vesselKind} names, `other` last. */
|
||||
export const VESSEL_KINDS = Object.freeze([
|
||||
...VESSEL_KIND_RULES.map(([kind]) => kind),
|
||||
'other',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Each vessel kind's colour on the map and on its card, as CSS and as the
|
||||
* card's "r, g, b" accent. Every one reads on dark water and differs from
|
||||
* the rest; cargo and other share the default cyan.
|
||||
*/
|
||||
export const VESSEL_KIND_STYLES = Object.freeze({
|
||||
cargo: Object.freeze({ css: '#39d5ff', accent: '57, 213, 255' }),
|
||||
tanker: Object.freeze({ css: '#ffb347', accent: '255, 179, 71' }),
|
||||
passenger: Object.freeze({ css: '#ff7adf', accent: '255, 122, 223' }),
|
||||
highspeed: Object.freeze({ css: '#c6ff3d', accent: '198, 255, 61' }),
|
||||
fishing: Object.freeze({ css: '#7cff9b', accent: '124, 255, 155' }),
|
||||
tug: Object.freeze({ css: '#f7f0a3', accent: '247, 240, 163' }),
|
||||
sailing: Object.freeze({ css: '#b49cff', accent: '180, 156, 255' }),
|
||||
pleasure: Object.freeze({ css: '#ff6f61', accent: '255, 111, 97' }),
|
||||
military: Object.freeze({ css: '#a9bccb', accent: '169, 188, 203' }),
|
||||
other: Object.freeze({ css: '#39d5ff', accent: '57, 213, 255' }),
|
||||
});
|
||||
|
||||
/** Kind by type text: a feed uses few distinct type texts. */
|
||||
const KIND_MEMO = new Map();
|
||||
const KIND_MEMO_MAX = 1024;
|
||||
|
||||
/**
|
||||
* The kind of vessel an AIS type names, a numeric ship-type code (ITU-R
|
||||
* M.1371) or a text type: `cargo` (70 to 79), `tanker` (80 to 89),
|
||||
* `passenger` (60 to 69), `highspeed` (40 to 49), `fishing` (30), `tug`
|
||||
* (tugs, towing, pilots, tenders, anti-pollution: 31, 32, 50, 52 to 54),
|
||||
* `sailing` (36), `pleasure` (37), `military` (military, law enforcement,
|
||||
* search and rescue: 35, 55, 51) or `other` (anything else, unknown types
|
||||
* included).
|
||||
* @param {string|number|null|undefined} type
|
||||
* @returns {string} One of {@link VESSEL_KINDS}.
|
||||
*/
|
||||
export function vesselKind(type) {
|
||||
const text = normalizeVesselType(type);
|
||||
let kind = KIND_MEMO.get(text);
|
||||
if (kind !== undefined) return kind;
|
||||
kind = VESSEL_KIND_RULES.find(([, pattern]) => pattern.test(text))?.[0];
|
||||
kind ??= 'other';
|
||||
if (KIND_MEMO.size >= KIND_MEMO_MAX) KIND_MEMO.clear();
|
||||
KIND_MEMO.set(text, kind);
|
||||
return kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
|
||||
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
|
||||
|
||||
@@ -1100,6 +1100,10 @@
|
||||
"Fast jet": "نفاثة سريعة",
|
||||
"Business jet": "طائرة رجال أعمال",
|
||||
"Drone": "طائرة مسيّرة",
|
||||
"Airport vehicle": "مركبة مطار",
|
||||
"Ground station / obstacle": "محطة أرضية / عائق",
|
||||
"Airport vehicles": "مركبات المطار",
|
||||
"Ground stations / obstacles": "محطات أرضية / عوائق",
|
||||
"General emergency": "طوارئ عامة",
|
||||
"Unlawful interference": "تدخل غير مشروع",
|
||||
"Radio failure": "عطل في الاتصال اللاسلكي",
|
||||
|
||||
@@ -1060,6 +1060,10 @@
|
||||
"Fast jet": "Kampfjet",
|
||||
"Business jet": "Businessjet",
|
||||
"Drone": "Drohne",
|
||||
"Airport vehicle": "Flughafenfahrzeug",
|
||||
"Ground station / obstacle": "Bodenstation / Hindernis",
|
||||
"Airport vehicles": "Flughafenfahrzeuge",
|
||||
"Ground stations / obstacles": "Bodenstationen / Hindernisse",
|
||||
"General emergency": "Allgemeiner Notfall",
|
||||
"Unlawful interference": "Widerrechtlicher Eingriff",
|
||||
"Radio failure": "Funkausfall",
|
||||
|
||||
@@ -2836,6 +2836,10 @@
|
||||
"Fast jet": "Avión de alto rendimiento",
|
||||
"Business jet": "Reactor ejecutivo",
|
||||
"Drone": "Dron",
|
||||
"Airport vehicle": "Vehículo de aeropuerto",
|
||||
"Ground station / obstacle": "Estación terrestre / obstáculo",
|
||||
"Airport vehicles": "Vehículos de aeropuerto",
|
||||
"Ground stations / obstacles": "Estaciones terrestres / obstáculos",
|
||||
"fire cause|Human": "humana",
|
||||
"fire cause|Natural": "natural",
|
||||
"fire cause|Undetermined": "indeterminada",
|
||||
|
||||
@@ -127,6 +127,10 @@
|
||||
"Fast jet": "Avion de chasse",
|
||||
"Business jet": "Jet d'affaires",
|
||||
"Drone": "Drone",
|
||||
"Airport vehicle": "Véhicule d'aéroport",
|
||||
"Ground station / obstacle": "Station au sol / obstacle",
|
||||
"Airport vehicles": "Véhicules d'aéroport",
|
||||
"Ground stations / obstacles": "Stations au sol / obstacles",
|
||||
"General emergency": "Urgence générale",
|
||||
"Unlawful interference": "Intervention illicite",
|
||||
"Radio failure": "Panne radio",
|
||||
|
||||
@@ -52,6 +52,10 @@
|
||||
"Fast jet": "מטוס סילון מהיר",
|
||||
"Business jet": "מטוס מנהלים",
|
||||
"Drone": "רחפן",
|
||||
"Airport vehicle": "רכב שדה תעופה",
|
||||
"Ground station / obstacle": "תחנה קרקעית / מכשול",
|
||||
"Airport vehicles": "רכבי שדה תעופה",
|
||||
"Ground stations / obstacles": "תחנות קרקעיות / מכשולים",
|
||||
"General emergency": "חירום כללי",
|
||||
"Unlawful interference": "התערבות בלתי חוקית",
|
||||
"Radio failure": "כשל קשר",
|
||||
|
||||
@@ -127,6 +127,10 @@
|
||||
"Fast jet": "Jet ad alte prestazioni",
|
||||
"Business jet": "Business jet",
|
||||
"Drone": "Drone",
|
||||
"Airport vehicle": "Veicolo aeroportuale",
|
||||
"Ground station / obstacle": "Stazione a terra / ostacolo",
|
||||
"Airport vehicles": "Veicoli aeroportuali",
|
||||
"Ground stations / obstacles": "Stazioni a terra / ostacoli",
|
||||
"General emergency": "Emergenza generale",
|
||||
"Unlawful interference": "Interferenza illecita",
|
||||
"Radio failure": "Avaria radio",
|
||||
|
||||
@@ -119,6 +119,10 @@
|
||||
"Fast jet": "高速ジェット機",
|
||||
"Business jet": "ビジネスジェット",
|
||||
"Drone": "ドローン",
|
||||
"Airport vehicle": "空港車両",
|
||||
"Ground station / obstacle": "地上局 / 障害物",
|
||||
"Airport vehicles": "空港車両",
|
||||
"Ground stations / obstacles": "地上局 / 障害物",
|
||||
"General emergency": "緊急事態",
|
||||
"Unlawful interference": "不法妨害",
|
||||
"Radio failure": "通信機故障",
|
||||
|
||||
@@ -127,6 +127,10 @@
|
||||
"Fast jet": "Jato de alto desempenho",
|
||||
"Business jet": "Jato executivo",
|
||||
"Drone": "Drone",
|
||||
"Airport vehicle": "Veículo de aeroporto",
|
||||
"Ground station / obstacle": "Estação terrestre / obstáculo",
|
||||
"Airport vehicles": "Veículos de aeroporto",
|
||||
"Ground stations / obstacles": "Estações terrestres / obstáculos",
|
||||
"General emergency": "Emergência geral",
|
||||
"Unlawful interference": "Interferência ilícita",
|
||||
"Radio failure": "Falha de rádio",
|
||||
|
||||
@@ -2898,6 +2898,10 @@
|
||||
"Fast jet": "Высокоманёвренный самолёт",
|
||||
"Business jet": "Бизнес-джет",
|
||||
"Drone": "Беспилотник",
|
||||
"Airport vehicle": "Аэродромная машина",
|
||||
"Ground station / obstacle": "Наземная станция / препятствие",
|
||||
"Airport vehicles": "Аэродромные машины",
|
||||
"Ground stations / obstacles": "Наземные станции / препятствия",
|
||||
"fire cause|Human": "деятельность человека",
|
||||
"fire cause|Natural": "природная",
|
||||
"fire cause|Undetermined": "не установлена",
|
||||
|
||||
@@ -982,6 +982,10 @@
|
||||
"Fast jet": "Stridsflygplan",
|
||||
"Business jet": "Affärsjet",
|
||||
"Drone": "Drönare",
|
||||
"Airport vehicle": "Flygplatsfordon",
|
||||
"Ground station / obstacle": "Markstation / hinder",
|
||||
"Airport vehicles": "Flygplatsfordon",
|
||||
"Ground stations / obstacles": "Markstationer / hinder",
|
||||
"General emergency": "Allmänt nödläge",
|
||||
"Unlawful interference": "Olagligt ingripande",
|
||||
"Radio failure": "Radiobortfall",
|
||||
|
||||
@@ -131,6 +131,10 @@
|
||||
"Fast jet": "Швидкісний реактивний літак",
|
||||
"Business jet": "Бізнес-джет",
|
||||
"Drone": "Безпілотник",
|
||||
"Airport vehicle": "Аеродромний автомобіль",
|
||||
"Ground station / obstacle": "Наземна станція / перешкода",
|
||||
"Airport vehicles": "Аеродромні автомобілі",
|
||||
"Ground stations / obstacles": "Наземні станції / перешкоди",
|
||||
"General emergency": "Загальна аварійна ситуація",
|
||||
"Unlawful interference": "Незаконне втручання",
|
||||
"Radio failure": "Відмова радіозвʼязку",
|
||||
|
||||
@@ -119,6 +119,10 @@
|
||||
"Fast jet": "喷气战机",
|
||||
"Business jet": "公务机",
|
||||
"Drone": "无人机",
|
||||
"Airport vehicle": "机场车辆",
|
||||
"Ground station / obstacle": "地面站 / 障碍物",
|
||||
"Airport vehicles": "机场车辆",
|
||||
"Ground stations / obstacles": "地面站 / 障碍物",
|
||||
"General emergency": "一般紧急情况",
|
||||
"Unlawful interference": "非法干扰",
|
||||
"Radio failure": "无线电失效",
|
||||
|
||||
@@ -119,6 +119,10 @@
|
||||
"Fast jet": "噴氣戰機",
|
||||
"Business jet": "公務機",
|
||||
"Drone": "無人機",
|
||||
"Airport vehicle": "機場車輛",
|
||||
"Ground station / obstacle": "地面站 / 障礙物",
|
||||
"Airport vehicles": "機場車輛",
|
||||
"Ground stations / obstacles": "地面站 / 障礙物",
|
||||
"General emergency": "一般緊急情況",
|
||||
"Unlawful interference": "非法干擾",
|
||||
"Radio failure": "無線電失效",
|
||||
|
||||
@@ -27,6 +27,60 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState._lastCamPoseSig = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The contacts drawn now that the first live snapshot after the clock came
|
||||
* back to live lacks (the tracked one too): the snapshot judges them as a
|
||||
* poll judges any absence (see the snapshot renderer).
|
||||
* @param {{records: Array<{id: string}>}} snapshot
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
function absentAtHandover(snapshot) {
|
||||
const present = new Set(snapshot.records.map((record) => record.id));
|
||||
const drawn = [...(flightState._icons?.ids() ?? [])];
|
||||
if (flightState._trackedIcao) drawn.push(flightState._trackedIcao);
|
||||
return new Set(drawn.filter((id) => !present.has(id)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live: forget how every contact moved, as at a jump, but keep the
|
||||
* tracked trail, and keep the contacts `kept` (absentAtHandover) as they
|
||||
* were: their record, fixes and course. Each was last seen at its newest
|
||||
* fix, not when it was loaded, so absence judges how old it really is.
|
||||
* @param {Set<string>} kept
|
||||
*/
|
||||
function handOverMotion(kept) {
|
||||
const held = [];
|
||||
for (const id of kept)
|
||||
held.push([
|
||||
id,
|
||||
flightState.records.data.get(id),
|
||||
flightState._positionHistory.get(id),
|
||||
flightState._displayCourse.get(id),
|
||||
]);
|
||||
forgetPlacedAircraft(
|
||||
services?.placement,
|
||||
[...flightState._positionHistory.keys()].filter((id) => !kept.has(id)),
|
||||
);
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
flightState._displayFloorState.clear();
|
||||
flightState._drReconcileValid = false;
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._cachedDRPosition = null;
|
||||
flightState._lastCamPoseSig = '';
|
||||
for (const [id, meta, history, course] of held) {
|
||||
if (meta)
|
||||
flightState.records.data.set(id, {
|
||||
...meta,
|
||||
observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs,
|
||||
});
|
||||
if (history) flightState._positionHistory.set(id, history);
|
||||
if (course !== undefined) flightState._displayCourse.set(id, course);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every contact: the time has none to show, or the clock went live. */
|
||||
function clear() {
|
||||
if (flightState._trackedIcao)
|
||||
@@ -40,5 +94,5 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState.feed._lastUpdate = null;
|
||||
}
|
||||
|
||||
return { resetMotion, clear };
|
||||
return { resetMotion, absentAtHandover, handOverMotion, clear };
|
||||
}
|
||||
@@ -12,7 +12,10 @@ import { createEvidence } from './evidence.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one civil-flight layer with application-owned scene services. */
|
||||
export function createCivilFlightLayer({
|
||||
@@ -53,10 +56,19 @@ export function createCivilFlightLayer({
|
||||
getQuery: (viewer) =>
|
||||
parts.controller._flightQuery(viewer || flightState._viewer),
|
||||
applySnapshot: (snapshot, viewer, options) => {
|
||||
// At another time the snapshot takes the place of every contact: how
|
||||
// each moved belongs to the time the clock left. Back at live too, but
|
||||
// the contacts it lacks are kept as they were for it to judge.
|
||||
if (options?.replace) parts.clockFollow.resetMotion();
|
||||
if (options?.handover) {
|
||||
parts.clockFollow.handOverMotion(
|
||||
parts.clockFollow.absentAtHandover(snapshot),
|
||||
);
|
||||
}
|
||||
return applySnapshot(snapshot, viewer, options);
|
||||
},
|
||||
followsClock: () => flightState.timeline.active(),
|
||||
timedAnswer: snapshotAnswer,
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
@@ -72,9 +84,7 @@ export function createCivilFlightLayer({
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
|
||||
clear: () => parts.clockFollow.clear(),
|
||||
resumeLive: () => {
|
||||
layer.update(flightState._viewer).catch(() => {});
|
||||
},
|
||||
resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer),
|
||||
});
|
||||
|
||||
Object.assign(
|
||||
|
||||
@@ -12,6 +12,7 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
applyPendingTrackingRestore,
|
||||
followsClock = () => false,
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
@@ -21,13 +22,27 @@ export function createIngestion({
|
||||
await acquire(viewer, { signal });
|
||||
},
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once, and let this live
|
||||
* snapshot stand in for every contact. Those it has keep their
|
||||
* icon and model and move on from where they are drawn; those it lacks
|
||||
* go. Resolves true once it is applied, else false (nothing to poll yet,
|
||||
* or the poll failed); rejects with an AbortError when it was dropped.
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async resumeLive(viewer) {
|
||||
return (await acquire(viewer, { handover: true })) === true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every contact when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* whether it was applied: `{ reachMs }`, the newest fix its records
|
||||
* carry, when they carry fixes; else true, or false when it was not.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
@@ -38,7 +53,10 @@ export function createIngestion({
|
||||
},
|
||||
};
|
||||
|
||||
async function acquire(viewer, { signal = null, atMs, replace = false }) {
|
||||
async function acquire(
|
||||
viewer,
|
||||
{ signal = null, atMs, replace = false, handover = false },
|
||||
) {
|
||||
const nowMs = Date.now();
|
||||
const timed = atMs !== undefined;
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
@@ -85,7 +103,9 @@ export function createIngestion({
|
||||
setSourceLabel(feed._lastSource);
|
||||
const accepted = timed
|
||||
? applySnapshot(snapshot, viewer, { replace })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
: handover
|
||||
? applySnapshot(snapshot, viewer, { handover: true })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
// Freshness belongs to the source snapshot, not the moment this browser
|
||||
// received a cached 200 response.
|
||||
@@ -99,7 +119,8 @@ export function createIngestion({
|
||||
};
|
||||
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
return true;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Flights update aborted', 'AbortError');
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFlightSnapshotRenderer } from './snapshotRenderer.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createFlightFeed, createIngestion } from './ingestion.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
|
||||
// Back at live from another time, the first live snapshot stands in for
|
||||
// every contact: those it has keep their icon and ease on from where they
|
||||
// are drawn, and only those it lacks go (src/time/snapshotTimeline.js).
|
||||
|
||||
/** Any property is a no-op function unless given. */
|
||||
function stub(overrides = {}) {
|
||||
return new Proxy(overrides, {
|
||||
get: (target, key) => (key in target ? target[key] : () => undefined),
|
||||
});
|
||||
}
|
||||
|
||||
function harness() {
|
||||
const iconIds = new Set();
|
||||
const calls = [];
|
||||
const landed = new Set();
|
||||
const groundFloor = stub({
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
GROUND_FLOOR_LIFT_M: 0.5,
|
||||
});
|
||||
const services = stub({
|
||||
geoid: { geoidHeight: () => 0 },
|
||||
camera: stub(),
|
||||
focus: stub(),
|
||||
groundFloor,
|
||||
meshFloor: stub(),
|
||||
groundSnap: stub({ createGroundSnap: () => stub() }),
|
||||
placement: null,
|
||||
});
|
||||
const flightState = createFlightState({
|
||||
services,
|
||||
source: { label: 'Fixture aircraft' },
|
||||
});
|
||||
flightState._icons = {
|
||||
has: (id) => iconIds.has(id),
|
||||
ids: () => [...iconIds],
|
||||
get count() {
|
||||
return iconIds.size;
|
||||
},
|
||||
};
|
||||
const parts = {
|
||||
rendering: stub({ _modelOwnsVisual: () => false }),
|
||||
icons: stub({
|
||||
_addIcon: (id) => {
|
||||
calls.push(['add', id]);
|
||||
iconIds.add(id);
|
||||
},
|
||||
_forgetContact: (id) => {
|
||||
calls.push(['forget', id]);
|
||||
iconIds.delete(id);
|
||||
},
|
||||
_planIcon: (id, options) => calls.push(['plan', id, options]),
|
||||
}),
|
||||
tracking: stub({
|
||||
_militaryLayerSuppresses: () => false,
|
||||
_appendTrailFix: () => calls.push(['trail-append']),
|
||||
_startTrail: (id) => calls.push(['trail-start', id]),
|
||||
_clearTrail: () => calls.push(['trail-clear']),
|
||||
}),
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
const apply = createFlightSnapshotRenderer({
|
||||
flightState,
|
||||
records: flightState.records,
|
||||
militaryRegistry: stub({ isMilitaryIcao: () => false }),
|
||||
groundFloor,
|
||||
rendering: parts.rendering,
|
||||
tracking: parts.tracking,
|
||||
motion: parts.motion,
|
||||
icons: parts.icons,
|
||||
enrichment: stub(),
|
||||
queries: stub({ _likelyLanded: (id) => landed.has(id) }),
|
||||
});
|
||||
const clockFollow = createClockFollow({ flightState, services, parts });
|
||||
return {
|
||||
calls,
|
||||
iconIds,
|
||||
flightState,
|
||||
clockFollow,
|
||||
landed,
|
||||
// `ids`: an id, or [id, fix age ms, on the ground].
|
||||
snapshot: (ids, fields = {}) => ({
|
||||
observedAtMs: Date.now(),
|
||||
records: ids.map((entry, k) => {
|
||||
const [id, ageMs = 5_000, onGround = false] = [entry].flat();
|
||||
return {
|
||||
id,
|
||||
reference: id,
|
||||
longitude: -115 + k,
|
||||
latitude: 36,
|
||||
callsign: 'TEST1',
|
||||
baroAltitudeM: onGround ? 0 : 9_000,
|
||||
onGround,
|
||||
speedMps: onGround ? 5 : 220,
|
||||
courseDeg: 90,
|
||||
positionTimeMs: Date.now() - ageMs,
|
||||
};
|
||||
}),
|
||||
complete: true,
|
||||
...fields,
|
||||
}),
|
||||
apply(ids, options, fields) {
|
||||
calls.length = 0;
|
||||
return apply(this.snapshot(ids, fields), null, options);
|
||||
},
|
||||
// Back at live, as the layer applies its first live snapshot.
|
||||
handOver(ids, fields) {
|
||||
calls.length = 0;
|
||||
const snapshot = this.snapshot(ids, fields);
|
||||
clockFollow.handOverMotion(clockFollow.absentAtHandover(snapshot));
|
||||
return apply(snapshot, null, { handover: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the first live snapshot keeps the icons of contacts it has and drops only those it lacks', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001', 'a00002']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']);
|
||||
|
||||
const accepted = h.handOver(['a00001', 'a00003']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00003']);
|
||||
assert.equal(accepted.count, 2);
|
||||
// The contact it has keeps its icon: no remove and add, and its motion is
|
||||
// planned as a handover, easing from where it is drawn.
|
||||
assert.equal(
|
||||
h.calls.some(
|
||||
([kind, id]) => id === 'a00001' && (kind === 'add' || kind === 'forget'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.calls.find(([kind, id]) => kind === 'plan' && id === 'a00001'),
|
||||
['plan', 'a00001', { handover: true }],
|
||||
);
|
||||
assert.ok(h.calls.some(([kind, id]) => kind === 'forget' && id === 'a00002'));
|
||||
assert.ok(h.calls.some(([kind, id]) => kind === 'add' && id === 'a00003'));
|
||||
});
|
||||
|
||||
test('a plain live poll keeps a missing contact as its absence rules say', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001', 'a00002']);
|
||||
h.apply(['a00001']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']);
|
||||
assert.deepEqual(
|
||||
h.calls.find(([kind]) => kind === 'plan'),
|
||||
['plan', 'a00001', undefined],
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, only the first live snapshot applied takes over; a failed poll says so', async () => {
|
||||
const applied = [];
|
||||
let fail = false;
|
||||
const feed = createFlightFeed({
|
||||
async getSnapshot() {
|
||||
if (fail) throw new Error('down');
|
||||
return { records: [], observedAtMs: Date.now(), freshness: 'current' };
|
||||
},
|
||||
});
|
||||
const { methods } = createIngestion({
|
||||
feed,
|
||||
getQuery: () => ({}),
|
||||
applySnapshot: (_snapshot, _viewer, options) => {
|
||||
applied.push(options);
|
||||
return { count: 0, ids: new Set() };
|
||||
},
|
||||
setSourceLabel: () => {},
|
||||
applyPendingTrackingRestore: () => {},
|
||||
});
|
||||
assert.equal(await methods.resumeLive(null), true);
|
||||
await methods.update(null);
|
||||
assert.deepEqual(applied, [{ handover: true }, undefined]);
|
||||
|
||||
fail = true;
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await methods.resumeLive(null), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live, the tracked contact and those the snapshot retains stay, stale, and a partial snapshot drops none', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001', 'a00002', 'a00003', 'a00004']);
|
||||
h.flightState._trackedIcao = 'a00001';
|
||||
const history = [{ epochMs: Date.now() - 60_000 }];
|
||||
h.flightState._positionHistory.set('a00001', history);
|
||||
h.handOver(['a00004'], { retainIds: new Set(['a00002']) });
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002', 'a00004']);
|
||||
assert.equal(
|
||||
h.flightState._positionHistory.get('a00001'),
|
||||
history,
|
||||
'the tracked contact keeps its fixes for the next poll to judge',
|
||||
);
|
||||
assert.ok(h.flightState.records.data.has('a00001'));
|
||||
assert.equal(
|
||||
h.calls.some(([kind]) => kind === 'trail-clear' || kind === 'trail-start'),
|
||||
false,
|
||||
'its trail goes on',
|
||||
);
|
||||
|
||||
const partial = harness();
|
||||
partial.apply(['a00001', 'a00002']);
|
||||
partial.handOver(['a00003'], { complete: false });
|
||||
assert.deepEqual([...partial.iconIds].sort(), ['a00001', 'a00002', 'a00003']);
|
||||
});
|
||||
|
||||
test('back at live, the tracked contact the snapshot has goes on adding to its trail', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001']);
|
||||
h.flightState._trackedIcao = 'a00001';
|
||||
h.handOver(['a00001']);
|
||||
assert.deepEqual(
|
||||
h.calls.filter(([kind]) => kind.startsWith('trail')),
|
||||
[['trail-append']],
|
||||
);
|
||||
});
|
||||
|
||||
const HOURS_3 = 3 * 3_600_000;
|
||||
|
||||
test('back at live, a partial snapshot keeps only contacts whose newest fix is recent, by the real absence rules', () => {
|
||||
const h = harness();
|
||||
// Shown from a time three hours back, and one from a minute ago.
|
||||
h.apply([
|
||||
['a00001', HOURS_3],
|
||||
['a00002', 60_000],
|
||||
]);
|
||||
h.handOver(['a00003'], { complete: false });
|
||||
assert.deepEqual(
|
||||
[...h.iconIds].sort(),
|
||||
['a00002', 'a00003'],
|
||||
'the three-hour-old contact is no ghost',
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, a tracked aircraft is kept only while its newest fix is recent and it has not landed', () => {
|
||||
for (const [label, setUp, kept] of [
|
||||
['recent', (h) => h.apply([['a00001', 60_000]]), true],
|
||||
['three hours old', (h) => h.apply([['a00001', HOURS_3]]), false],
|
||||
[
|
||||
'landed',
|
||||
(h) => {
|
||||
h.apply([['a00001', 120_000]]);
|
||||
h.apply([['a00001', 60_000, true]]);
|
||||
h.landed.add('a00001');
|
||||
},
|
||||
false,
|
||||
],
|
||||
]) {
|
||||
const h = harness();
|
||||
setUp(h);
|
||||
h.flightState._trackedIcao = 'a00001';
|
||||
h.handOver(['a00002']);
|
||||
assert.equal(h.iconIds.has('a00001'), kept, label);
|
||||
}
|
||||
});
|
||||
@@ -42,7 +42,6 @@ import {
|
||||
limitCourseStep,
|
||||
corridorPathLatLon,
|
||||
} from '../../data/motionModel.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { placeLiveAircraft } from './placed.js';
|
||||
import {
|
||||
modelVisualAnchor,
|
||||
@@ -425,9 +424,7 @@ export function createMotion({
|
||||
const sprite = readEntityRecord(flightState._trackedEntity)?.sprite;
|
||||
const width = sprite?.width ?? 28;
|
||||
const height = sprite?.height ?? 28;
|
||||
const scale =
|
||||
sprite?.scale ??
|
||||
(CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1);
|
||||
const scale = sprite?.scale ?? 1;
|
||||
const scaleByDistance =
|
||||
sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE;
|
||||
const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
|
||||
/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */
|
||||
const rgba = (css, alpha) =>
|
||||
@@ -13,6 +14,10 @@ export const FOCUS_EVIDENCE_DEV = import.meta.env?.DEV === true;
|
||||
|
||||
export const MIL_TINT = rgba('#FFB800');
|
||||
|
||||
/** Amber tint for airport vehicles (type ZVEH, emitter C1/C2), apart from aircraft. */
|
||||
|
||||
export const VEHICLE_TINT = rgba(VEHICLE_TINT_CSS);
|
||||
|
||||
/** Red tint for aircraft broadcasting an emergency (7500/7600/7700 or ADS-B status). */
|
||||
|
||||
export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS);
|
||||
|
||||
@@ -123,9 +123,14 @@ export class FlightRecords {
|
||||
stickyText(callsign, prevMeta?.callsign),
|
||||
);
|
||||
const feedType = observation.typeCode || null;
|
||||
const typeCode =
|
||||
airframe?.typeCode ??
|
||||
(feedType && groundModel(feedType) ? feedType : null);
|
||||
// The feed's type is kept for what it names itself, not for a surface
|
||||
// category: a C1 contact whose feed names an airliner type stays a vehicle.
|
||||
const keepFeedType =
|
||||
Boolean(feedType) &&
|
||||
(groundCategory(category)
|
||||
? GROUND_FEED_TYPES.has(feedType.trim().toUpperCase())
|
||||
: groundModel(feedType));
|
||||
const typeCode = airframe?.typeCode ?? (keepFeedType ? feedType : null);
|
||||
const onGround =
|
||||
on_ground === true ||
|
||||
(!Number.isFinite(baro_alt) &&
|
||||
@@ -280,7 +285,8 @@ export class FlightRecords {
|
||||
const groundFlipped =
|
||||
!!prevMeta && (prevMeta.onGround === true) !== onGround;
|
||||
// Store flight metadata for click-to-track labels
|
||||
const cat = stickyNumber(category, prevMeta?.category, null);
|
||||
// OpenSky's integer category, or a feed's ADS-B emitter category ("C1").
|
||||
const cat = stickyCategory(category, prevMeta?.category);
|
||||
const nextCallsign = stickyText(callsign, prevMeta?.callsign);
|
||||
// A route (and its airline) belongs to the callsign it was looked up for;
|
||||
// a new callsign drops it, so an old flight's route never shows under it.
|
||||
@@ -325,11 +331,9 @@ export class FlightRecords {
|
||||
),
|
||||
courseAnchor: course.anchor,
|
||||
category: cat,
|
||||
// An adsbdb-enriched type code outranks the coarse OpenSky category.
|
||||
klass: classifyAircraft({
|
||||
typeCode: airframe?.typeCode ?? null,
|
||||
category: cat,
|
||||
}),
|
||||
// An adsbdb-enriched type code outranks the coarse OpenSky category;
|
||||
// a feed's own ground type (ZVEH, GRND) classes it from the first fix.
|
||||
klass: classifyAircraft({ typeCode, category: cat }),
|
||||
turnRateDps: prevMeta?.turnRateDps || 0,
|
||||
verticalRate: stickyNumber(vertical_rate, prevMeta?.verticalRate, null),
|
||||
// Analyst seam: OpenSky origin_country (state[2]) — additive, sticky
|
||||
@@ -452,13 +456,46 @@ export class FlightRecords {
|
||||
}
|
||||
}
|
||||
|
||||
/** An ADS-B emitter category as a feed gives it ("A3", "C1"). */
|
||||
const EMITTER_CATEGORY = /^[A-D][0-7]$/;
|
||||
|
||||
/**
|
||||
* A contact's category, kept across polls that omit it: OpenSky's integer
|
||||
* category or an ADS-B emitter category string, else the last one, else null.
|
||||
* @param {*} next
|
||||
* @param {*} prev
|
||||
* @returns {number|string|null}
|
||||
*/
|
||||
function stickyCategory(next, prev) {
|
||||
if (Number.isFinite(next)) return next;
|
||||
const text = typeof next === 'string' ? next.trim().toUpperCase() : '';
|
||||
if (EMITTER_CATEGORY.test(text)) return text;
|
||||
return prev ?? null;
|
||||
}
|
||||
|
||||
/** The types a feed gives airport vehicles (ZVEH) and ground stations (GRND). */
|
||||
const GROUND_FEED_TYPES = new Set(['ZVEH', 'GRND']);
|
||||
|
||||
/** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */
|
||||
const groundModelCaches = new WeakMap();
|
||||
|
||||
/**
|
||||
* Whether an emitter category is a surface one: a vehicle or an obstacle
|
||||
* (ADS-B C1 to C5, OpenSky 16 to 20).
|
||||
* @param {string|number|null} category
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function groundCategory(category) {
|
||||
if (Number.isInteger(category)) return category >= 16 && category <= 20;
|
||||
return typeof category === 'string' && /^C[1-5]$/i.test(category.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an aircraft of this type, emitter category and callsign is drawn
|
||||
* with a model built standing on the ground (catalog category `other`: an
|
||||
* airport vehicle, a ground station's mast). False before the set loads.
|
||||
* airport vehicle, a ground station's mast). A surface emitter category
|
||||
* (C1 to C5, OpenSky 16 to 20) always is. Otherwise, before the set loads,
|
||||
* whether the type is one a feed gives ground vehicles and stations.
|
||||
* Answered once per type, category and callsign rule matched.
|
||||
* @param {object|null} set The loaded fleet model set.
|
||||
* @param {string|null} typeCode
|
||||
@@ -467,7 +504,11 @@ const groundModelCaches = new WeakMap();
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function drawnAsGroundModel(set, typeCode, category, callsign) {
|
||||
if (!set || !typeCode) return false;
|
||||
if (groundCategory(category)) return true;
|
||||
if (!typeCode) return false;
|
||||
// Before the set loads, the feed's own ground types: an airport vehicle
|
||||
// must not be drawn as an aircraft until the set says what it is.
|
||||
if (!set) return GROUND_FEED_TYPES.has(typeCode.trim().toUpperCase());
|
||||
let cache = groundModelCaches.get(set);
|
||||
if (!cache) groundModelCaches.set(set, (cache = new Map()));
|
||||
const rule = aircraftCallsignRule(set.types, typeCode, callsign);
|
||||
|
||||
@@ -312,12 +312,83 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(reported.onGround, false);
|
||||
// Before the model set loads nothing is grounded by its model.
|
||||
const unloaded = records().receive(
|
||||
// Before the model set loads, the feed's ground types already count: an
|
||||
// airport vehicle is never drawn as an aircraft first.
|
||||
const early = records();
|
||||
const unloaded = early.receive(
|
||||
observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(unloaded.onGround, false);
|
||||
assert.equal(unloaded.onGround, true);
|
||||
assert.equal(unloaded.typeCode, 'ZVEH');
|
||||
const earlyPlane = early.receive(
|
||||
observation({ id: 'p2', typeCode: 'A320', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(earlyPlane.onGround, false);
|
||||
assert.equal(earlyPlane.typeCode, null);
|
||||
});
|
||||
|
||||
test('airport vehicles and ground stations take their class from the first fix', () => {
|
||||
// Before the model set loads, and after.
|
||||
for (const store of [records(), records(() => fleetSet)]) {
|
||||
const klass = (fields) =>
|
||||
store.receive(observation({ callsign: '', ...fields }), view()).meta
|
||||
.klass;
|
||||
assert.equal(klass({ id: 'v1', typeCode: 'ZVEH' }), 'vehicle');
|
||||
assert.equal(
|
||||
klass({ id: 'v2', typeCode: 'ZVEH', callsign: 'FIRE 2' }),
|
||||
'vehicle',
|
||||
);
|
||||
assert.equal(klass({ id: 'v3', category: 'C1' }), 'vehicle');
|
||||
assert.equal(klass({ id: 'v4', category: 'C2' }), 'vehicle');
|
||||
assert.equal(klass({ id: 'm1', typeCode: 'GRND' }), 'station');
|
||||
assert.equal(klass({ id: 'm2', category: 'C4' }), 'station');
|
||||
// An aircraft's feed type still waits for the airframe lookup.
|
||||
assert.equal(
|
||||
klass({ id: 'p1', typeCode: 'A320', category: 'A7' }),
|
||||
'helicopter',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a surface emitter category stands on the ground, before and after the model set loads', () => {
|
||||
const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null };
|
||||
for (const store of [records(), records(() => fleetSet)]) {
|
||||
for (const [id, category] of [
|
||||
['c1', 'C1'],
|
||||
['c2', 'C2'],
|
||||
['c3', 'C3'],
|
||||
['c5', 'C5'],
|
||||
['o16', 16],
|
||||
['o20', 20],
|
||||
]) {
|
||||
const meta = store.receive(
|
||||
observation({ id, category, callsign: '', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(meta.onGround, true, `${id} stands on the ground`);
|
||||
assert.equal(meta.altitude, 0, id);
|
||||
}
|
||||
// An aircraft category with no altitude keeps the airborne default.
|
||||
const plane = store.receive(
|
||||
observation({ id: 'a3', category: 'A3', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(plane.onGround, false);
|
||||
// A feed's aircraft type on a surface category does not make it an aircraft.
|
||||
const odd = store.receive(
|
||||
observation({
|
||||
id: 'c9',
|
||||
category: 'C1',
|
||||
typeCode: 'A320',
|
||||
...noAltitude,
|
||||
}),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(odd.klass, 'vehicle');
|
||||
assert.equal(odd.onGround, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('a contact reported with no course faces the way its newer fixes went', () => {
|
||||
|
||||
@@ -2,11 +2,11 @@ import {
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
} from './modelSpec.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { isEmergency } from '../../data/aircraftEmergency.js';
|
||||
import {
|
||||
MIL_TINT,
|
||||
EMERGENCY_TINT,
|
||||
VEHICLE_TINT,
|
||||
FLEET_TINT,
|
||||
TRACKED_CYAN,
|
||||
GROUND_SCALE,
|
||||
@@ -32,14 +32,16 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/** Fleet (untracked) billboard tint: red while broadcasting an emergency,
|
||||
* amber for known-military, white otherwise.
|
||||
* Ground traffic gets NO special tint (owner verdict 2026-07-03 field test). */
|
||||
* orange amber for an airport vehicle, amber for known-military, white
|
||||
* otherwise. Grounded aircraft get NO special tint (owner verdict
|
||||
* 2026-07-03 field test). */
|
||||
|
||||
function _fleetBillboardColor(
|
||||
icao24,
|
||||
info = flightState.records.data.get(icao24),
|
||||
) {
|
||||
if (_isEmergency(icao24, info)) return EMERGENCY_TINT;
|
||||
if (info?.klass === 'vehicle') return VEHICLE_TINT;
|
||||
return isMilitaryIcao(icao24) ? MIL_TINT : FLEET_TINT;
|
||||
}
|
||||
|
||||
@@ -53,13 +55,10 @@ export function createRendering({
|
||||
return isMilitaryIcao(icao24) ? MIL_TINT : COCKPIT_CIVILIAN_COLOR;
|
||||
}
|
||||
|
||||
/** Fleet billboard scale: per-class scale, ×GROUND_SCALE while grounded. */
|
||||
/** Fleet billboard scale: one size for every class, ×GROUND_SCALE while grounded. */
|
||||
|
||||
function _fleetBillboardScale(icao24, klass) {
|
||||
return (
|
||||
(CLASS_SCALE_2D[klass] || 1) *
|
||||
(flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1)
|
||||
);
|
||||
function _fleetBillboardScale(icao24) {
|
||||
return flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1;
|
||||
}
|
||||
|
||||
/** The fleet model an aircraft draws with, by its type and emitter category. */
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// src/layers/flights/rendering.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { createRendering as createFlightsRendering } from './rendering.js';
|
||||
import { createRendering as createMilitaryRendering } from '../military/rendering.js';
|
||||
|
||||
function rendering(create) {
|
||||
const data = new Map([
|
||||
['light', { klass: 'light' }],
|
||||
['quadjet', { klass: 'quadjet' }],
|
||||
['vehicle', { klass: 'vehicle' }],
|
||||
['parked', { klass: 'quadjet', onGround: true }],
|
||||
]);
|
||||
return create({
|
||||
flightState: { records: { data } },
|
||||
services: {
|
||||
militaryRegistry: { isMilitaryIcao: () => false },
|
||||
aircraftPresentation: { tr3bIconKind: () => null },
|
||||
focus: { focusNowMs: () => 0, getFocusTarget: () => null },
|
||||
},
|
||||
parts: {},
|
||||
layer: {},
|
||||
resolveAsset: (url) => url,
|
||||
});
|
||||
}
|
||||
|
||||
test('Flights draws every class at one size, smaller on the ground', () => {
|
||||
const r = rendering(createFlightsRendering);
|
||||
for (const id of ['light', 'quadjet', 'vehicle']) {
|
||||
assert.equal(r._fleetBillboardScale(id), 1, id);
|
||||
}
|
||||
assert.equal(r._fleetBillboardScale('parked'), 0.8);
|
||||
});
|
||||
|
||||
test('Military draws every class at its one size, smaller on the ground', () => {
|
||||
const r = rendering(createMilitaryRendering);
|
||||
const size = r._fleetBillboardScale('light');
|
||||
for (const id of ['quadjet', 'vehicle']) {
|
||||
assert.equal(r._fleetBillboardScale(id), size, id);
|
||||
}
|
||||
assert.ok(Math.abs(r._fleetBillboardScale('parked') - size * 0.8) < 1e-12);
|
||||
});
|
||||
@@ -56,8 +56,16 @@ export function createFlightSnapshotRenderer({
|
||||
/**
|
||||
* `replace`: the snapshot is the world at another time (the world clock
|
||||
* jumped), so it stands in for every contact: one it lacks is gone at once.
|
||||
* `handover`: the first live snapshot after the clock came back to live: it
|
||||
* stands in for every contact too, and those it has keep their icon and
|
||||
* model and ease on from where they are drawn; of those it lacks, only
|
||||
* those absence keeps (judged by their newest fix) stay.
|
||||
*/
|
||||
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
|
||||
return function applySnapshot(
|
||||
snapshot,
|
||||
viewer,
|
||||
{ replace = false, handover = false } = {},
|
||||
) {
|
||||
// Before init (or after destroy) there is no icon set to draw into.
|
||||
if (!flightState._icons) return { count: 0, ids: new Set() };
|
||||
const currentIcaos = new Set();
|
||||
@@ -254,7 +262,7 @@ export function createFlightSnapshotRenderer({
|
||||
// freshness change and the cockpit contract all land on the row's
|
||||
// style; motion re-plans from the updated history.
|
||||
icons._applyIconPresentation(icao24);
|
||||
icons._planIcon(icao24);
|
||||
icons._planIcon(icao24, handover ? { handover } : undefined);
|
||||
// Poll-path type or category change: same model resync rule as the
|
||||
// enrichment path — the fleet model or its scale may have changed.
|
||||
if (
|
||||
@@ -294,6 +302,23 @@ export function createFlightSnapshotRenderer({
|
||||
// EXCEPTION: likely-landed planes (last fix low + slow) get only
|
||||
// LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a
|
||||
// feed gap, and the full grace left phantom planes parked at airports.
|
||||
// Back at live, a contact it lacks is from the time the clock left: it
|
||||
// goes at once, unless absence keeps it as any poll would (a partial or
|
||||
// retaining snapshot, the tracked aircraft), judged by its newest fix.
|
||||
// No missed-poll grace, and a landed tracked aircraft is not kept.
|
||||
const absenceAtHandover = (icao24) => {
|
||||
const likelyLanded = queries._likelyLanded(icao24);
|
||||
const judged = records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded,
|
||||
tracked: icao24 === flightState._trackedIcao && !likelyLanded,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
return judged === 'stale' && icao24 !== flightState._trackedIcao
|
||||
? 'remove'
|
||||
: judged;
|
||||
};
|
||||
const absentIds = [];
|
||||
for (const icao24 of flightState._icons.ids()) {
|
||||
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
|
||||
@@ -301,13 +326,15 @@ export function createFlightSnapshotRenderer({
|
||||
for (const icao24 of absentIds) {
|
||||
const absence = replace
|
||||
? 'remove'
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
: handover
|
||||
? absenceAtHandover(icao24)
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
if (absence === 'retain') continue;
|
||||
if (absence === 'stale') {
|
||||
icons._applyIconPresentation(icao24); // the faded freshness alpha
|
||||
@@ -334,7 +361,8 @@ export function createFlightSnapshotRenderer({
|
||||
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
|
||||
}
|
||||
|
||||
// The tracked contact at the new time: its trail starts there.
|
||||
// The tracked contact at the new time: its trail starts there. Back at
|
||||
// live its trail goes on.
|
||||
if (
|
||||
replace &&
|
||||
flightState._trackedIcao &&
|
||||
|
||||
@@ -912,10 +912,7 @@ export function createTracking({
|
||||
width: look.size[0],
|
||||
height: look.size[1],
|
||||
get scale() {
|
||||
return parts.rendering._fleetBillboardScale(
|
||||
icao24,
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
);
|
||||
return parts.rendering._fleetBillboardScale(icao24);
|
||||
},
|
||||
scaleByDistance: look.scaleByDistance,
|
||||
};
|
||||
@@ -1092,6 +1089,8 @@ export function createTracking({
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
// A ground station's mast stands upright.
|
||||
if (tracked.klass === 'station') return 0;
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
|
||||
@@ -24,7 +24,8 @@ export function localAdsbClass(record, meta = null) {
|
||||
const category = record?.category || null;
|
||||
return {
|
||||
klass: classifyAircraft({ typeCode, category }),
|
||||
evidence: Boolean(typeCode) || /^(?:A[1-7]|B1)$/.test(category || ''),
|
||||
evidence:
|
||||
Boolean(typeCode) || /^(?:A[1-7]|B1|C[1-5])$/.test(category || ''),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
import { aircraftIcon } from '../../data/aircraftIcons.js';
|
||||
import { rotorFrame } from '../../data/rotorFrames.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
import {
|
||||
courseScreenRotation,
|
||||
stabilizeScreenRotation,
|
||||
@@ -133,6 +135,8 @@ export function createLocalAdsbLayer({
|
||||
} = services.context;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const color = hexColor(LOCAL_ADSB_COLOR);
|
||||
// An airport vehicle's tint, as in the Flights layer.
|
||||
const vehicleColor = hexColor(VEHICLE_TINT_CSS);
|
||||
const uatRingColor = hexColor(LOCAL_ADSB_UAT_RING_COLOR);
|
||||
|
||||
let viewer = null;
|
||||
@@ -265,9 +269,7 @@ export function createLocalAdsbLayer({
|
||||
}
|
||||
|
||||
function billboardScale(marker) {
|
||||
return (
|
||||
(CLASS_SCALE_2D[marker.klass] || 1) * (marker.onGround ? GROUND_SCALE : 1)
|
||||
);
|
||||
return marker.onGround ? GROUND_SCALE : 1;
|
||||
}
|
||||
|
||||
/** Class silhouette and per-class scale (×0.8 on the ground), magenta. */
|
||||
@@ -350,18 +352,34 @@ export function createLocalAdsbLayer({
|
||||
};
|
||||
}
|
||||
|
||||
/** A marker's icon, where and how it now draws. */
|
||||
function markerItem(marker, basis) {
|
||||
/**
|
||||
* A marker's icon, where and how it now draws: a helicopter's rotor frame
|
||||
* at `at` (still on the ground), an airport vehicle in its own tint, a
|
||||
* ground station's mast upright.
|
||||
*/
|
||||
function markerItem(marker, basis, at) {
|
||||
const kind = marker.iconKind ?? 'airliner';
|
||||
return {
|
||||
id: marker.id,
|
||||
pos: marker.position,
|
||||
image: aircraftIcon(marker.iconKind ?? 'airliner'),
|
||||
image: aircraftIcon(
|
||||
kind,
|
||||
undefined,
|
||||
kind === 'helicopter'
|
||||
? rotorFrame(marker.id, at, {
|
||||
onGround: marker.onGround,
|
||||
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
|
||||
? marker.record.groundSpeedKt * KNOT_MPS
|
||||
: null,
|
||||
})
|
||||
: undefined,
|
||||
),
|
||||
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
|
||||
scale: marker.iconScale ?? 1,
|
||||
color,
|
||||
color: kind === 'vehicle' ? vehicleColor : color,
|
||||
scaleByDistance: MARKER_SPRITE.scaleByDistance,
|
||||
rotationMode: 'screen',
|
||||
rotation: markerRotation(marker, basis),
|
||||
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
|
||||
// The 3D model, once loaded and placed, is the visual instead.
|
||||
show: !marker.modelOwnsVisual,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
@@ -390,11 +408,12 @@ export function createLocalAdsbLayer({
|
||||
function drawMarkers() {
|
||||
if (!sets) return;
|
||||
const basis = cameraBasis();
|
||||
const at = now();
|
||||
const icons = [];
|
||||
const rings = [];
|
||||
for (const marker of markers.values()) {
|
||||
if (!marker.position) continue;
|
||||
icons.push(markerItem(marker, basis));
|
||||
icons.push(markerItem(marker, basis, at));
|
||||
if (marker.uat) rings.push(ringItem(marker));
|
||||
}
|
||||
if (icons.length) sets.markers.upsert(icons);
|
||||
|
||||
@@ -2,9 +2,10 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { aircraftIcon } from '../../data/aircraftIcons.js';
|
||||
import { ROTOR_STILL_FRAME, rotorFrame } from '../../data/rotorFrames.js';
|
||||
import {
|
||||
createLocalAdsbLayer,
|
||||
HEARD_BY_RECEIVER,
|
||||
@@ -238,7 +239,7 @@ test('enabling Local ADS-B asks the shared tuner for 1090 MHz; disabling leaves
|
||||
);
|
||||
});
|
||||
|
||||
test('local aircraft use their class silhouette and scale in magenta', async (t) => {
|
||||
test('local aircraft use their class silhouette at one size in magenta', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
const { layer, draw, calls } = await enabledLayer(receiver, clock);
|
||||
@@ -265,8 +266,17 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
|
||||
assert.equal(typeof readEntityRecord(carrier)?.displayPosition, 'function');
|
||||
|
||||
const heli = () => iconOf(draw, 'local-adsb:a0b702');
|
||||
assert.equal(heli().image, aircraftIcon('helicopter'));
|
||||
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter);
|
||||
// Airborne, its rotor turns: the frame of its own phase at the layer's time.
|
||||
assert.equal(
|
||||
heli().image,
|
||||
aircraftIcon(
|
||||
'helicopter',
|
||||
undefined,
|
||||
rotorFrame('local-adsb:a0b702', clock.now),
|
||||
),
|
||||
);
|
||||
assert.equal(heli().scale, 1, 'every class draws at one size');
|
||||
assert.equal(icon.scale, heli().scale);
|
||||
assert.deepEqual(
|
||||
heli().color,
|
||||
MAGENTA,
|
||||
@@ -285,18 +295,48 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
|
||||
icao: 'a0b702',
|
||||
category: 'A7',
|
||||
onGround: true,
|
||||
groundSpeedKt: 0,
|
||||
lastPositionAt: 100_500,
|
||||
}),
|
||||
],
|
||||
});
|
||||
await layer.update();
|
||||
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter * 0.8);
|
||||
assert.equal(heli().scale, 0.8);
|
||||
// Parked on the ground its rotor holds still.
|
||||
assert.equal(
|
||||
heli().image,
|
||||
aircraftIcon('helicopter', undefined, ROTOR_STILL_FRAME),
|
||||
);
|
||||
|
||||
const [detectable] = layer.getDetectableObjects();
|
||||
assert.equal(detectable.sourceId, 'a0b702');
|
||||
assert.equal(detectable.type, 'AIR');
|
||||
});
|
||||
|
||||
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
const { layer, draw } = await enabledLayer(receiver, clock);
|
||||
t.after(() => layer.destroy());
|
||||
receiver.set({
|
||||
aircraft: [
|
||||
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
|
||||
record({ icao: 'a0c002', category: 'C2', trackDeg: 90 }),
|
||||
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
|
||||
],
|
||||
});
|
||||
await layer.update();
|
||||
for (const id of ['a0c001', 'a0c002']) {
|
||||
const icon = iconOf(draw, `local-adsb:${id}`);
|
||||
assert.equal(icon.image, aircraftIcon('vehicle'), id);
|
||||
assert.deepEqual(icon.color, hexColor(VEHICLE_TINT_CSS), id);
|
||||
}
|
||||
const mast = iconOf(draw, 'local-adsb:a0c003');
|
||||
assert.equal(mast.image, aircraftIcon('station'));
|
||||
assert.deepEqual(mast.color, MAGENTA);
|
||||
assert.equal(mast.rotation, 0, 'upright whatever its track');
|
||||
});
|
||||
|
||||
test('the heading slews toward a new track instead of snapping', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
|
||||
@@ -8,7 +8,13 @@ import {
|
||||
sub,
|
||||
} from '../../geo/vector.js';
|
||||
import { aircraftLayerModelSpec } from '../flights/modelSpec.js';
|
||||
import { fleetModelSet, loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
import {
|
||||
fleetModelSet,
|
||||
fleetPartTable,
|
||||
loadFleetModelSet,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { aircraftLayerPartState } from '../../data/modelPartDrivers.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
import {
|
||||
FLEET_DR_INTERVAL_MS,
|
||||
MODEL_ALL_ADD_M,
|
||||
@@ -165,6 +171,36 @@ export function createLocalAdsbModels({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The moving parts an aircraft's model is posed with, from its record
|
||||
* (`aircraftLayerPartState`). The receiver knows no ground height, so its gear
|
||||
* follows the approach rule by its reported altitude, climb and speed. An
|
||||
* airport vehicle is a road vehicle (`groundVehiclePartState`): its wheels
|
||||
* roll with its speed.
|
||||
*/
|
||||
function partsOf(marker, spec) {
|
||||
const table = fleetPartTable(fleetModelSet(), spec.model);
|
||||
if (!table) return undefined;
|
||||
const record = marker.record ?? {};
|
||||
const finite = (v) => (Number.isFinite(v) ? v : null);
|
||||
const speedMps =
|
||||
finite(record.groundSpeedKt) === null
|
||||
? null
|
||||
: record.groundSpeedKt * KNOT_MPS;
|
||||
return aircraftLayerPartState(table, {
|
||||
klass: marker.klass,
|
||||
onGround: marker.onGround === true,
|
||||
heightAboveGroundM: null,
|
||||
altitudeM:
|
||||
finite(record.altitudeFt) === null ? null : record.altitudeFt * 0.3048,
|
||||
verticalRateMps:
|
||||
finite(record.verticalRateFpm) === null
|
||||
? null
|
||||
: (record.verticalRateFpm * 0.3048) / 60,
|
||||
speedMps,
|
||||
});
|
||||
}
|
||||
|
||||
function regime(preferences, pose) {
|
||||
if (!preferences?.models3d) return false;
|
||||
return pose.height < MODEL_ALT_CEIL_M;
|
||||
@@ -246,6 +282,7 @@ export function createLocalAdsbModels({
|
||||
const gltf = fleetModelSet()?.bytes?.get(spec.model);
|
||||
noteAsset(record, url, spec.bellyM);
|
||||
const position = placement(id, marker);
|
||||
const parts = partsOf(marker, spec);
|
||||
const shown =
|
||||
Boolean(position) && horizon.isPointVisible(marker.position);
|
||||
items.push({
|
||||
@@ -268,6 +305,7 @@ export function createLocalAdsbModels({
|
||||
tint: WHITE,
|
||||
colorBlend: aircraftModelBlend(false),
|
||||
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
|
||||
...(parts ? { parts } : {}),
|
||||
show: shown,
|
||||
});
|
||||
if (shown && record.ready) marker.modelOwnsVisual = true;
|
||||
|
||||
@@ -26,6 +26,59 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState._lastCamPoseSig = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The contacts drawn now that the first live snapshot after the clock came
|
||||
* back to live lacks (the tracked one too): the snapshot judges them as a
|
||||
* poll judges any absence (see the snapshot renderer).
|
||||
* @param {{records: Array<{id: string}>}} snapshot
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
function absentAtHandover(snapshot) {
|
||||
const present = new Set(snapshot.records.map((record) => record.id));
|
||||
const drawn = [...(flightState._icons?.ids() ?? [])];
|
||||
if (flightState._trackedIcao) drawn.push(flightState._trackedIcao);
|
||||
return new Set(drawn.filter((id) => !present.has(id)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live: forget how every contact moved, as at a jump, but keep the
|
||||
* tracked trail, and keep the contacts `kept` (absentAtHandover) as they
|
||||
* were: their record, fixes and course. Each was last seen at its newest
|
||||
* fix, not when it was loaded, so absence judges how old it really is.
|
||||
* @param {Set<string>} kept
|
||||
*/
|
||||
function handOverMotion(kept) {
|
||||
const held = [];
|
||||
for (const id of kept)
|
||||
held.push([
|
||||
id,
|
||||
flightState.records.data.get(id),
|
||||
flightState._positionHistory.get(id),
|
||||
flightState._displayCourse.get(id),
|
||||
]);
|
||||
forgetPlacedAircraft(
|
||||
services?.placement,
|
||||
[...flightState._positionHistory.keys()].filter((id) => !kept.has(id)),
|
||||
);
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
flightState._drReconcileValid = false;
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._cachedDRPosition = null;
|
||||
flightState._lastCamPoseSig = '';
|
||||
for (const [id, meta, history, course] of held) {
|
||||
if (meta)
|
||||
flightState.records.data.set(id, {
|
||||
...meta,
|
||||
observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs,
|
||||
});
|
||||
if (history) flightState._positionHistory.set(id, history);
|
||||
if (course !== undefined) flightState._displayCourse.set(id, course);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every contact: the time has none to show, or the clock went live. */
|
||||
function clear() {
|
||||
if (flightState._trackedIcao)
|
||||
@@ -39,5 +92,5 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState.feed._lastUpdate = null;
|
||||
}
|
||||
|
||||
return { resetMotion, clear };
|
||||
return { resetMotion, absentAtHandover, handOverMotion, clear };
|
||||
}
|
||||
@@ -10,7 +10,10 @@ import { createLifecycle } from './lifecycle.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one military-flight layer with application-owned scene services. */
|
||||
export function createMilitaryFlightLayer({
|
||||
@@ -46,10 +49,19 @@ export function createMilitaryFlightLayer({
|
||||
parts.ingestion = createIngestion({
|
||||
feed: flightState.feed,
|
||||
applySnapshot: (snapshot, viewer, options) => {
|
||||
// At another time the snapshot takes the place of every contact: how
|
||||
// each moved belongs to the time the clock left. Back at live too, but
|
||||
// the contacts it lacks are kept as they were for it to judge.
|
||||
if (options?.replace) parts.clockFollow.resetMotion();
|
||||
if (options?.handover) {
|
||||
parts.clockFollow.handOverMotion(
|
||||
parts.clockFollow.absentAtHandover(snapshot),
|
||||
);
|
||||
}
|
||||
return applySnapshot(snapshot, viewer, options);
|
||||
},
|
||||
followsClock: () => flightState.timeline.active(),
|
||||
timedAnswer: snapshotAnswer,
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
@@ -65,9 +77,7 @@ export function createMilitaryFlightLayer({
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
|
||||
clear: () => parts.clockFollow.clear(),
|
||||
resumeLive: () => {
|
||||
layer.update(flightState._viewer).catch(() => {});
|
||||
},
|
||||
resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer),
|
||||
});
|
||||
|
||||
Object.assign(
|
||||
|
||||
@@ -11,6 +11,7 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
applyPendingTrackingRestore,
|
||||
followsClock = () => false,
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
@@ -20,13 +21,27 @@ export function createIngestion({
|
||||
await acquire(viewer, { signal });
|
||||
},
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once, and let this live
|
||||
* snapshot stand in for every contact. Those it has keep their
|
||||
* icon and model and move on from where they are drawn; those it lacks
|
||||
* go. Resolves true once it is applied, else false (nothing to poll yet,
|
||||
* or the poll failed); rejects with an AbortError when it was dropped.
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async resumeLive(viewer) {
|
||||
return (await acquire(viewer, { handover: true })) === true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every contact when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* whether it was applied: `{ reachMs }`, the newest fix its records
|
||||
* carry, when they carry fixes; else true, or false when it was not.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
@@ -37,7 +52,10 @@ export function createIngestion({
|
||||
},
|
||||
};
|
||||
|
||||
async function acquire(viewer, { signal = null, atMs, replace = false }) {
|
||||
async function acquire(
|
||||
viewer,
|
||||
{ signal = null, atMs, replace = false, handover = false },
|
||||
) {
|
||||
const nowMs = Date.now();
|
||||
const timed = atMs !== undefined;
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
@@ -77,7 +95,9 @@ export function createIngestion({
|
||||
: null);
|
||||
const accepted = timed
|
||||
? applySnapshot(snapshot, viewer, { replace })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
: handover
|
||||
? applySnapshot(snapshot, viewer, { handover: true })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
feed._lastUpdate = snapshot.observedAtMs;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
@@ -88,7 +108,8 @@ export function createIngestion({
|
||||
};
|
||||
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
return true;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Military update aborted', 'AbortError');
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createMilitarySnapshotRenderer } from './snapshotRenderer.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createIngestion, createMilitaryFeed } from './ingestion.js';
|
||||
import { MilitaryFlightRecords } from './records.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
|
||||
// Back at live from another time, the first live snapshot stands in for
|
||||
// every military contact: those it has keep their icon, and only those it
|
||||
// lacks go (src/time/snapshotTimeline.js).
|
||||
|
||||
function harness() {
|
||||
const iconIds = new Set();
|
||||
const calls = [];
|
||||
const flightState = {
|
||||
_viewer: null,
|
||||
_icons: {
|
||||
has: (id) => iconIds.has(id),
|
||||
ids: () => [...iconIds],
|
||||
get count() {
|
||||
return iconIds.size;
|
||||
},
|
||||
},
|
||||
_positionHistory: new Map(),
|
||||
_groundSnap: { forget() {} },
|
||||
_models: new Map(),
|
||||
_trackedModel: null,
|
||||
_trackedIcao: null,
|
||||
records: { data: new Map() },
|
||||
};
|
||||
const parts = {
|
||||
rendering: {
|
||||
_modelOwnsVisual: () => false,
|
||||
_syncModelToClass() {},
|
||||
_groundSampleExclusions: () => ({ sets: [] }),
|
||||
},
|
||||
icons: {
|
||||
_addIcon: (id) => {
|
||||
calls.push(['add', id]);
|
||||
iconIds.add(id);
|
||||
},
|
||||
_applyIconPresentation() {},
|
||||
_planIcon: (id, options) => calls.push(['plan', id, options]),
|
||||
_forgetContact: (id) => {
|
||||
calls.push(['forget', id]);
|
||||
iconIds.delete(id);
|
||||
},
|
||||
},
|
||||
};
|
||||
const services = {
|
||||
camera: { trackedModelScaleForPixelCap: () => 1 },
|
||||
focus: {},
|
||||
groundFloor: { cachedGroundFloor: () => null, GROUND_FLOOR_LIFT_M: 0.5 },
|
||||
meshFloor: { sampleMeshFloorCells() {} },
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
const records = new MilitaryFlightRecords({
|
||||
geoidHeight: () => 0,
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
now: () => Date.now(),
|
||||
});
|
||||
flightState.records = records;
|
||||
flightState.now = () => Date.now();
|
||||
flightState._displayCourse = new Map();
|
||||
flightState._groundSnap.clear = () => {};
|
||||
const apply = createMilitarySnapshotRenderer({
|
||||
flightState,
|
||||
records,
|
||||
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null },
|
||||
militaryRegistry: { registerMilitaryIcaos() {} },
|
||||
rendering: parts.rendering,
|
||||
tracking: {},
|
||||
motion: parts.motion,
|
||||
icons: parts.icons,
|
||||
queries: { _likelyLanded: () => false },
|
||||
});
|
||||
const clockFollow = createClockFollow({
|
||||
flightState,
|
||||
services: { placement: null },
|
||||
parts: { tracking: { _clearTrail() {} } },
|
||||
});
|
||||
// `ids`: an id, or [id, fix age ms].
|
||||
const snapshot = (ids, fields) => ({
|
||||
observedAtMs: Date.now(),
|
||||
records: ids.map((entry, k) => {
|
||||
const [id, ageMs = 5_000] = [entry].flat();
|
||||
return {
|
||||
id,
|
||||
reference: id,
|
||||
longitude: -97 + k,
|
||||
latitude: 30,
|
||||
baroAltitudeM: 3_000,
|
||||
onGround: false,
|
||||
speedMps: 200,
|
||||
courseDeg: 90,
|
||||
positionTimeMs: Date.now() - ageMs,
|
||||
};
|
||||
}),
|
||||
complete: true,
|
||||
...fields,
|
||||
});
|
||||
return {
|
||||
calls,
|
||||
iconIds,
|
||||
apply(ids, options, fields) {
|
||||
calls.length = 0;
|
||||
return apply(snapshot(ids, fields), null, options);
|
||||
},
|
||||
// Back at live, as the layer applies its first live snapshot.
|
||||
handOver(ids, fields) {
|
||||
calls.length = 0;
|
||||
const live = snapshot(ids, fields);
|
||||
clockFollow.handOverMotion(clockFollow.absentAtHandover(live));
|
||||
return apply(live, null, { handover: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the first live military snapshot keeps the icons of contacts it has and drops only those it lacks', () => {
|
||||
const h = harness();
|
||||
h.apply(['ae0001', 'ae0002']);
|
||||
h.handOver(['ae0001', 'ae0003']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']);
|
||||
assert.equal(
|
||||
h.calls.some(
|
||||
([kind, id]) => id === 'ae0001' && (kind === 'add' || kind === 'forget'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.calls.find(([kind, id]) => kind === 'plan' && id === 'ae0001'),
|
||||
['plan', 'ae0001', { handover: true }],
|
||||
);
|
||||
// A plain poll keeps a missing contact as its absence rules say.
|
||||
h.apply(['ae0001']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']);
|
||||
});
|
||||
|
||||
test('back at live, only the first live military snapshot applied takes over; a failed poll says so', async () => {
|
||||
const applied = [];
|
||||
let fail = false;
|
||||
const feed = createMilitaryFeed({
|
||||
async getSnapshot() {
|
||||
if (fail) throw new Error('down');
|
||||
return { records: [], observedAtMs: Date.now(), freshness: 'current' };
|
||||
},
|
||||
});
|
||||
const { methods } = createIngestion({
|
||||
feed,
|
||||
applySnapshot: (_snapshot, _viewer, options) => {
|
||||
applied.push(options);
|
||||
return { count: 0, ids: new Set() };
|
||||
},
|
||||
setSourceLabel: () => {},
|
||||
applyPendingTrackingRestore: () => {},
|
||||
});
|
||||
assert.equal(await methods.resumeLive(null), true);
|
||||
await methods.update(null);
|
||||
assert.deepEqual(applied, [{ handover: true }, undefined]);
|
||||
fail = true;
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await methods.resumeLive(null), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live, a partial military snapshot keeps only contacts whose newest fix is recent', () => {
|
||||
const h = harness();
|
||||
h.apply([
|
||||
['ae0001', 3 * 3_600_000],
|
||||
['ae0002', 60_000],
|
||||
]);
|
||||
h.handOver(['ae0003'], { complete: false });
|
||||
assert.deepEqual([...h.iconIds].sort(), ['ae0002', 'ae0003']);
|
||||
});
|
||||
@@ -35,7 +35,6 @@ import {
|
||||
recoveryMs,
|
||||
limitCourseStep,
|
||||
} from '../../data/motionModel.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { placeLiveAircraft } from '../flights/placed.js';
|
||||
import {
|
||||
modelVisualAnchor,
|
||||
@@ -322,10 +321,7 @@ export function createMotion({
|
||||
const sprite = readEntityRecord(flightState._trackedEntity)?.sprite;
|
||||
const width = sprite?.width ?? 28;
|
||||
const height = sprite?.height ?? 28;
|
||||
const scale =
|
||||
sprite?.scale ??
|
||||
BILLBOARD_SCALE *
|
||||
(CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1);
|
||||
const scale = sprite?.scale ?? BILLBOARD_SCALE;
|
||||
const scaleByDistance =
|
||||
sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE;
|
||||
const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import {
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
@@ -41,15 +40,11 @@ export function createRendering({
|
||||
return spec;
|
||||
}
|
||||
|
||||
/** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */
|
||||
/** Fleet icon scale: one size for every class, ×GROUND_SCALE while grounded. */
|
||||
|
||||
function _fleetBillboardScale(icao24) {
|
||||
const meta = flightState.records.data.get(icao24);
|
||||
return (
|
||||
BILLBOARD_SCALE *
|
||||
(CLASS_SCALE_2D[meta?.klass] || 1) *
|
||||
(meta?.onGround ? GROUND_SCALE : 1)
|
||||
);
|
||||
return BILLBOARD_SCALE * (meta?.onGround ? GROUND_SCALE : 1);
|
||||
}
|
||||
|
||||
/** Sprite kind for one contact's icon. Identity for every aircraft except
|
||||
|
||||
@@ -55,8 +55,16 @@ export function createMilitarySnapshotRenderer({
|
||||
/**
|
||||
* `replace`: the snapshot is the world at another time (the world clock
|
||||
* jumped), so it stands in for every contact: one it lacks is gone at once.
|
||||
* `handover`: the first live snapshot after the clock came back to live: it
|
||||
* stands in for every contact too, and those it has keep their icon and
|
||||
* model and ease on from where they are drawn; of those it lacks, only
|
||||
* those absence keeps (judged by their newest fix) stay.
|
||||
*/
|
||||
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
|
||||
return function applySnapshot(
|
||||
snapshot,
|
||||
viewer,
|
||||
{ replace = false, handover = false } = {},
|
||||
) {
|
||||
// Before init (or after destroy) there is no icon set to draw into.
|
||||
if (!flightState._icons) return { count: 0, ids: new Set() };
|
||||
const currentIcaos = new Set();
|
||||
@@ -223,7 +231,7 @@ export function createMilitarySnapshotRenderer({
|
||||
// freshness change and the cockpit contract all land on the row's
|
||||
// style; motion re-plans from the updated history.
|
||||
icons._applyIconPresentation(icao24);
|
||||
icons._planIcon(icao24);
|
||||
icons._planIcon(icao24, handover ? { handover } : undefined);
|
||||
// Per-type fleet models: a type or category change can mean a
|
||||
// different model OR scale — resync the live model, any in-flight
|
||||
// load, and the tracked standalone (mirror of flights.js).
|
||||
@@ -279,6 +287,23 @@ export function createMilitarySnapshotRenderer({
|
||||
// EXCEPTION: likely-landed planes (last fix low + slow) get only
|
||||
// LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a
|
||||
// feed gap, and the full grace left phantom planes parked at airports.
|
||||
// Back at live, a contact it lacks is from the time the clock left: it
|
||||
// goes at once, unless absence keeps it as any poll would (a partial or
|
||||
// retaining snapshot, the tracked aircraft), judged by its newest fix.
|
||||
// No missed-poll grace, and a landed tracked aircraft is not kept.
|
||||
const absenceAtHandover = (icao24) => {
|
||||
const likelyLanded = queries._likelyLanded(icao24);
|
||||
const judged = records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded,
|
||||
tracked: icao24 === flightState._trackedIcao && !likelyLanded,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
return judged === 'stale' && icao24 !== flightState._trackedIcao
|
||||
? 'remove'
|
||||
: judged;
|
||||
};
|
||||
const absentIds = [];
|
||||
for (const icao24 of flightState._icons.ids()) {
|
||||
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
|
||||
@@ -286,13 +311,15 @@ export function createMilitarySnapshotRenderer({
|
||||
for (const icao24 of absentIds) {
|
||||
const absence = replace
|
||||
? 'remove'
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
: handover
|
||||
? absenceAtHandover(icao24)
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
if (absence === 'retain') continue;
|
||||
if (absence === 'stale') {
|
||||
icons._applyIconPresentation(icao24); // the faded freshness alpha
|
||||
@@ -319,7 +346,8 @@ export function createMilitarySnapshotRenderer({
|
||||
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
|
||||
}
|
||||
|
||||
// The tracked contact at the new time: its trail starts there.
|
||||
// The tracked contact at the new time: its trail starts there. Back at
|
||||
// live its trail goes on.
|
||||
if (
|
||||
replace &&
|
||||
flightState._trackedIcao &&
|
||||
|
||||
@@ -404,10 +404,7 @@ export function createTracking({
|
||||
width: look.size[0],
|
||||
height: look.size[1],
|
||||
get scale() {
|
||||
return parts.rendering._fleetBillboardScale(
|
||||
icao24,
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
);
|
||||
return parts.rendering._fleetBillboardScale(icao24);
|
||||
},
|
||||
scaleByDistance: look.scaleByDistance,
|
||||
};
|
||||
@@ -1059,6 +1056,8 @@ export function createTracking({
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
// A ground station's mast stands upright.
|
||||
if (tracked.klass === 'station') return 0;
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const source = (layer) =>
|
||||
readFileSync(new URL(`../${layer}/tracking.js`, import.meta.url), 'utf8');
|
||||
|
||||
for (const layer of ['military', 'flights']) {
|
||||
test(`${layer}: a tracked ground station's mast is never turned`, () => {
|
||||
// The tracked billboard's rotation answers 0 for a station before any
|
||||
// course is projected on screen.
|
||||
const rotation = /rotation: \(\) => \{[\s\S]*?courseScreenRotation\(/.exec(
|
||||
source(layer),
|
||||
)?.[0];
|
||||
assert.ok(rotation, 'the tracked billboard turns by a rotation callback');
|
||||
assert.match(
|
||||
rotation,
|
||||
/if \(tracked\.klass === 'station'\) return 0;\s*const projected = courseScreenRotation\(/,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
transitModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { groundVehiclePartState } from '../../data/modelPartDrivers.js';
|
||||
|
||||
/** How often the trains near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
@@ -924,6 +925,25 @@ export function createRendering({ state, services, parts }) {
|
||||
display: fleet.display,
|
||||
policy: fleet.policy,
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
partState: vehiclePartState,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wheels rolling at the speed it is drawn moving at (else its reported
|
||||
* one), doors open while it stands at a stop.
|
||||
*/
|
||||
function vehiclePartState(item, table) {
|
||||
const entry = item.entry;
|
||||
const drawn = entry?.sample?.segmentSpeedMps;
|
||||
const reported = entry?.record?.speedMps;
|
||||
return groundVehiclePartState(table, {
|
||||
speedMps: Number.isFinite(drawn)
|
||||
? drawn
|
||||
: Number.isFinite(reported)
|
||||
? reported
|
||||
: null,
|
||||
atStop: entry?.record?.status === 'STOPPED_AT',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
transitModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { groundVehiclePartState } from '../../data/modelPartDrivers.js';
|
||||
|
||||
/** Layers built so far, so each one's draw sets have ids of their own. */
|
||||
let instances = 0;
|
||||
@@ -944,6 +945,25 @@ export function createRendering({ state, services, parts }) {
|
||||
display: fleet.display,
|
||||
policy: fleet.policy,
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
partState: vehiclePartState,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wheels rolling at the speed it is drawn moving at (else its reported
|
||||
* one), doors open while it stands at a stop.
|
||||
*/
|
||||
function vehiclePartState(item, table) {
|
||||
const entry = item.entry;
|
||||
const drawn = entry?.sample?.segmentSpeedMps;
|
||||
const reported = entry?.record?.speedMps;
|
||||
return groundVehiclePartState(table, {
|
||||
speedMps: Number.isFinite(drawn)
|
||||
? drawn
|
||||
: Number.isFinite(reported)
|
||||
? reported
|
||||
: null,
|
||||
atStop: entry?.record?.status === 'STOPPED_AT',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -216,3 +216,87 @@ test('back at live, the live poll goes out at once even while a snapshot at a ti
|
||||
assert.equal(Object.hasOwn(queries[1], 'atMs'), false);
|
||||
assert.equal(probe.applied.at(-1).rows.length, 1);
|
||||
});
|
||||
|
||||
test('back at live, only the first live vessel rows applied take over; a poll that fails or brings none says so', async () => {
|
||||
let answer = 'rows';
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
if (answer === 'fail') throw new Error('down');
|
||||
return {
|
||||
records:
|
||||
answer === 'rows'
|
||||
? [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }]
|
||||
: [],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal(await probe.resumeLive({}), true);
|
||||
await probe.methods.update();
|
||||
assert.deepEqual(
|
||||
probe.applied.map(({ options }) => options),
|
||||
[{ complete: true, handover: true }, { complete: true }],
|
||||
);
|
||||
answer = 'none';
|
||||
assert.equal(await probe.resumeLive({}), false);
|
||||
answer = 'fail';
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await probe.resumeLive({}), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live while a live poll is already out, that poll takes over and its answer is awaited', async () => {
|
||||
let answer;
|
||||
const probe = ingestion({
|
||||
getSnapshot: () =>
|
||||
new Promise((resolve) => {
|
||||
answer = () =>
|
||||
resolve({
|
||||
records: [
|
||||
{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 },
|
||||
],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
});
|
||||
}),
|
||||
});
|
||||
const poll = probe.methods.update();
|
||||
const resumed = probe.resumeLive({});
|
||||
answer();
|
||||
assert.equal(await resumed, true);
|
||||
await poll;
|
||||
assert.deepEqual(
|
||||
probe.applied.map(({ options }) => options),
|
||||
[{ complete: true, handover: true }],
|
||||
);
|
||||
});
|
||||
|
||||
test('without AbortSignal.any a vessel request still gives up after its timeout', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const any = AbortSignal.any;
|
||||
AbortSignal.any = undefined;
|
||||
try {
|
||||
const probe = ingestion({
|
||||
getSnapshot: (_query, { signal }) =>
|
||||
new Promise((_, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason)),
|
||||
),
|
||||
});
|
||||
const resumed = probe.resumeLive({});
|
||||
await Promise.resolve();
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(await resumed, false);
|
||||
assert.equal(probe.feed.loading, false);
|
||||
} finally {
|
||||
AbortSignal.any = any;
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,10 @@ import { createTesting } from './testing.js';
|
||||
import { createEvidence } from './evidence.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one vessel layer with application-owned scene services. */
|
||||
export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
@@ -58,6 +61,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
layer.source = source;
|
||||
},
|
||||
followsClock: () => followsClock(vesselState),
|
||||
timedAnswer: snapshotAnswer,
|
||||
reloadAtClock: () => vesselState.timeline.reload(),
|
||||
});
|
||||
// Vessels follow the world clock while the source declares a timeline.
|
||||
@@ -77,9 +81,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
state.feed.count = state.records.all.length;
|
||||
state.feed.lastUpdate = null;
|
||||
},
|
||||
resumeLive: () => {
|
||||
void parts.ingestion.loadLivePositions(vesselState.state.viewer);
|
||||
},
|
||||
resumeLive: () => parts.ingestion.resumeLive(vesselState.state.viewer),
|
||||
});
|
||||
Object.assign(
|
||||
layer,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { AIS_FIRST_CONNECT_LABEL } from './recordPolicy.js';
|
||||
import { viewAreaMovedEnough } from './viewArea.js';
|
||||
|
||||
/** Longest a vessel request may take before it is given up. */
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
// A portable export (package.json): no i18n here. The text stays English data
|
||||
// and the layer panel shows it translated.
|
||||
const msg = (text) => text;
|
||||
@@ -23,14 +26,47 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
followsClock = () => false,
|
||||
reloadAtClock = () => {},
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
async function loadLivePositions(viewer) {
|
||||
// The live load in flight: its result, and its request, whose `handover`
|
||||
// may still be set while it loads (see resumeLive).
|
||||
let liveLoad = null;
|
||||
|
||||
async function loadLivePositions(viewer, { handover = false } = {}) {
|
||||
// Following the world clock, the layer shows the snapshots loadAt applies.
|
||||
if (followsClock()) return;
|
||||
if (followsClock()) return false;
|
||||
// Back at live, a snapshot at a time still loading no longer applies:
|
||||
// it would hold the live poll back until the next refresh.
|
||||
if (feed.loading && feed.loadingAtTime) dropLoad();
|
||||
await loadPositions(viewer);
|
||||
// A live load already out answers this one too.
|
||||
if (feed.loading && liveLoad) {
|
||||
if (handover) liveLoad.request.handover = true;
|
||||
return liveLoad.promise;
|
||||
}
|
||||
const request = { handover };
|
||||
const promise = loadPositions(viewer, { request });
|
||||
const load = { request, promise };
|
||||
liveLoad = load;
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
if (liveLoad === load) liveLoad = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once (or take the live poll
|
||||
* already out), and let its snapshot stand in for every vessel. Those it has keep their
|
||||
* icon and model and move on from where they are; those it lacks go.
|
||||
* Resolves true once it is applied, else false (it could not be had).
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function resumeLive(viewer) {
|
||||
const applied = await loadLivePositions(viewer || readViewer(), {
|
||||
handover: true,
|
||||
});
|
||||
return applied === true;
|
||||
}
|
||||
|
||||
/** Let go of the load in flight, so another can start now. */
|
||||
@@ -44,10 +80,11 @@ export function createIngestion({
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every vessel when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* whether it was applied: `{ reachMs }`, the newest fix its records carry,
|
||||
* when they carry fixes; else true, or false when it was not.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async function loadAt(atMs, { signal = null, replace = false } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies: the
|
||||
@@ -56,7 +93,10 @@ export function createIngestion({
|
||||
return loadPositions(readViewer(), { atMs, replace, signal });
|
||||
}
|
||||
|
||||
async function loadPositions(viewer, { atMs, replace = false, signal } = {}) {
|
||||
async function loadPositions(
|
||||
viewer,
|
||||
{ atMs, replace = false, signal, request = null } = {},
|
||||
) {
|
||||
const timed = atMs !== undefined;
|
||||
if (!viewer || feed.loading) return false;
|
||||
feed.loading = true;
|
||||
@@ -65,18 +105,35 @@ export function createIngestion({
|
||||
const requestController = new AbortController();
|
||||
const requestSessionId = feed.sessionId;
|
||||
feed.abort = requestController;
|
||||
let timeout = null;
|
||||
|
||||
try {
|
||||
// Combine the layer's teardown-abort with a hard timeout so a hung upstream
|
||||
// can't wedge the poll indefinitely (parity with the track fetch + flights).
|
||||
const requestSignal =
|
||||
typeof AbortSignal.any === 'function'
|
||||
? AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(10000),
|
||||
...(signal ? [signal] : []),
|
||||
])
|
||||
: requestController.signal;
|
||||
let requestSignal;
|
||||
if (typeof AbortSignal.any === 'function')
|
||||
requestSignal = AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
...(signal ? [signal] : []),
|
||||
]);
|
||||
else {
|
||||
// Without it, the request's own controller takes the timeout and
|
||||
// the caller's abort.
|
||||
timeout = setTimeout(
|
||||
() =>
|
||||
requestController.abort(
|
||||
new DOMException('Vessel request timed out', 'TimeoutError'),
|
||||
),
|
||||
REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
signal?.addEventListener(
|
||||
'abort',
|
||||
() => requestController.abort(signal.reason),
|
||||
{ once: true },
|
||||
);
|
||||
requestSignal = requestController.signal;
|
||||
}
|
||||
// Ask for the vessels in view; a wide view asks for every vessel.
|
||||
const area = readArea(viewer);
|
||||
feed.lastArea = area;
|
||||
@@ -92,9 +149,10 @@ export function createIngestion({
|
||||
if (signal?.aborted) return false;
|
||||
// The clock left the live edge while this poll was out.
|
||||
if (!timed && followsClock()) return false;
|
||||
const takesOver = !timed && request?.handover === true;
|
||||
setSourceLabel(snapshot.source);
|
||||
// Map observations into the existing display store; source fields stop here.
|
||||
applyAisFeedSnapshot(viewer, {
|
||||
const applied = applyAisFeedSnapshot(viewer, {
|
||||
rows: snapshot.records.map(vesselDisplayRow),
|
||||
observedAtMs: snapshot.observedAtMs,
|
||||
freshness: snapshot.freshness,
|
||||
@@ -112,8 +170,12 @@ export function createIngestion({
|
||||
silentForMs: snapshot.silentForMs,
|
||||
reconnectAttempt: snapshot.reconnectAttempt,
|
||||
...(replace && { replace }),
|
||||
...(takesOver && { handover: true }),
|
||||
});
|
||||
return true;
|
||||
// Back at live, a snapshot that placed no vessel could not take over.
|
||||
if (takesOver) return applied.reconciled;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (error) {
|
||||
// A snapshot at a time the source dropped for a newer one is no failure.
|
||||
if (timed && error?.name === 'AbortError') throw error;
|
||||
@@ -130,6 +192,7 @@ export function createIngestion({
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (timeout !== null) clearTimeout(timeout);
|
||||
if (
|
||||
feed.abort === requestController &&
|
||||
feed.sessionId === requestSessionId
|
||||
@@ -197,6 +260,7 @@ export function createIngestion({
|
||||
applyRows(viewer, snapshot.acceptedRows, {
|
||||
complete: payload?.complete !== false,
|
||||
...(payload?.replace && { replace: true }),
|
||||
...(payload?.handover && { handover: true }),
|
||||
});
|
||||
feed.count = readCount();
|
||||
feed.stale =
|
||||
@@ -266,6 +330,7 @@ export function createIngestion({
|
||||
|
||||
return {
|
||||
loadLivePositions,
|
||||
resumeLive,
|
||||
loadAt,
|
||||
refreshIfMoved,
|
||||
ownsAisRequest,
|
||||
|
||||
@@ -7,6 +7,10 @@ import { createVesselIconBook } from './iconBook.js';
|
||||
import { liftedForHorizon } from '../../geo/horizon.js';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { VESSEL_KIND_STYLES } from '../../data/vesselTypes.js';
|
||||
import { AID_TO_NAVIGATION_STYLE } from '../../data/vesselLabels.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
|
||||
/** A query port with nothing on screen: the viewer doubles have no scene. */
|
||||
const offscreen = {
|
||||
@@ -90,7 +94,7 @@ const snapshot = (records, extra = {}) => ({
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('vessel construction is inert and each instance owns its records, icon cache and clock', () => {
|
||||
test('vessel construction is inert and each instance owns its records and clock', () => {
|
||||
let requested = 0;
|
||||
const source = {
|
||||
getSnapshot() {
|
||||
@@ -99,8 +103,7 @@ test('vessel construction is inert and each instance owns its records, icon cach
|
||||
};
|
||||
const one = createVesselState({ source, services: services() });
|
||||
const two = createVesselState({ source, services: services() });
|
||||
for (const key of ['state', 'shipIconCache'])
|
||||
assert.notEqual(one[key], two[key]);
|
||||
assert.notEqual(one.state, two.state);
|
||||
assert.notEqual(one.state.records.byId, two.state.records.byId);
|
||||
assert.notEqual(one.state.feed, two.state.feed);
|
||||
assert.notEqual(one.state.records.all, two.state.records.all);
|
||||
@@ -557,7 +560,7 @@ test('AIS feed rows stay keyed by their MMSI', async () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => {
|
||||
test('an aid to navigation is drawn as the upright buoy, a vessel as its kind’s hull turned with course', async () => {
|
||||
const aid = {
|
||||
...observation('993672001'),
|
||||
mmsi: '993672001',
|
||||
@@ -565,26 +568,39 @@ test('an aid to navigation is drawn as a disc, a vessel as its chevron', async (
|
||||
speedMps: 0,
|
||||
};
|
||||
const ship = { ...observation('366999002'), type: 'Cargo' };
|
||||
const sailing = { ...observation('366999003'), type: '36' };
|
||||
const { layer, icons } = setup({
|
||||
async getSnapshot() {
|
||||
return snapshot([aid, ship]);
|
||||
return snapshot([aid, ship, sailing]);
|
||||
},
|
||||
});
|
||||
await layer.update();
|
||||
const svgOf = (id) => {
|
||||
const itemOf = (id) => {
|
||||
assert.ok(icons.has(id), id);
|
||||
return atob(icons.item(id).image.split(',')[1]);
|
||||
return icons.item(id);
|
||||
};
|
||||
assert.match(svgOf('993672001'), /<circle/);
|
||||
const buoy = itemOf('993672001');
|
||||
assert.equal(buoy.image, aidSprite());
|
||||
assert.equal(buoy.rotationMode, 'screen', 'upright');
|
||||
assert.equal(buoy.rotation, 0, 'never turned');
|
||||
assert.deepEqual(buoy.color, cssColor(AID_TO_NAVIGATION_STYLE.css));
|
||||
// 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/);
|
||||
const cargo = itemOf('366999002');
|
||||
assert.equal(cargo.image, vesselSprite('cargo'));
|
||||
assert.equal(cargo.rotationMode, 'course');
|
||||
assert.deepEqual(cargo.color, cssColor(VESSEL_KIND_STYLES.cargo.css));
|
||||
const sail = itemOf('366999003');
|
||||
assert.equal(sail.image, vesselSprite('sailing'));
|
||||
assert.deepEqual(sail.color, cssColor(VESSEL_KIND_STYLES.sailing.css));
|
||||
// Every vessel and aid draws the same size before its speed scale.
|
||||
assert.deepEqual(cargo.size, buoy.size);
|
||||
assert.deepEqual(sail.size, buoy.size);
|
||||
});
|
||||
|
||||
test('a virtual aid to navigation keeps its disc and its virtual flag', async () => {
|
||||
test('a virtual aid to navigation keeps its buoy and its virtual flag', async () => {
|
||||
const aid = {
|
||||
...observation('993672009'),
|
||||
mmsi: '993672009',
|
||||
@@ -599,7 +615,7 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async ()
|
||||
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/);
|
||||
assert.equal(icons.item('993672009').image, aidSprite());
|
||||
});
|
||||
|
||||
test('a feed with no AISStream key reports its key as required, and a live one does not', async () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ function harness({ placement = null, following = false } = {}) {
|
||||
const visuals = [];
|
||||
const state = { selectedRecord: null, trailId: null };
|
||||
const records = new VesselRecords({ now: () => 5_000_000 });
|
||||
const primitives = [];
|
||||
const rendering = {
|
||||
ensureCollections() {},
|
||||
makeOccluder: () => null,
|
||||
@@ -28,8 +29,12 @@ function harness({ placement = null, following = false } = {}) {
|
||||
visuals.push(record.id);
|
||||
return { billboard: null };
|
||||
},
|
||||
addRecordPrimitives() {},
|
||||
removeRecordPrimitives() {},
|
||||
addRecordPrimitives(record) {
|
||||
primitives.push(['add', record.id]);
|
||||
},
|
||||
removeRecordPrimitives(record) {
|
||||
primitives.push(['remove', record.id]);
|
||||
},
|
||||
shipIcon: () => 'icon',
|
||||
shipScale: () => 1,
|
||||
syncRecordIcon() {},
|
||||
@@ -41,12 +46,15 @@ function harness({ placement = null, following = false } = {}) {
|
||||
records,
|
||||
rendering,
|
||||
tracking: {},
|
||||
selection: {},
|
||||
cards: {},
|
||||
selection: { clearVesselInspection() {} },
|
||||
cards: { updateSelectedVesselHud() {} },
|
||||
followsClock: () => following,
|
||||
});
|
||||
return {
|
||||
visuals,
|
||||
primitives,
|
||||
state,
|
||||
records,
|
||||
reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options),
|
||||
};
|
||||
}
|
||||
@@ -105,3 +113,61 @@ test('following the world clock, or rows at another time, tell the placement not
|
||||
harness({ placement }).reconcile([row('a')], { replace: true });
|
||||
assert.deepEqual(told, []);
|
||||
});
|
||||
|
||||
test('back at live, the first live vessel rows keep the vessels they have, drop the rest, and are told to the placement', () => {
|
||||
const { told, forgotten, placement } = recording();
|
||||
const probe = harness({ placement });
|
||||
probe.reconcile([row('a'), row('b')]);
|
||||
probe.primitives.length = 0;
|
||||
told.length = 0;
|
||||
probe.reconcile(
|
||||
[row('a', { lat: 52, last_position_epoch: 1_060 }), row('c')],
|
||||
{ handover: true },
|
||||
);
|
||||
// The vessel it has keeps its icon; the one it lacks goes; a new one is
|
||||
// added.
|
||||
assert.deepEqual(probe.primitives, [
|
||||
['add', 'c'],
|
||||
['remove', 'b'],
|
||||
]);
|
||||
assert.deepEqual(forgotten, ['b']);
|
||||
assert.deepEqual(
|
||||
told.map(([id]) => id),
|
||||
['a', 'c'],
|
||||
'live fixes, told to the placement',
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, partial vessel rows keep the vessels they lack whose newest fix is recent; complete rows pin the selected one', () => {
|
||||
const probe = harness();
|
||||
// The records' clock reads 5 000 s: 'recent' was fixed 100 s before it,
|
||||
// 'old' and 'picked' over an hour before.
|
||||
probe.reconcile([
|
||||
row('recent', { last_position_epoch: 4_900 }),
|
||||
row('old'),
|
||||
row('picked'),
|
||||
]);
|
||||
probe.state.selectedRecord = probe.records.byId.get('picked');
|
||||
probe.primitives.length = 0;
|
||||
probe.reconcile([row('c', { last_position_epoch: 4_990 })], {
|
||||
complete: false,
|
||||
handover: true,
|
||||
});
|
||||
// Partial rows prove no absence for a recent fix; an old one is gone.
|
||||
assert.ok(probe.records.byId.has('recent'));
|
||||
assert.equal(probe.records.byId.get('recent').motion, null);
|
||||
assert.equal(probe.records.byId.has('old'), false);
|
||||
|
||||
const complete = harness();
|
||||
complete.reconcile([
|
||||
row('recent', { last_position_epoch: 4_900 }),
|
||||
row('picked'),
|
||||
]);
|
||||
complete.state.selectedRecord = complete.records.byId.get('picked');
|
||||
complete.reconcile([row('c', { last_position_epoch: 4_990 })], {
|
||||
handover: true,
|
||||
});
|
||||
// Complete rows judge as a refresh does: the selected vessel is pinned for
|
||||
// a few refreshes, the rest go.
|
||||
assert.deepEqual([...complete.records.byId.keys()].sort(), ['c', 'picked']);
|
||||
});
|
||||
@@ -103,7 +103,12 @@ export class VesselRecords {
|
||||
* between the two (see motion.js). `replace`: the rows are the world at
|
||||
* another time (the clock jumped), so they stand in for every vessel: one
|
||||
* they lack is gone at once, selected or not, and none moves from where it
|
||||
* was at the time the clock left.
|
||||
* was at the time the clock left. `handover`: the first live rows after the
|
||||
* clock came back to live: a vessel they have moves to its live fix, not
|
||||
* from where it was at the time the clock left; one they lack is judged
|
||||
* as any live refresh judges it (a partial refresh, the selected vessel),
|
||||
* by how old its newest fix is rather than when it was loaded, and holds
|
||||
* at its last position meanwhile.
|
||||
*/
|
||||
reconcile(
|
||||
rows,
|
||||
@@ -112,6 +117,7 @@ export class VesselRecords {
|
||||
selectedRecord = null,
|
||||
cap = Infinity,
|
||||
replace = false,
|
||||
handover = false,
|
||||
follow = false,
|
||||
},
|
||||
effects,
|
||||
@@ -152,7 +158,7 @@ export class VesselRecords {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
if (replace) {
|
||||
if (replace || handover) {
|
||||
record.motion = null;
|
||||
record.fixes = next.fixes;
|
||||
} else if (follow) {
|
||||
@@ -195,6 +201,13 @@ export class VesselRecords {
|
||||
}
|
||||
for (const [id, record] of this.byId) {
|
||||
if (seen.has(id)) continue;
|
||||
if (handover) {
|
||||
record.motion = null;
|
||||
record.fixes = null;
|
||||
// Loaded for another time: last seen at its newest fix.
|
||||
const fixMs = finiteNumber(record.lastPositionEpoch);
|
||||
if (fixMs !== null) record.receivedAtMs = fixMs * 1000;
|
||||
}
|
||||
if (replace) {
|
||||
effects.remove(record, record === selectedRecord);
|
||||
this.byId.delete(id);
|
||||
|
||||
@@ -43,7 +43,11 @@ import {
|
||||
vesselModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { isAidToNavigation } from '../../data/vesselTypes.js';
|
||||
import { vesselPartState } from '../../data/modelPartDrivers.js';
|
||||
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
|
||||
/** A moving vessel's next frame is asked for once it would move this far on
|
||||
* screen (pixels), so it glides when it moves visibly and the scene idles
|
||||
@@ -55,11 +59,16 @@ const PLACEMENT_FRAME_MS = 1000;
|
||||
* ms), so one that comes into view is judged where it is. */
|
||||
const HIDDEN_FOLLOW_MS = 250;
|
||||
|
||||
/** The ship artwork's own raster size (px). */
|
||||
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
|
||||
const SHIP_ICON_PX = 32;
|
||||
/** A selected vessel's or aid's tint. */
|
||||
const SELECTED_TINT = Object.freeze([1, 1, 1, 1]);
|
||||
|
||||
let instances = 0;
|
||||
|
||||
/** Tint by CSS colour: a handful of type colours. */
|
||||
const tints = new Map();
|
||||
|
||||
/** How often the vessels near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
|
||||
@@ -405,6 +414,7 @@ export function createRendering({
|
||||
/** The icon item a record draws, as it now is. */
|
||||
function iconItem(record, visual) {
|
||||
const selected = record === state.selectedRecord;
|
||||
const aid = isAidToNavigation(record);
|
||||
const courseDeg = vesselCourseDeg(record);
|
||||
// Following the clock, not there yet at the time drawn.
|
||||
visual.seen = seenYet(record);
|
||||
@@ -418,11 +428,14 @@ export function createRendering({
|
||||
// is not there yet.
|
||||
show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen,
|
||||
pos: plan?.pos ?? visual.position,
|
||||
image: shipIcon(record, selected),
|
||||
image: shipIcon(record),
|
||||
size: [SHIP_ICON_PX, SHIP_ICON_PX],
|
||||
// Selection changes the colour only, never the size.
|
||||
// Tinted by type; selection changes the colour only, never the size.
|
||||
color: selected ? SELECTED_TINT : shipTint(record),
|
||||
scale: shipScale(record),
|
||||
rotationMode: 'course',
|
||||
// An aid's buoy stands upright on screen; a vessel turns with course.
|
||||
rotationMode: aid ? 'screen' : 'course',
|
||||
rotation: 0,
|
||||
// Held on course, or along its track on the renderer's clock;
|
||||
// `course` for renderers without motion segments.
|
||||
course: courseDeg,
|
||||
@@ -519,40 +532,33 @@ 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.
|
||||
* The sprite a vessel is drawn as: the white hull of its kind
|
||||
* (`vesselKind`), bow up so the row's course turns it to its heading, or
|
||||
* for an aid to navigation the buoy. The layer tints it
|
||||
* (`shipTint`), so each shape takes one icon-atlas slot.
|
||||
* @param {Object} record - Vessel record.
|
||||
* @returns {string} SVG data URL.
|
||||
*/
|
||||
|
||||
function shipIcon(record, selected) {
|
||||
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);
|
||||
function shipIcon(record) {
|
||||
return isAidToNavigation(record)
|
||||
? aidSprite()
|
||||
: vesselSprite(vesselKind(record.type));
|
||||
}
|
||||
|
||||
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)">
|
||||
${shape}
|
||||
</g>
|
||||
</svg>`;
|
||||
const icon = 'data:image/svg+xml;base64,' + btoa(svg);
|
||||
vesselState.shipIconCache.set(key, icon);
|
||||
return icon;
|
||||
/**
|
||||
* A vessel's tint, `[r, g, b, a]`: its type's colour (vesselLabels.js,
|
||||
* shared with its card), an aid's bone white.
|
||||
* @param {Object} record - Vessel record.
|
||||
*/
|
||||
|
||||
function shipTint(record) {
|
||||
const css = isAidToNavigation(record)
|
||||
? AID_TO_NAVIGATION_STYLE.css
|
||||
: vesselTypeCss(record.type);
|
||||
let tint = tints.get(css);
|
||||
if (!tint) tints.set(css, (tint = Object.freeze(cssColor(css))));
|
||||
return tint;
|
||||
}
|
||||
|
||||
// Under the DISPLAY rail's 3D toggle, vessels near the camera are drawn as
|
||||
@@ -578,6 +584,13 @@ export function createRendering({
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
// A hull below the waterline would show through a plain globe.
|
||||
waterline: true,
|
||||
// Its radar sweeps while it is under way (speed in knots).
|
||||
partState: (item, table) =>
|
||||
vesselPartState(table, {
|
||||
speedMps: Number.isFinite(item.record?.speed)
|
||||
? item.record.speed * KNOT_MPS
|
||||
: null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const KNOT_MPS = 1852 / 3600;
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
|
||||
const finiteOrNaN = (value) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : NaN;
|
||||
|
||||
@@ -34,11 +35,15 @@ export function createVesselSnapshotRenderer({
|
||||
cards,
|
||||
followsClock = () => false,
|
||||
}) {
|
||||
/** `replace`: the rows are the world at another time (see VesselRecords). */
|
||||
/**
|
||||
* `replace`: the rows are the world at another time (see VesselRecords).
|
||||
* `handover`: the first live rows after the clock came back to live (see
|
||||
* VesselRecords); they are live fixes.
|
||||
*/
|
||||
function reconcileVessels(
|
||||
viewer,
|
||||
rows,
|
||||
{ complete = true, replace = false } = {},
|
||||
{ complete = true, replace = false, handover = false } = {},
|
||||
) {
|
||||
rendering.ensureCollections(viewer);
|
||||
const occluder = rendering.makeOccluder();
|
||||
@@ -57,6 +62,7 @@ export function createVesselSnapshotRenderer({
|
||||
selectedRecord: state.selectedRecord,
|
||||
cap: rendering.renderRowLimit(),
|
||||
...(replace && { replace }),
|
||||
...(handover && { handover }),
|
||||
...(follow && { follow }),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -53,10 +53,6 @@ export function createVesselState({ source, services }) {
|
||||
|
||||
vesselState._geoidReady = false;
|
||||
|
||||
/** @type {Map<string, string>} `${cssColor}:${variant}` -> chevron SVG data URL */
|
||||
|
||||
vesselState.shipIconCache = new Map();
|
||||
|
||||
/** Row ids for unkeyed (no-id) records, which are rebuilt every poll. */
|
||||
|
||||
vesselState._unkeyedIconSequence = 0;
|
||||
|
||||
@@ -5312,10 +5312,14 @@ export function createCesiumDraw({
|
||||
replaceHost,
|
||||
horizonNow,
|
||||
requestRender,
|
||||
parts: capabilities.has('modelParts'),
|
||||
now,
|
||||
});
|
||||
const buildModels = (record) => modelSets.build(record);
|
||||
// Whether shapes pulsed in the last frame, which draws on in the next.
|
||||
let pulsing = false;
|
||||
// Whether a shown model's parts spun in the last frame, likewise.
|
||||
let spinning = false;
|
||||
const lineWidth = (px) =>
|
||||
typeof scene.clampLineWidth === 'function'
|
||||
? scene.clampLineWidth(px)
|
||||
@@ -5452,7 +5456,7 @@ export function createCesiumDraw({
|
||||
turnInertial(record);
|
||||
record.drapeInertial?.();
|
||||
}
|
||||
modelSets.beforeRender(sets.values());
|
||||
spinning = modelSets.beforeRender(sets.values());
|
||||
quadSets.beforeRender(sets.values());
|
||||
},
|
||||
/** Each frame, after it drew: clamp state, and ground swaps. */
|
||||
@@ -5483,7 +5487,8 @@ export function createCesiumDraw({
|
||||
// Rows moving on a live clock, and flowing lines, draw on in the
|
||||
// frames that follow.
|
||||
const playing = quadSets.afterRender(sets.values());
|
||||
if (anySet(animating) || flowing() || pulsing || playing) requestRender();
|
||||
if (anySet(animating) || flowing() || pulsing || spinning || playing)
|
||||
requestRender();
|
||||
},
|
||||
/**
|
||||
* Let go of the sets; with `removeHosts`, take what they draw out of
|
||||
@@ -5494,6 +5499,8 @@ export function createCesiumDraw({
|
||||
clampListeners.clear();
|
||||
// Fields go with the port, and their frame listeners with them.
|
||||
fieldPart.dispose();
|
||||
// Part shaders and their textures go with it too.
|
||||
modelSets.dispose();
|
||||
// Late model loads find no host and destroy themselves.
|
||||
for (const record of sets.values()) {
|
||||
if (removeHosts && !scene.isDestroyed?.()) {
|
||||
@@ -5538,7 +5545,7 @@ provideUnboundDraw((viewer) => {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: uncaught,
|
||||
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields']),
|
||||
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
|
||||
});
|
||||
unboundParts.set(part.port, part);
|
||||
const offs = [
|
||||
|
||||
@@ -26,6 +26,20 @@
|
||||
* `shading: 'thermal'` draws the model unlit and white-hot (its texture
|
||||
* left out), then tinted as asked: a hot target, as the thermal views draw
|
||||
* them. Heights are absolute: models clamp nothing.
|
||||
*
|
||||
* An item's `parts` (with `modelParts`) poses the moving parts of a model
|
||||
* whose mesh carries `_PART` and whose root node carries a part table
|
||||
* (`render/modelParts.js`): its model then draws with a custom shader of
|
||||
* its own whose vertex stage moves each vertex by its part's matrix, read
|
||||
* from a small float texture (`PARTS_VERTEX` says its layout), with the
|
||||
* item's mask, unlit or thermal look in the same shader; a moved part's
|
||||
* material normal turns with it. The texture is written again in place
|
||||
* when the part state changes, and each frame while a part of a model in
|
||||
* view spins (frames are asked for while one does). Spins keep their angle
|
||||
* across a change of rate. A model at rest, or without a part table, draws
|
||||
* exactly as it would without `parts`, on the shared shaders above. Cesium
|
||||
* culls and picks a model by its bounds as its file draws it, so a part
|
||||
* moved outside them is drawn only while those bounds are in view.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
@@ -34,6 +48,15 @@ import {
|
||||
recedeParams,
|
||||
recededAlpha,
|
||||
} from '../recession.js';
|
||||
import { customShaderTexture } from './internals.js';
|
||||
import {
|
||||
glbJson,
|
||||
gltfMeshMatrix,
|
||||
gltfPartTable,
|
||||
partMatrices,
|
||||
PART_HIGHLIGHT,
|
||||
asksHighlight,
|
||||
} from '../modelParts.js';
|
||||
|
||||
const BLEND_MODES = {
|
||||
highlight: Cesium.ColorBlendMode.HIGHLIGHT,
|
||||
@@ -144,6 +167,366 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The colour a part with `highlight: true` is drawn in. */
|
||||
const PART_HIGHLIGHT_COLOR = '#ffc400';
|
||||
|
||||
/** How much of a highlighted part's colour the highlight replaces. */
|
||||
const PART_HIGHLIGHT_MIX = 0.6;
|
||||
|
||||
/** Texels in a part's row of its texture. */
|
||||
const PART_TEXELS = 8;
|
||||
/** Floats in a part's row: `PART_TEXELS` RGBA texels. */
|
||||
const PART_FLOATS = PART_TEXELS * 4;
|
||||
|
||||
/** A texel's centre across a part's row, as a texture coordinate. */
|
||||
const texelAt = (i) => ((i + 0.5) / PART_TEXELS).toFixed(4);
|
||||
|
||||
/**
|
||||
* The vertex stage of a posed model. A part's row of the texture holds the
|
||||
* three rows of its matrix in the mesh's own frame (texels 0..2), the three
|
||||
* rows of that matrix's inverse transpose (3..5; texel 3's alpha is 1 where
|
||||
* the part is moved, 0 where it is at rest), and its highlight colour (6,
|
||||
* alpha 0 for none). Each vertex is moved by its part's matrix; the normal
|
||||
* turn is passed on in eye space, for the fragment stage to turn the
|
||||
* material's own normal (normal maps and back-face flips kept) by it.
|
||||
* Positions are the mesh's own (before its node's transform), as are the
|
||||
* matrices written for it, and as `czm_normal` takes them to eye space.
|
||||
*/
|
||||
const PARTS_VERTEX = `
|
||||
void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
|
||||
float row = (floor(vsInput.attributes.part + 0.5) + 0.5) / u_partRows;
|
||||
vec4 r0 = texture(u_partMatrices, vec2(${texelAt(0)}, row));
|
||||
vec4 r1 = texture(u_partMatrices, vec2(${texelAt(1)}, row));
|
||||
vec4 r2 = texture(u_partMatrices, vec2(${texelAt(2)}, row));
|
||||
vec4 n0 = texture(u_partMatrices, vec2(${texelAt(3)}, row));
|
||||
v_partHighlight = texture(u_partMatrices, vec2(${texelAt(6)}, row));
|
||||
vec4 p = vec4(vsOutput.positionMC, 1.0);
|
||||
vsOutput.positionMC = vec3(dot(r0, p), dot(r1, p), dot(r2, p));
|
||||
v_partMoved = n0.a;
|
||||
if (n0.a > 0.5) {
|
||||
vec4 n1 = texture(u_partMatrices, vec2(${texelAt(4)}, row));
|
||||
vec4 n2 = texture(u_partMatrices, vec2(${texelAt(5)}, row));
|
||||
mat3 turn = transpose(mat3(n0.xyz, n1.xyz, n2.xyz));
|
||||
v_partNormalEC = czm_normal * turn * inverse(czm_normal);
|
||||
} else {
|
||||
v_partNormalEC = mat3(1.0);
|
||||
}
|
||||
}`;
|
||||
|
||||
/**
|
||||
* A posed model's custom shader: its parts moved (`PARTS_VERTEX`), drawn in
|
||||
* `shading` with `mask` painted where `_TINT` marks the model (not under
|
||||
* `thermal`), and its highlighted parts in their colour. Lit, a moved
|
||||
* part's material normal is turned with it; the body and parts at rest keep
|
||||
* theirs as the material made them. `data` is the part texture's first
|
||||
* contents, `rows` its parts.
|
||||
*/
|
||||
function partShaderOf(shading, mask, data, rows) {
|
||||
const lit = shading !== 'unlit' && shading !== 'thermal';
|
||||
const masked = Boolean(mask) && shading !== 'thermal';
|
||||
return new Cesium.CustomShader({
|
||||
mode: Cesium.CustomShaderMode.MODIFY_MATERIAL,
|
||||
...(lit ? {} : { lightingModel: Cesium.LightingModel.UNLIT }),
|
||||
uniforms: {
|
||||
u_partMatrices: {
|
||||
type: Cesium.UniformType.SAMPLER_2D,
|
||||
value: partTexture(data, rows),
|
||||
},
|
||||
u_partRows: { type: Cesium.UniformType.FLOAT, value: rows },
|
||||
...(masked
|
||||
? {
|
||||
u_maskColor: {
|
||||
type: Cesium.UniformType.VEC3,
|
||||
value: new Cesium.Cartesian3(mask.red, mask.green, mask.blue),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
varyings: {
|
||||
v_partNormalEC: Cesium.VaryingType.MAT3,
|
||||
v_partMoved: Cesium.VaryingType.FLOAT,
|
||||
v_partHighlight: Cesium.VaryingType.VEC4,
|
||||
},
|
||||
vertexShaderText: PARTS_VERTEX,
|
||||
fragmentShaderText: `
|
||||
void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
|
||||
${
|
||||
lit
|
||||
? ` if (v_partMoved > 0.5)
|
||||
material.normalEC = normalize(v_partNormalEC * material.normalEC);`
|
||||
: ''
|
||||
}
|
||||
${shading === 'thermal' ? ' material.diffuse = vec3(1.0);' : ''}
|
||||
${
|
||||
masked
|
||||
? ` vec3 mask = czm_srgbToLinear(u_maskColor);
|
||||
material.diffuse *= mix(vec3(1.0), mask, fsInput.attributes.tint);`
|
||||
: ''
|
||||
}
|
||||
if (v_partHighlight.a > 0.0) {
|
||||
vec3 highlight = czm_srgbToLinear(v_partHighlight.rgb);
|
||||
material.diffuse = mix(material.diffuse, highlight, ${PART_HIGHLIGHT_MIX.toFixed(2)});
|
||||
material.emissive = max(material.emissive, highlight * 0.5);
|
||||
}
|
||||
}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** A part texture's contents as a texture uniform: `PART_TEXELS` float texels a row, read unfiltered. */
|
||||
function partTexture(data, rows) {
|
||||
return new Cesium.TextureUniform({
|
||||
typedArray: data,
|
||||
width: PART_TEXELS,
|
||||
height: rows,
|
||||
pixelFormat: Cesium.PixelFormat.RGBA,
|
||||
pixelDatatype: Cesium.PixelDatatype.FLOAT,
|
||||
repeat: false,
|
||||
minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
|
||||
magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST,
|
||||
});
|
||||
}
|
||||
|
||||
/** An affine column-major 4×4's inverse. */
|
||||
function inverseAffine(m) {
|
||||
const [a, b, c] = [m[0], m[1], m[2]];
|
||||
const [d, e, f] = [m[4], m[5], m[6]];
|
||||
const [g, h, i] = [m[8], m[9], m[10]];
|
||||
const A = e * i - f * h;
|
||||
const B = -(b * i - c * h);
|
||||
const C = b * f - c * e;
|
||||
const det = a * A + d * B + g * C;
|
||||
if (!(Math.abs(det) > 1e-30)) return null;
|
||||
const r = 1 / det;
|
||||
const out = [
|
||||
A * r,
|
||||
B * r,
|
||||
C * r,
|
||||
0,
|
||||
-(d * i - f * g) * r,
|
||||
(a * i - c * g) * r,
|
||||
-(a * f - c * d) * r,
|
||||
0,
|
||||
(d * h - e * g) * r,
|
||||
-(a * h - b * g) * r,
|
||||
(a * e - b * d) * r,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
];
|
||||
for (let row = 0; row < 3; row++)
|
||||
out[12 + row] = -(
|
||||
out[row] * m[12] +
|
||||
out[4 + row] * m[13] +
|
||||
out[8 + row] * m[14]
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What a glTF document (or GLB) says of its parts: its table and mesh frame; null without a table. */
|
||||
const partInfos = new WeakMap();
|
||||
|
||||
/** `source`'s part table and mesh frame, read once; null for a model without moving parts. */
|
||||
function partInfoOf(source) {
|
||||
if (partInfos.has(source)) return partInfos.get(source);
|
||||
let info = null;
|
||||
try {
|
||||
const json = source instanceof Uint8Array ? glbJson(source) : source;
|
||||
const table = gltfPartTable(json);
|
||||
const mesh = table && gltfMeshMatrix(json);
|
||||
const meshInverse = mesh && inverseAffine(mesh);
|
||||
if (table && table.parts.length > 1 && meshInverse)
|
||||
info = { table, mesh, meshInverse };
|
||||
} catch {
|
||||
// A malformed table: the model draws whole.
|
||||
info = null;
|
||||
}
|
||||
partInfos.set(source, info);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Whether a part state asks for anything. */
|
||||
const asksParts = (state) =>
|
||||
Boolean(state) &&
|
||||
typeof state === 'object' &&
|
||||
['spin', 'deploy', 'poses'].some(
|
||||
(key) => state[key] && Object.keys(state[key]).length > 0,
|
||||
);
|
||||
|
||||
/** Scratch for one model's part matrices and flags, and one matrix's rows. */
|
||||
let scratchParts = new Float64Array(16 * 32);
|
||||
let scratchFlags = new Uint8Array(32);
|
||||
const scratchRow = new Float64Array(4);
|
||||
const scratchL = new Float64Array(12);
|
||||
|
||||
/** How far from the identity a part's matrix may be and still be at rest. */
|
||||
const AT_REST_EPSILON = 1e-9;
|
||||
|
||||
/** Highlight colours by what was asked, read once (a few at most). */
|
||||
const highlightColors = new Map();
|
||||
|
||||
/**
|
||||
* The colour a part's `highlight` asks for, read once: `true` the
|
||||
* renderer's own, a colour that parses as itself; null for anything else
|
||||
* (drawn without a highlight).
|
||||
*/
|
||||
export function partHighlightColor(value) {
|
||||
if (!asksHighlight(value)) return null;
|
||||
const key = value === true ? PART_HIGHLIGHT_COLOR : String(value);
|
||||
let color = highlightColors.get(key);
|
||||
if (color === undefined) {
|
||||
if (value === true || typeof value === 'string')
|
||||
color = Cesium.Color.fromCssColorString(key.trim()) ?? null;
|
||||
else color = new Cesium.Color(value[0], value[1], value[2], 1);
|
||||
if (highlightColors.size >= 256) highlightColors.clear();
|
||||
highlightColors.set(key, color);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a model's part texture into `data` (`PART_FLOATS` a part, the
|
||||
* layout `PARTS_VERTEX` reads) for `state` at `timeS`: for each part the
|
||||
* rows of its matrix in the mesh's own frame, L = meshInverse · X · mesh,
|
||||
* then the rows of L's inverse transpose (normals turn by it, exact under a
|
||||
* stretch or a mesh frame that is not a rotation) with whether the part is
|
||||
* moved, then its highlight colour. Whether any part is not at rest.
|
||||
*/
|
||||
export function writePartTexture(info, state, timeS, scale, data) {
|
||||
const { table, mesh, meshInverse } = info;
|
||||
const n = table.parts.length;
|
||||
if (scratchParts.length < n * 16) {
|
||||
scratchParts = new Float64Array(n * 16);
|
||||
scratchFlags = new Uint8Array(n);
|
||||
}
|
||||
const posed = partMatrices(table, state, timeS, scratchParts, {
|
||||
flags: scratchFlags,
|
||||
scale,
|
||||
});
|
||||
const poses = state?.poses;
|
||||
const x = scratchParts;
|
||||
const ix = scratchRow;
|
||||
const L = scratchL;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const o = k * 16;
|
||||
const d = k * PART_FLOATS;
|
||||
let moved = false;
|
||||
for (let row = 0; row < 3; row++) {
|
||||
// (meshInverse · X) row `row`, as four column entries.
|
||||
for (let col = 0; col < 4; col++) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < 4; j++)
|
||||
sum += meshInverse[j * 4 + row] * x[o + col * 4 + j];
|
||||
ix[col] = sum;
|
||||
}
|
||||
for (let col = 0; col < 4; col++) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < 4; j++) sum += ix[j] * mesh[col * 4 + j];
|
||||
L[row * 4 + col] = sum;
|
||||
data[d + row * 4 + col] = sum;
|
||||
if (Math.abs(sum - (row === col ? 1 : 0)) > AT_REST_EPSILON)
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
// The inverse transpose of L's 3×3: its cofactors over its determinant.
|
||||
const a = L[0];
|
||||
const b = L[1];
|
||||
const c = L[2];
|
||||
const e = L[4];
|
||||
const f = L[5];
|
||||
const g = L[6];
|
||||
const h = L[8];
|
||||
const i = L[9];
|
||||
const j = L[10];
|
||||
const c00 = f * j - g * i;
|
||||
const c01 = -(e * j - g * h);
|
||||
const c02 = e * i - f * h;
|
||||
const c10 = -(b * j - c * i);
|
||||
const c11 = a * j - c * h;
|
||||
const c12 = -(a * i - b * h);
|
||||
const c20 = b * g - c * f;
|
||||
const c21 = -(a * g - c * e);
|
||||
const c22 = a * f - b * e;
|
||||
const det = a * c00 + b * c01 + c * c02;
|
||||
const nd = d + 12;
|
||||
// At rest, or hidden (collapsed to a point): normals as they are.
|
||||
const turned = moved && Math.abs(det) > 1e-12;
|
||||
const r = turned ? 1 / det : 0;
|
||||
data[nd] = turned ? c00 * r : 1;
|
||||
data[nd + 1] = turned ? c01 * r : 0;
|
||||
data[nd + 2] = turned ? c02 * r : 0;
|
||||
data[nd + 3] = turned ? 1 : 0;
|
||||
data[nd + 4] = turned ? c10 * r : 0;
|
||||
data[nd + 5] = turned ? c11 * r : 1;
|
||||
data[nd + 6] = turned ? c12 * r : 0;
|
||||
data[nd + 7] = 0;
|
||||
data[nd + 8] = turned ? c20 * r : 0;
|
||||
data[nd + 9] = turned ? c21 * r : 0;
|
||||
data[nd + 10] = turned ? c22 * r : 1;
|
||||
data[nd + 11] = 0;
|
||||
const color =
|
||||
scratchFlags[k] & PART_HIGHLIGHT
|
||||
? partHighlightColor(poses?.[table.parts[k].name]?.highlight)
|
||||
: null;
|
||||
const hd = d + 24;
|
||||
data[hd] = color ? color.red : 0;
|
||||
data[hd + 1] = color ? color.green : 0;
|
||||
data[hd + 2] = color ? color.blue : 0;
|
||||
data[hd + 3] = color ? 1 : 0;
|
||||
}
|
||||
return posed;
|
||||
}
|
||||
|
||||
/**
|
||||
* A posed model's spins, turned on to `timeS` (seconds): each spinning
|
||||
* part's angle moves on at its rate since it last did, so a change of rate
|
||||
* never makes a part jump. A part that stops spinning keeps its angle.
|
||||
*/
|
||||
export function advanceSpins(spins, timeS) {
|
||||
const dt = timeS - spins.at;
|
||||
spins.at = timeS;
|
||||
if (!(dt > 0)) return;
|
||||
for (const [name, rate] of spins.rates)
|
||||
spins.angles[name] = (spins.angles[name] + rate * dt) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spins at `state`'s rates from `timeS` on, carrying the angles reached; a
|
||||
* part starting to spin starts at an angle of `startAngle`'s (by default a
|
||||
* random one, so a fleet posed at once does not turn in step).
|
||||
*/
|
||||
export function respin(
|
||||
spins,
|
||||
table,
|
||||
state,
|
||||
timeS,
|
||||
startAngle = () => Math.random() * 360,
|
||||
) {
|
||||
advanceSpins(spins, timeS);
|
||||
spins.rates.clear();
|
||||
for (const [name, rate] of Object.entries(state?.spin ?? {})) {
|
||||
const index = table.byName.get(name);
|
||||
if (
|
||||
index === undefined ||
|
||||
!table.parts[index].axis ||
|
||||
typeof rate !== 'number' ||
|
||||
!Number.isFinite(rate) ||
|
||||
rate === 0
|
||||
)
|
||||
continue;
|
||||
spins.rates.set(name, rate);
|
||||
if (!(name in spins.angles)) spins.angles[name] = startAngle();
|
||||
}
|
||||
}
|
||||
|
||||
/** New spins: none yet, at `timeS`. */
|
||||
export const newSpins = (timeS) => ({
|
||||
rates: new Map(),
|
||||
angles: {},
|
||||
at: timeS,
|
||||
});
|
||||
|
||||
/** A contract distance curve's value at `distance`: linear, clamped. */
|
||||
export function nearFarValue(curve, distance) {
|
||||
if (!curve) return 1;
|
||||
@@ -228,8 +611,11 @@ const focusOf = (item) =>
|
||||
* The models part of a Cesium draw port.
|
||||
* @param {{scene: object, toColor: Function, pickId: Function,
|
||||
* replaceHost: Function, horizonNow: () => object|null,
|
||||
* requestRender: () => void}} options From the draw port: its colour
|
||||
* conversion, pick ids, host swap, horizon and render request.
|
||||
* requestRender: () => void, parts?: boolean,
|
||||
* now?: () => number}} options From the draw port: its colour
|
||||
* conversion, pick ids, host swap, horizon and render request; whether it
|
||||
* poses models' parts (`modelParts`), and the clock (milliseconds) spins
|
||||
* are turned by.
|
||||
*/
|
||||
export function createModelSets({
|
||||
scene,
|
||||
@@ -238,7 +624,238 @@ export function createModelSets({
|
||||
replaceHost,
|
||||
horizonNow,
|
||||
requestRender,
|
||||
parts: posesParts = false,
|
||||
now = () => performance.now(),
|
||||
}) {
|
||||
/** Each Cesium model drawn posed: its part shader, texture and spins. */
|
||||
const posings = new Map();
|
||||
/** The GLB bytes each model was built from, where it was. */
|
||||
const modelBytes = new WeakMap();
|
||||
/** Part shaders let go, destroyed once no draw uses them. */
|
||||
const retired = [];
|
||||
// Float textures carry the part matrices, and WebGL 2's shading language
|
||||
// turns the normals: without them models draw whole.
|
||||
const canPose = () =>
|
||||
scene.context?.floatingPointTexture !== false &&
|
||||
scene.context?.webgl2 !== false;
|
||||
|
||||
/** A model's part table and mesh frame, or null. */
|
||||
function partInfoOfModel(model) {
|
||||
const bytes = modelBytes.get(model);
|
||||
if (bytes) return partInfoOf(bytes);
|
||||
const json = model.loader?.gltfJson;
|
||||
return json ? partInfoOf(json) : null;
|
||||
}
|
||||
|
||||
/** Let go of a model's posing: its shader goes once no draw uses it. */
|
||||
function unpose(model) {
|
||||
const posing = posings.get(model);
|
||||
if (!posing) return;
|
||||
posings.delete(model);
|
||||
retired.push({ shader: posing.shader, frames: 0 });
|
||||
}
|
||||
|
||||
/** Write a posing's texture where its shader reads it. */
|
||||
function upload(posing) {
|
||||
const texture = customShaderTexture(posing.shader, 'u_partMatrices');
|
||||
if (
|
||||
texture &&
|
||||
!texture.isDestroyed?.() &&
|
||||
texture.width === PART_TEXELS &&
|
||||
texture.height === posing.rows
|
||||
)
|
||||
texture.copyFrom({
|
||||
source: {
|
||||
arrayBufferView: posing.data,
|
||||
width: PART_TEXELS,
|
||||
height: posing.rows,
|
||||
},
|
||||
});
|
||||
else
|
||||
posing.shader.setUniform(
|
||||
'u_partMatrices',
|
||||
partTexture(posing.data, posing.rows),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The state a posing's texture is written for: its item's deploys and
|
||||
* poses, its spins as the angles they have reached (written at a time of
|
||||
* 1 s, each angle given as a rate).
|
||||
*/
|
||||
function spunState(posing) {
|
||||
const drawn = posing.drawn;
|
||||
drawn.deploy = posing.state.deploy;
|
||||
drawn.poses = posing.state.poses;
|
||||
drawn.spin = posing.spins.angles;
|
||||
return drawn;
|
||||
}
|
||||
|
||||
/** Write a posing's texture for now. Whether any part is not at rest. */
|
||||
function writePosing(posing, timeS) {
|
||||
advanceSpins(posing.spins, timeS);
|
||||
return writePartTexture(
|
||||
posing.info,
|
||||
spunState(posing),
|
||||
1,
|
||||
posing.scale,
|
||||
posing.data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shader `model` draws its entry's item's `parts` with, its texture
|
||||
* written for them now; undefined when the model draws whole (no `parts`,
|
||||
* no part table, or every part at rest), its posing let go.
|
||||
*/
|
||||
function posedShader(entry, model) {
|
||||
const item = entry.item;
|
||||
const state = posesParts ? item.parts : undefined;
|
||||
const posing = posings.get(model);
|
||||
const info = asksParts(state) && canPose() ? partInfoOfModel(model) : null;
|
||||
if (!info) {
|
||||
unpose(model);
|
||||
return undefined;
|
||||
}
|
||||
const axes = item.axisScale;
|
||||
const scale =
|
||||
axes && (axes[0] !== 1 || axes[1] !== 1 || axes[2] !== 1)
|
||||
? axes
|
||||
: undefined;
|
||||
const key = JSON.stringify(state);
|
||||
const scaleKey = scale ? scale.join(',') : '';
|
||||
const shading = item.shading;
|
||||
const sameLook =
|
||||
posing?.info === info &&
|
||||
posing.shading === shading &&
|
||||
posing.mask === entry.mask;
|
||||
// A fleet re-poses every frame with the same parts: written when they
|
||||
// change (a spin turns in the frame pass).
|
||||
if (sameLook && posing.key === key && posing.scaleKey === scaleKey)
|
||||
return posing.shader;
|
||||
const timeS = now() / 1000;
|
||||
// Spins go on from where they were, whatever else changed.
|
||||
const spins = posing?.info === info ? posing.spins : newSpins(timeS);
|
||||
respin(spins, info.table, state, timeS);
|
||||
const spinning = spins.rates.size > 0;
|
||||
const rows = info.table.parts.length;
|
||||
const next = {
|
||||
info,
|
||||
shader: sameLook ? posing.shader : null,
|
||||
shading,
|
||||
mask: entry.mask,
|
||||
data: sameLook ? posing.data : new Float32Array(rows * PART_FLOATS),
|
||||
rows,
|
||||
key,
|
||||
scaleKey,
|
||||
scale,
|
||||
spinning,
|
||||
state,
|
||||
spins,
|
||||
drawn: posing?.drawn ?? {},
|
||||
};
|
||||
const posed = writePosing(next, timeS);
|
||||
if (!posed && !spinning) {
|
||||
unpose(model);
|
||||
return undefined;
|
||||
}
|
||||
if (sameLook) {
|
||||
Object.assign(posing, next);
|
||||
upload(posing);
|
||||
return posing.shader;
|
||||
}
|
||||
unpose(model);
|
||||
next.shader = partShaderOf(shading, entry.mask, next.data, rows);
|
||||
posings.set(model, next);
|
||||
return next.shader;
|
||||
}
|
||||
|
||||
/** Pixels across a model's bounds under which its spins are not turned. */
|
||||
const MIN_SPIN_PIXELS = 4;
|
||||
const scratchSpinSphere = new Cesium.BoundingSphere();
|
||||
|
||||
/**
|
||||
* Whether a model is worth turning this frame: shown, in the view, and
|
||||
* at least `MIN_SPIN_PIXELS` across.
|
||||
*/
|
||||
function seen(model, culling, width, height) {
|
||||
if (!model.show || !model.ready) return false;
|
||||
const sphere = model.boundingSphere;
|
||||
if (!sphere || !(sphere.radius > 0)) return false;
|
||||
if (
|
||||
culling &&
|
||||
culling.computeVisibility(sphere) === Cesium.Intersect.OUTSIDE
|
||||
)
|
||||
return false;
|
||||
if (!(width > 0 && height > 0)) return true;
|
||||
Cesium.BoundingSphere.clone(sphere, scratchSpinSphere);
|
||||
scratchSpinSphere.radius = 0;
|
||||
const metresPerPixel = scene.camera.getPixelSize(
|
||||
scratchSpinSphere,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
return (
|
||||
!(metresPerPixel > 0) ||
|
||||
!Number.isFinite(metresPerPixel) ||
|
||||
(2 * sphere.radius) / metresPerPixel >= MIN_SPIN_PIXELS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Before a frame: turn the spinning parts of each model in view to now,
|
||||
* sweep the posings of models gone, and destroy part shaders no draw
|
||||
* uses any more. Whether any model in view spins (frames go on being
|
||||
* asked for; one out of view or too small to see asks for none).
|
||||
*/
|
||||
function turnParts() {
|
||||
for (let i = retired.length - 1; i >= 0; i--)
|
||||
if ((retired[i].frames += 1) > 2) {
|
||||
const [{ shader }] = retired.splice(i, 1);
|
||||
shader.destroy?.();
|
||||
}
|
||||
if (!posings.size) return false;
|
||||
const timeS = now() / 1000;
|
||||
const camera = scene.camera;
|
||||
const culling =
|
||||
camera?.frustum?.computeCullingVolume && camera.positionWC
|
||||
? camera.frustum.computeCullingVolume(
|
||||
camera.positionWC,
|
||||
camera.directionWC,
|
||||
camera.upWC,
|
||||
)
|
||||
: null;
|
||||
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
|
||||
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
|
||||
let spinning = false;
|
||||
for (const [model, posing] of posings) {
|
||||
if (model.isDestroyed?.()) {
|
||||
unpose(model);
|
||||
continue;
|
||||
}
|
||||
if (!posing.spinning || !seen(model, culling, width, height)) continue;
|
||||
spinning = true;
|
||||
writePosing(posing, timeS);
|
||||
upload(posing);
|
||||
}
|
||||
return spinning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Let go of every posing and part shader now, their textures with them:
|
||||
* the port is done, and no frame comes to retire them. A model still
|
||||
* drawn is left drawing whole.
|
||||
*/
|
||||
function dispose() {
|
||||
for (const [model, posing] of posings) {
|
||||
if (!model.isDestroyed?.() && model.customShader === posing.shader)
|
||||
model.customShader = undefined;
|
||||
posing.shader.destroy?.();
|
||||
}
|
||||
posings.clear();
|
||||
for (const { shader } of retired.splice(0)) shader.destroy?.();
|
||||
}
|
||||
|
||||
/** The set's host, made once: its models are changed where they are. */
|
||||
function hostOf(record) {
|
||||
if (record.host && !record.host.isDestroyed?.()) return record.host;
|
||||
@@ -337,6 +954,7 @@ export function createModelSets({
|
||||
settle(false);
|
||||
return model.destroy();
|
||||
}
|
||||
if (item.gltf) modelBytes.set(model, item.gltf);
|
||||
entry.next = model;
|
||||
entry.styled = null;
|
||||
style(record, entry, model, true);
|
||||
@@ -413,7 +1031,7 @@ export function createModelSets({
|
||||
if (model.minimumPixelSize !== minimum) model.minimumPixelSize = minimum;
|
||||
if (model.maximumScale !== item.maxScale)
|
||||
model.maximumScale = item.maxScale;
|
||||
const shader = entryShader(entry);
|
||||
const shader = posedShader(entry, model) ?? entryShader(entry);
|
||||
if (model.customShader !== shader) model.customShader = shader;
|
||||
const clip = item.clip === 'belowOrigin';
|
||||
if (Boolean(model.clippingPlanes) !== clip)
|
||||
@@ -583,10 +1201,14 @@ export function createModelSets({
|
||||
notePickIds(record);
|
||||
}
|
||||
|
||||
/** Each frame, before it draws: distance curves, pixel caps and the cull. */
|
||||
/**
|
||||
* Each frame, before it draws: distance curves, pixel caps, the cull and
|
||||
* spinning parts. Whether any shown model spins.
|
||||
*/
|
||||
function beforeRender(sets) {
|
||||
const spinning = turnParts();
|
||||
const eye = scene.camera?.positionWC;
|
||||
if (!eye) return;
|
||||
if (!eye) return spinning;
|
||||
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
|
||||
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
|
||||
let horizon;
|
||||
@@ -677,6 +1299,7 @@ export function createModelSets({
|
||||
if (m) apply(entry, m, frame, hidden);
|
||||
}
|
||||
}
|
||||
return spinning;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -701,5 +1324,5 @@ export function createModelSets({
|
||||
}
|
||||
}
|
||||
|
||||
return { build, upsert, beforeRender, restyle };
|
||||
return { build, upsert, beforeRender, restyle, dispose };
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
advanceSpins,
|
||||
newSpins,
|
||||
partHighlightColor,
|
||||
respin,
|
||||
writePartTexture,
|
||||
} from './drawModels.js';
|
||||
import { partsModelGlb } from '../conformance/partsModel.js';
|
||||
import { glbJson, gltfMeshMatrix, gltfPartTable } from '../modelParts.js';
|
||||
|
||||
/** Floats a part's row of the texture holds. */
|
||||
const ROW = 32;
|
||||
|
||||
/** The part info `drawModels.js` reads from a model's GLB. */
|
||||
function infoOf(glb) {
|
||||
const json = glbJson(glb);
|
||||
const mesh = gltfMeshMatrix(json);
|
||||
// The test models' node transforms are rotations, uniform scales and moves.
|
||||
const s = Math.hypot(mesh[0], mesh[1], mesh[2]);
|
||||
const r = (i, j) => mesh[j * 4 + i] / s;
|
||||
const t = [mesh[12], mesh[13], mesh[14]];
|
||||
const inv = new Array(16).fill(0);
|
||||
for (let i = 0; i < 3; i++)
|
||||
for (let j = 0; j < 3; j++) inv[j * 4 + i] = r(j, i) / s;
|
||||
for (let i = 0; i < 3; i++)
|
||||
inv[12 + i] = -(inv[i] * t[0] + inv[4 + i] * t[1] + inv[8 + i] * t[2]);
|
||||
inv[15] = 1;
|
||||
return { table: gltfPartTable(json), mesh, meshInverse: inv };
|
||||
}
|
||||
|
||||
const row = (data, k, texel) =>
|
||||
Array.from(data.slice(k * ROW + texel * 4, k * ROW + texel * 4 + 4));
|
||||
|
||||
/** A part's matrix in the mesh frame, as rows of 4. */
|
||||
const matrixOf = (data, k) => [0, 1, 2].map((t) => row(data, k, t));
|
||||
/** Its normal matrix, as rows of 3, and whether it is moved. */
|
||||
const normalsOf = (data, k) => ({
|
||||
rows: [3, 4, 5].map((t) => row(data, k, t).slice(0, 3)),
|
||||
moved: row(data, k, 3)[3],
|
||||
});
|
||||
|
||||
const near = (a, b, eps = 1e-5) => a.every((v, i) => Math.abs(v - b[i]) < eps);
|
||||
|
||||
test('a part moved writes its matrix in the mesh’s own frame, the rest identity', () => {
|
||||
for (const node of [{}, { scale: 4, turnDeg: 90, translation: [3, 2, -1] }]) {
|
||||
const info = infoOf(partsModelGlb(node));
|
||||
const data = new Float32Array(4 * ROW);
|
||||
const posed = writePartTexture(
|
||||
info,
|
||||
{ poses: { body: { offsetM: [15, 0, 0] } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.equal(posed, true);
|
||||
// The body's vertex at model (10, −10, −10) lands 15 m to its right
|
||||
// (−Z): back in the model frame through the node's transform.
|
||||
const m = info.mesh;
|
||||
const inv = info.meshInverse;
|
||||
const toMesh = (p) =>
|
||||
[0, 1, 2].map(
|
||||
(i) =>
|
||||
inv[i] * p[0] + inv[4 + i] * p[1] + inv[8 + i] * p[2] + inv[12 + i],
|
||||
);
|
||||
const toModel = (p) =>
|
||||
[0, 1, 2].map(
|
||||
(i) => m[i] * p[0] + m[4 + i] * p[1] + m[8 + i] * p[2] + m[12 + i],
|
||||
);
|
||||
const L = matrixOf(data, 0);
|
||||
const v = [...toMesh([10, -10, -10]), 1];
|
||||
const moved = toModel(L.map((r) => r.reduce((s, x, i) => s + x * v[i], 0)));
|
||||
assert.ok(near(moved, [10, -10, -25], 1e-4), JSON.stringify(moved));
|
||||
// A move turns no normal, but the part is marked moved.
|
||||
const n = normalsOf(data, 0);
|
||||
assert.equal(n.moved, 1);
|
||||
assert.ok(near(n.rows.flat(), [1, 0, 0, 0, 1, 0, 0, 0, 1]));
|
||||
}
|
||||
});
|
||||
|
||||
test('normals turn by the inverse transpose, exact under a stretch', () => {
|
||||
const info = infoOf(partsModelGlb());
|
||||
const data = new Float32Array(4 * ROW);
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { yawDeg: 30 } } },
|
||||
0,
|
||||
[2, 1, 1],
|
||||
data,
|
||||
);
|
||||
const L = matrixOf(data, 1).map((r) => r.slice(0, 3));
|
||||
const { rows: N, moved } = normalsOf(data, 1);
|
||||
assert.equal(moved, 1);
|
||||
// N = L⁻ᵀ: Nᵀ · L is the identity.
|
||||
for (let i = 0; i < 3; i++)
|
||||
for (let j = 0; j < 3; j++) {
|
||||
let sum = 0;
|
||||
for (let k = 0; k < 3; k++) sum += N[k][i] * L[k][j];
|
||||
assert.ok(Math.abs(sum - (i === j ? 1 : 0)) < 1e-4, `${i},${j}: ${sum}`);
|
||||
}
|
||||
// A stretched turn is not a rotation: its own 3×3 would turn normals wrong.
|
||||
assert.ok(!near(N.flat(), L.flat(), 1e-3));
|
||||
// The body, at rest, is left as it is.
|
||||
assert.equal(normalsOf(data, 0).moved, 0);
|
||||
});
|
||||
|
||||
test('a highlight that is not true or a colour draws none, and never throws', () => {
|
||||
const info = infoOf(partsModelGlb());
|
||||
const data = new Float32Array(4 * ROW);
|
||||
for (const highlight of ['', 'not a colour', 0, [1, 'x', 0], {}]) {
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { highlight } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.deepEqual(row(data, 1, 6), [0, 0, 0, 0], String(highlight));
|
||||
}
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { highlight: true } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.equal(row(data, 1, 6)[3], 1);
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { highlight: [0, 1, 0] } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.deepEqual(row(data, 1, 6), [0, 1, 0, 1]);
|
||||
assert.equal(partHighlightColor('#00f').blue, 1);
|
||||
assert.equal(partHighlightColor('nope'), null);
|
||||
assert.equal(partHighlightColor(false), null);
|
||||
});
|
||||
|
||||
test('a hidden part collapses, its normals left alone', () => {
|
||||
const info = infoOf(partsModelGlb());
|
||||
const data = new Float32Array(4 * ROW);
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { hidden: true } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.ok(
|
||||
matrixOf(data, 1)
|
||||
.flat()
|
||||
.every((v) => v === 0),
|
||||
);
|
||||
assert.equal(normalsOf(data, 1).moved, 0);
|
||||
assert.ok(data.every(Number.isFinite));
|
||||
});
|
||||
|
||||
test('spins keep their angle when their rate changes, and stop where they are', () => {
|
||||
const { table } = infoOf(partsModelGlb());
|
||||
const spins = newSpins(0);
|
||||
respin(spins, table, { spin: { pod: 90 } }, 0, () => 10);
|
||||
assert.equal(spins.angles.pod, 10);
|
||||
advanceSpins(spins, 1);
|
||||
assert.equal(spins.angles.pod, 100);
|
||||
// Twice as fast from here: no jump at the change.
|
||||
respin(spins, table, { spin: { pod: 180 } }, 1.5);
|
||||
assert.equal(spins.angles.pod, 145);
|
||||
advanceSpins(spins, 2);
|
||||
assert.equal(spins.angles.pod, 235);
|
||||
// Stopped: the angle stays; a name without an axis or a rate of 0 spins nothing.
|
||||
respin(spins, table, { spin: { body: 50, missing: 5, pod: 0 } }, 3);
|
||||
assert.equal(spins.angles.pod, (235 + 180) % 360);
|
||||
assert.equal(spins.rates.size, 0);
|
||||
advanceSpins(spins, 10);
|
||||
assert.equal(spins.angles.pod, (235 + 180) % 360);
|
||||
});
|
||||
@@ -85,6 +85,7 @@ export const CESIUM_CHECKS = new Set([
|
||||
'draw.models.tint',
|
||||
'draw.models.blend',
|
||||
'draw.models.update',
|
||||
'draw.models.parts',
|
||||
'draw.motion',
|
||||
'draw.motion.arc',
|
||||
'draw.motion.climb',
|
||||
|
||||
@@ -300,3 +300,17 @@ export function creditDisplayContents(display) {
|
||||
export function materialTexture(material, uniform) {
|
||||
return material?._textures?.[uniform];
|
||||
}
|
||||
|
||||
/**
|
||||
* The texture a custom shader holds for a texture uniform, once it has made
|
||||
* it. A custom shader takes a new texture uniform only as a texture it makes
|
||||
* (and the old one it destroys) on its next update; `drawModels.js` writes a
|
||||
* posed model's part matrices into this texture in place instead, each frame
|
||||
* a part spins.
|
||||
* @param {object} shader Cesium CustomShader.
|
||||
* @param {string} uniform The uniform's name.
|
||||
* @returns {object|undefined} Cesium Texture.
|
||||
*/
|
||||
export function customShaderTexture(shader, uniform) {
|
||||
return shader?._textureManager?.getTexture?.(uniform);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
closeRenderLoopLatch,
|
||||
commandExtents,
|
||||
creditDisplayContents,
|
||||
customShaderTexture,
|
||||
defaultView,
|
||||
globeTilesDrawn,
|
||||
lastRenderTime,
|
||||
@@ -70,6 +71,7 @@ test('every private field the app reaches is still declared by the installed Ces
|
||||
[ENGINE, 'Scene/CreditDisplay.js', '_currentFrameCredits'],
|
||||
[ENGINE, 'Scene/CreditDisplay.js', '_currentCesiumCredit'],
|
||||
[ENGINE, 'Scene/Material.js', '_textures'],
|
||||
[ENGINE, 'Scene/Model/CustomShader.js', '_textureManager'],
|
||||
];
|
||||
const missing = fields.filter(
|
||||
([root, file, field]) =>
|
||||
@@ -281,6 +283,18 @@ test('private Cesium fields are reached only through internals.js', () => {
|
||||
assert.deepEqual([...new Set(offenders)], []);
|
||||
});
|
||||
|
||||
test('customShaderTexture reads the texture a custom shader made for a uniform', () => {
|
||||
const texture = {};
|
||||
const shader = {
|
||||
_textureManager: {
|
||||
getTexture: (name) => (name === 'u_a' ? texture : undefined),
|
||||
},
|
||||
};
|
||||
assert.equal(customShaderTexture(shader, 'u_a'), texture);
|
||||
assert.equal(customShaderTexture(shader, 'u_b'), undefined);
|
||||
assert.equal(customShaderTexture(undefined, 'u_a'), undefined);
|
||||
});
|
||||
|
||||
test('trimGlobeTiles empties the globe cache of what the frame did not draw', () => {
|
||||
const trims = [];
|
||||
trimGlobeTiles({
|
||||
|
||||
@@ -70,6 +70,8 @@ const GLOBE_CAPABILITIES = [
|
||||
export function cesiumCapabilities(scene, only) {
|
||||
const all = [
|
||||
'models',
|
||||
// Moving parts posed in a custom shader per posed model (`drawModels.js`).
|
||||
'modelParts',
|
||||
// Cesium scatters drawn models through the atmosphere wherever the
|
||||
// scene draws fog (its models' atmosphere stage).
|
||||
'modelAtmosphere',
|
||||
|
||||
@@ -33,7 +33,14 @@ test('capabilities follow what the scene supports', () => {
|
||||
'vectorBase',
|
||||
];
|
||||
const globe = { show: true };
|
||||
const draw = ['models', 'modelAtmosphere', 'quads', 'meshes', 'fields'];
|
||||
const draw = [
|
||||
'models',
|
||||
'modelParts',
|
||||
'modelAtmosphere',
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
];
|
||||
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
|
||||
// A scene with a globe reads its visibility back.
|
||||
assert.deepEqual(cesiumCapabilities({ globe }), [
|
||||
|
||||
@@ -14,6 +14,7 @@ import { AUSTIN, SCRIPT_VIEWPORT } from '../cameraScripts.js';
|
||||
import { deepEqual, equal, near, nearVec, ok, throws } from '../expect.js';
|
||||
import { iconPosition } from '../../motion/iconMotion.js';
|
||||
import { encodeVectorTile } from '../../vectorBase/encode.js';
|
||||
import { partsModelGlb } from '../partsModel.js';
|
||||
|
||||
/** 1 × 1 PNGs (red, green, blue), so imagery checks load nothing from the network. */
|
||||
const PIXEL_PNGS = [
|
||||
@@ -4123,6 +4124,183 @@ export function portChecks() {
|
||||
},
|
||||
{ capability: 'models' },
|
||||
),
|
||||
check(
|
||||
'draw.models.parts',
|
||||
'a model’s parts are moved, hidden, clamped and spun live, without loading again',
|
||||
async (h, r) => {
|
||||
await overAustin(h, r, 200);
|
||||
const set = r.draw.models({ id: 'conf:models.parts' });
|
||||
const ready = [];
|
||||
const failed = [];
|
||||
set.on('ready', (id) => ready.push(id));
|
||||
set.on('loadFailed', (id) => failed.push(id));
|
||||
// `partsModel.js`: a body, a pod on it, a ram on that, an arm ahead.
|
||||
const models = {
|
||||
m: partsModelGlb(),
|
||||
// The same model, its mesh node turned, scaled and moved.
|
||||
n: partsModelGlb({ scale: 4, turnDeg: 90, translation: [3, 2, -1] }),
|
||||
};
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
const model = (id, parts, extra = {}) => ({
|
||||
id,
|
||||
pos,
|
||||
url: `conformance:parts-model-${id}.glb`,
|
||||
gltf: models[id],
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
environmentMap: false,
|
||||
meta: { n: 1 },
|
||||
...extra,
|
||||
...(parts ? { parts } : {}),
|
||||
});
|
||||
const metresPerLon = 111320 * Math.cos((AUSTIN.lat * Math.PI) / 180);
|
||||
/** The point `east`, `north` metres from the model, `up` above it. */
|
||||
const at = ([east, north], metres, up = 0) =>
|
||||
h.toEcef({
|
||||
lon: AUSTIN.lon + (east * metres) / metresPerLon,
|
||||
lat: AUSTIN.lat + (north * metres) / 110574,
|
||||
height: up,
|
||||
});
|
||||
const pickedAt = (p) => {
|
||||
const s = r.query.project(p);
|
||||
return (
|
||||
s !== null &&
|
||||
r.query.drillPick(s.x, s.y).some((hit) => hit.set === set.id)
|
||||
);
|
||||
};
|
||||
// The compass, clockwise seen from above.
|
||||
const COMPASS = [
|
||||
[0, 1],
|
||||
[1, 0],
|
||||
[0, -1],
|
||||
[-1, 0],
|
||||
];
|
||||
const clockwise = ([e, n]) => [n, -e];
|
||||
const same = (a, b) => a[0] === b[0] && a[1] === b[1];
|
||||
/** The compass points 15 m off at which the model is picked. */
|
||||
const pickedAround = (up = 0) =>
|
||||
COMPASS.filter((d) => pickedAt(at(d, 15, up)));
|
||||
const picks = h.pixels !== false;
|
||||
const look = async () => {
|
||||
await drawn(h, r, 3);
|
||||
await settled(r);
|
||||
};
|
||||
const show = async (item) => {
|
||||
set.upsert([item]);
|
||||
await look();
|
||||
};
|
||||
set.set([model('m')]);
|
||||
for (let i = 0; i < 600 && !ready.length && !failed.length; i++)
|
||||
await drawn(h, r, 1);
|
||||
deepEqual(ready, ['m'], 'ready');
|
||||
await look();
|
||||
if (picks) ok(pickedAt(pos), 'drawn whole, at rest');
|
||||
|
||||
await show(model('m', { poses: { pod: { hidden: true } } }));
|
||||
if (picks) ok(pickedAt(pos), 'the pod hidden, the body drawn');
|
||||
await show(model('m', { poses: { body: { hidden: true } } }));
|
||||
if (picks) ok(!pickedAt(pos), 'the body hidden, and all riding it');
|
||||
|
||||
// Moves go where they say: forward, then right of that.
|
||||
await show(model('m', { poses: { body: { offsetM: [0, 15, 0] } } }));
|
||||
const ahead = picks ? pickedAround() : [];
|
||||
if (picks) equal(ahead.length, 1, 'moved forward, drawn 15 m one way');
|
||||
await show(model('m', { poses: { body: { offsetM: [15, 0, 0] } } }));
|
||||
if (picks) {
|
||||
ok(!pickedAt(pos), 'moved right, gone from its place');
|
||||
const right = pickedAround();
|
||||
equal(right.length, 1, 'moved right, drawn 15 m one way');
|
||||
ok(
|
||||
ahead.length === 1 &&
|
||||
right.length === 1 &&
|
||||
same(right[0], clockwise(ahead[0])),
|
||||
'its right is a quarter turn clockwise of its forward',
|
||||
);
|
||||
}
|
||||
const forward = ahead[0] ?? COMPASS[0];
|
||||
const rightward = clockwise(forward);
|
||||
const back = clockwise(clockwise(forward));
|
||||
|
||||
// A mesh node turned, scaled and moved: parts move in the model's
|
||||
// frame all the same.
|
||||
set.set([model('n')]);
|
||||
for (let i = 0; i < 600 && ready.length < 2 && !failed.length; i++)
|
||||
await drawn(h, r, 1);
|
||||
deepEqual(ready, ['m', 'n'], 'the turned-node model ready');
|
||||
await show(model('n', { poses: { body: { offsetM: [15, 0, 0] } } }));
|
||||
if (picks) {
|
||||
ok(
|
||||
!pickedAt(pos),
|
||||
'its node turned: moved right, gone from its place',
|
||||
);
|
||||
ok(pickedAt(at(rightward, 15)), 'and drawn 15 m to its right');
|
||||
}
|
||||
set.set([model('m')]);
|
||||
for (let i = 0; i < 600 && ready.length < 3 && !failed.length; i++)
|
||||
await drawn(h, r, 1);
|
||||
await look();
|
||||
|
||||
// Stretched twice its length: a move along it stretches with it.
|
||||
const stretched = { axisScale: [2, 1, 1] };
|
||||
await show(model('m', undefined, stretched));
|
||||
if (picks) ok(!pickedAt(at(back, 30)), 'stretched, it ends 20 m back');
|
||||
await show(
|
||||
model('m', { poses: { body: { offsetM: [0, -7.5, 0] } } }, stretched),
|
||||
);
|
||||
if (picks)
|
||||
ok(
|
||||
pickedAt(at(back, 30)),
|
||||
'moved 7.5 m back stretched, drawn 15 m back',
|
||||
);
|
||||
|
||||
// A slide's travel stays within its limits: the ram stops at 20 m.
|
||||
const ramAhead = at(forward, 20, 23);
|
||||
await show(model('m'));
|
||||
if (picks) ok(!pickedAt(ramAhead), 'the ram at rest, on top');
|
||||
await show(model('m', { poses: { ram: { offsetM: [0, 40, 0] } } }));
|
||||
if (picks) ok(pickedAt(ramAhead), 'pushed 40 m, the ram stops at 20 m');
|
||||
await show(model('m', { deploy: { ram: 1 } }));
|
||||
if (picks) ok(pickedAt(ramAhead), 'deployed, the ram is out 20 m');
|
||||
|
||||
// A hinge's turn stays within its limits: the arm swings 45° left
|
||||
// at most, and not at all to the right.
|
||||
const left = clockwise(back);
|
||||
const armAt = (d, m = 15) => at(d, m, 3);
|
||||
const diagonal = (side) =>
|
||||
h.toEcef({
|
||||
lon: AUSTIN.lon + ((forward[0] + side[0]) * 10.6) / metresPerLon,
|
||||
lat: AUSTIN.lat + ((forward[1] + side[1]) * 10.6) / 110574,
|
||||
height: 3,
|
||||
});
|
||||
if (picks) ok(pickedAt(armAt(forward)), 'the arm at rest, ahead');
|
||||
await show(model('m', { poses: { arm: { yawDeg: -90 } } }));
|
||||
if (picks) {
|
||||
ok(!pickedAt(armAt(forward)), 'turned left, the arm leaves');
|
||||
ok(!pickedAt(armAt(left)), 'and stops short of a quarter turn');
|
||||
ok(pickedAt(diagonal(left)), 'at 45° ahead and to the left');
|
||||
}
|
||||
await show(model('m', { poses: { arm: { yawDeg: 90 } } }));
|
||||
if (picks) {
|
||||
ok(!pickedAt(armAt(rightward)), 'turned right, the arm does not');
|
||||
ok(pickedAt(armAt(forward)), 'and stays ahead');
|
||||
}
|
||||
|
||||
await show(
|
||||
model('m', {
|
||||
spin: { pod: 90 },
|
||||
deploy: { pod: 1, missing: 1 },
|
||||
poses: { pod: { highlight: true }, missing: { hidden: true } },
|
||||
}),
|
||||
);
|
||||
if (picks) ok(pickedAt(pos), 'spinning and highlighted, where it is');
|
||||
await show(model('m'));
|
||||
if (picks) ok(pickedAt(pos), 'back at rest');
|
||||
deepEqual(ready, ['m', 'n', 'm'], 'posed without loading again');
|
||||
deepEqual(failed, [], 'nothing failed');
|
||||
equal(set.size(), 1, 'one model');
|
||||
set.dispose();
|
||||
},
|
||||
{ capability: ['models', 'modelParts'] },
|
||||
),
|
||||
|
||||
// --- Query -------------------------------------------------------------
|
||||
check(
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* @module render/conformance/partsModel
|
||||
* @description A glTF model with moving parts, built in code for the
|
||||
* conformance checks (`PARTS_MODEL_TABLE` says what its parts are). One
|
||||
* mesh whose vertices carry their part index (`_PART`), its node scaled
|
||||
* (by ten unless told otherwise: the mesh is in tenths of the model's
|
||||
* metres), and the part table in that node's `extras`.
|
||||
*/
|
||||
|
||||
/** Each cube face: its normal and two axes across it. */
|
||||
const FACES = [
|
||||
[
|
||||
[1, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[-1, 0, 0],
|
||||
[0, 0, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 0, 1],
|
||||
[1, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, -1, 0],
|
||||
[1, 0, 0],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[0, 0, 1],
|
||||
[1, 0, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, -1],
|
||||
[0, 1, 0],
|
||||
[1, 0, 0],
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Append a cube of half size `half` centred at `centre` (the model's glTF
|
||||
* frame, metres) as part `part`, its vertices and normals put into the
|
||||
* mesh's own frame by `toMesh`.
|
||||
*/
|
||||
function cube(mesh, centre, half, part, toMesh) {
|
||||
for (const [n, u, v] of FACES) {
|
||||
const base = mesh.positions.length / 3;
|
||||
for (const [su, sv] of [
|
||||
[-1, -1],
|
||||
[1, -1],
|
||||
[1, 1],
|
||||
[-1, 1],
|
||||
]) {
|
||||
const p = [0, 1, 2].map(
|
||||
(i) => centre[i] + half * (n[i] + su * u[i] + sv * v[i]),
|
||||
);
|
||||
mesh.positions.push(...toMesh.point(p));
|
||||
mesh.normals.push(...toMesh.direction(n));
|
||||
mesh.parts.push(part);
|
||||
}
|
||||
// Counter-clockwise seen from outside: u × v is the normal.
|
||||
mesh.indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table, in the model's glTF frame (forward −X, up +Y, right −Z):
|
||||
* a 20 m cube (`body`) centred on the origin; a 10 m cube on top of it
|
||||
* (`pod`) that spins about the vertical through its centre; a 6 m cube on
|
||||
* top of that (`ram`) that slides forward up to 20 m; and a 6 m cube 15 m
|
||||
* ahead of the body at its foot (`arm`), hinged about the vertical through
|
||||
* the body's centre, turning up to 45° to the left.
|
||||
*/
|
||||
export const PARTS_MODEL_TABLE = Object.freeze([
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'pod', kind: 'spin', pivot: [0, 15, 0], axis: [0, 1, 0] },
|
||||
{
|
||||
name: 'ram',
|
||||
kind: 'slide',
|
||||
pivot: [0, 23, 0],
|
||||
axis: [-1, 0, 0],
|
||||
limits: [0, 20],
|
||||
rest: 0,
|
||||
},
|
||||
{
|
||||
name: 'arm',
|
||||
kind: 'hinge',
|
||||
pivot: [0, 3, 0],
|
||||
axis: [0, 1, 0],
|
||||
limits: [0, 45],
|
||||
rest: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
/** Each part's cube: its centre (glTF frame, metres) and half size. */
|
||||
const CUBES = [
|
||||
[[0, 0, 0], 10],
|
||||
[[0, 15, 0], 5],
|
||||
[[0, 23, 0], 3],
|
||||
[[-15, 3, 0], 3],
|
||||
];
|
||||
|
||||
/**
|
||||
* The model's GLB bytes. Its mesh node is scaled by `scale`, turned
|
||||
* `turnDeg` about its vertical and moved by `translation`; the mesh is
|
||||
* built in that node's own frame, so the model it draws is the same
|
||||
* whatever the node's transform.
|
||||
* @param {{scale?: number, turnDeg?: number,
|
||||
* translation?: [number, number, number]}} [node]
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
export function partsModelGlb({
|
||||
scale = 10,
|
||||
turnDeg = 0,
|
||||
translation = [0, 0, 0],
|
||||
} = {}) {
|
||||
const a = (turnDeg * Math.PI) / 180;
|
||||
const c = Math.cos(a);
|
||||
const sn = Math.sin(a);
|
||||
// The node's turn undone: about +Y by −turnDeg.
|
||||
const unturn = ([x, y, z]) => [c * x - sn * z, y, sn * x + c * z];
|
||||
const toMesh = {
|
||||
point: (p) =>
|
||||
unturn([0, 1, 2].map((i) => p[i] - translation[i])).map((v) => v / scale),
|
||||
direction: unturn,
|
||||
};
|
||||
const mesh = { positions: [], normals: [], parts: [], indices: [] };
|
||||
CUBES.forEach(([centre, half], part) =>
|
||||
cube(mesh, centre, half, part, toMesh),
|
||||
);
|
||||
const count = mesh.parts.length;
|
||||
const positions = new Float32Array(mesh.positions);
|
||||
const normals = new Float32Array(mesh.normals);
|
||||
// A vertex attribute's elements sit on 4-byte boundaries.
|
||||
const parts = new Uint8Array(count * 4);
|
||||
mesh.parts.forEach((part, i) => (parts[i * 4] = part));
|
||||
const indices = new Uint16Array(mesh.indices);
|
||||
const chunks = [positions, normals, parts, indices];
|
||||
const offsets = [];
|
||||
let length = 0;
|
||||
for (const chunk of chunks) {
|
||||
offsets.push(length);
|
||||
length += Math.ceil(chunk.byteLength / 4) * 4;
|
||||
}
|
||||
const bin = new Uint8Array(length);
|
||||
chunks.forEach((chunk, i) =>
|
||||
bin.set(
|
||||
new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
|
||||
offsets[i],
|
||||
),
|
||||
);
|
||||
const min = [Infinity, Infinity, Infinity];
|
||||
const max = [-Infinity, -Infinity, -Infinity];
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
min[i % 3] = Math.min(min[i % 3], positions[i]);
|
||||
max[i % 3] = Math.max(max[i % 3], positions[i]);
|
||||
}
|
||||
const json = {
|
||||
asset: { version: '2.0' },
|
||||
scene: 0,
|
||||
scenes: [{ nodes: [0] }],
|
||||
nodes: [
|
||||
{
|
||||
name: 'parts',
|
||||
mesh: 0,
|
||||
scale: [scale, scale, scale],
|
||||
rotation: [0, Math.sin(a / 2), 0, Math.cos(a / 2)],
|
||||
translation,
|
||||
extras: { parts: PARTS_MODEL_TABLE },
|
||||
},
|
||||
],
|
||||
meshes: [
|
||||
{
|
||||
primitives: [
|
||||
{
|
||||
attributes: { POSITION: 0, NORMAL: 1, _PART: 2 },
|
||||
indices: 3,
|
||||
material: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
materials: [
|
||||
{
|
||||
pbrMetallicRoughness: {
|
||||
baseColorFactor: [1, 1, 1, 1],
|
||||
metallicFactor: 0,
|
||||
roughnessFactor: 1,
|
||||
},
|
||||
},
|
||||
],
|
||||
buffers: [{ byteLength: length }],
|
||||
bufferViews: [
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[0],
|
||||
byteLength: positions.byteLength,
|
||||
target: 34962,
|
||||
},
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[1],
|
||||
byteLength: normals.byteLength,
|
||||
target: 34962,
|
||||
},
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[2],
|
||||
byteLength: parts.byteLength,
|
||||
byteStride: 4,
|
||||
target: 34962,
|
||||
},
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[3],
|
||||
byteLength: indices.byteLength,
|
||||
target: 34963,
|
||||
},
|
||||
],
|
||||
accessors: [
|
||||
{
|
||||
bufferView: 0,
|
||||
componentType: 5126,
|
||||
count,
|
||||
type: 'VEC3',
|
||||
min,
|
||||
max,
|
||||
},
|
||||
{ bufferView: 1, componentType: 5126, count, type: 'VEC3' },
|
||||
{ bufferView: 2, componentType: 5121, count, type: 'SCALAR' },
|
||||
{
|
||||
bufferView: 3,
|
||||
componentType: 5123,
|
||||
count: indices.length,
|
||||
type: 'SCALAR',
|
||||
},
|
||||
],
|
||||
};
|
||||
let text = new TextEncoder().encode(JSON.stringify(json));
|
||||
const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20);
|
||||
padded.set(text);
|
||||
text = padded;
|
||||
const total = 12 + 8 + text.length + 8 + bin.length;
|
||||
const out = new Uint8Array(total);
|
||||
const view = new DataView(out.buffer);
|
||||
view.setUint32(0, 0x46546c67, true);
|
||||
view.setUint32(4, 2, true);
|
||||
view.setUint32(8, total, true);
|
||||
view.setUint32(12, text.length, true);
|
||||
view.setUint32(16, 0x4e4f534a, true);
|
||||
out.set(text, 20);
|
||||
const binAt = 20 + text.length;
|
||||
view.setUint32(binAt, bin.length, true);
|
||||
view.setUint32(binAt + 4, 0x004e4942, true);
|
||||
out.set(bin, binAt + 8);
|
||||
return out;
|
||||
}
|
||||
Vendored
+2
@@ -191,6 +191,8 @@ export type Capability =
|
||||
| 'motionSegments'
|
||||
/** glTF models. */
|
||||
| 'models'
|
||||
/** Moving parts of glTF models posed as an item's `parts` says. */
|
||||
| 'modelParts'
|
||||
/** Image, video and canvas planes. */
|
||||
| 'quads'
|
||||
/** Custom meshes in a local east-north-up frame. */
|
||||
|
||||
Vendored
+59
@@ -450,6 +450,65 @@ export interface ModelItem extends Placed {
|
||||
* change live.
|
||||
*/
|
||||
focus?: number;
|
||||
/**
|
||||
* `modelParts`: how the model's moving parts are posed. Applies to a
|
||||
* model whose mesh carries a `_PART` vertex attribute (each vertex's part
|
||||
* index) and whose root node's glTF `extras.parts` is its part table;
|
||||
* ignored for any other. Omitted, or without the capability, the model is
|
||||
* drawn whole, at rest, as its file draws it. Can change live, without
|
||||
* loading the model again.
|
||||
*/
|
||||
parts?: ModelPartState;
|
||||
}
|
||||
|
||||
/**
|
||||
* A model's part state (`ModelItem.parts`), each member by part name; a
|
||||
* part not named is at rest, and a name the model's part table lacks is
|
||||
* ignored. The maths is `render/modelParts`'s `partMatrices`: about each
|
||||
* part's pivot, its deploy fraction first, then its spin, then its pose,
|
||||
* then its parent part's whole motion.
|
||||
*/
|
||||
export interface ModelPartState {
|
||||
/**
|
||||
* Degrees a second about the part's axis, which the renderer advances
|
||||
* itself on its own clock each frame: a turning rotor costs the
|
||||
* application no write per frame. A change of rate goes on from the angle
|
||||
* reached, without a jump; a part that stops spinning stays where it is.
|
||||
*/
|
||||
spin?: Record<string, number>;
|
||||
/**
|
||||
* 0 (stowed, the table's first limit) to 1 (deployed, its second): a
|
||||
* hinge or deploy part turned, a slide or separable part moved along its
|
||||
* axis, that far between its limits. Clamped to 0..1.
|
||||
*/
|
||||
deploy?: Record<string, number>;
|
||||
/** Each part's pose, on top of its spin and deploy fraction. */
|
||||
poses?: Record<string, PartPose>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One part's pose about its pivot, in the model's own frame (in its glTF:
|
||||
* forward −X, up +Y, right −Z). A hinge or deploy part's turn about its
|
||||
* axis stays within its limits, as does a slide part's travel; the rest of
|
||||
* every part's motion is free. A number that is not finite counts as 0.
|
||||
*/
|
||||
export interface PartPose {
|
||||
/** Metres along the model's right, forward and up. */
|
||||
offsetM?: [right: number, forward: number, up: number];
|
||||
/** Degrees clockwise seen from above, as a heading. Applied first. */
|
||||
yawDeg?: number;
|
||||
/** Degrees nose up. Applied after the yaw. */
|
||||
pitchDeg?: number;
|
||||
/** Degrees clockwise looking forward. Applied last. */
|
||||
rollDeg?: number;
|
||||
/** Not drawn, nor any part riding it. */
|
||||
hidden?: boolean;
|
||||
/**
|
||||
* Drawn in a highlight colour: `true` for the renderer's own, or a
|
||||
* colour. Anything else, or a colour the renderer cannot read, draws no
|
||||
* highlight. Not inherited by the parts riding it.
|
||||
*/
|
||||
highlight?: boolean | Color;
|
||||
}
|
||||
|
||||
/** A plane showing an image, a video or a canvas. */
|
||||
|
||||
@@ -34,6 +34,7 @@ export const CAPABILITIES = Object.freeze([
|
||||
'columns',
|
||||
'motionSegments',
|
||||
'models',
|
||||
'modelParts',
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
|
||||
Vendored
+86
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* A model's moving parts (`modelParts.js`): its part table and the maths
|
||||
* that turns a model item's `parts` into one matrix per part, so a renderer
|
||||
* that poses parts draws exactly those.
|
||||
*/
|
||||
import type { ModelPartState } from './contract/index';
|
||||
|
||||
/** What a part does: what live data drives and what is offered first. */
|
||||
export type PartKind =
|
||||
'body' | 'spin' | 'hinge' | 'slide' | 'deploy' | 'separable' | 'marker';
|
||||
|
||||
/** `[x, y, z]`. */
|
||||
export type PartVec3 = readonly [number, number, number];
|
||||
|
||||
/** One part of a model, as its table gives it (glTF frame, metres and degrees). */
|
||||
export interface ModelPart {
|
||||
/** Its `_PART` index. */
|
||||
readonly index: number;
|
||||
readonly name: string;
|
||||
readonly kind: PartKind;
|
||||
/** The part it rides, or null for the body. */
|
||||
readonly parent: string | null;
|
||||
/** Its parent's index, or -1 for the body. */
|
||||
readonly parentIndex: number;
|
||||
/** The point it turns about; the origin for the body. */
|
||||
readonly pivot: PartVec3;
|
||||
/** Its axis of motion, unit length; null where the table gives none. */
|
||||
readonly axis: PartVec3 | null;
|
||||
/** `[stowed, deployed]`: degrees for hinge and deploy, metres for slide and separable. */
|
||||
readonly limits: readonly [number, number] | null;
|
||||
/** The value it is drawn at in the file; null without limits. */
|
||||
readonly rest: number | null;
|
||||
}
|
||||
|
||||
/** A model's part table: its parts in `_PART` index order, the body first. */
|
||||
export interface PartTable {
|
||||
readonly parts: readonly ModelPart[];
|
||||
/** A part's index by its name. */
|
||||
readonly byName: ReadonlyMap<string, number>;
|
||||
}
|
||||
|
||||
/** Where and how `partMatrices` writes. */
|
||||
export interface PartMatricesOptions {
|
||||
/** Where in `out` the first matrix goes; 0 by default. */
|
||||
readonly offset?: number;
|
||||
/** Gets each part's `PART_HIDDEN` and `PART_HIGHLIGHT`, from `flagsOffset`. */
|
||||
readonly flags?: Uint8Array;
|
||||
readonly flagsOffset?: number;
|
||||
/** The model's stretch along its glTF axes (`axisScale`): parts then turn rigidly in the stretched model. */
|
||||
readonly scale?: PartVec3 | null;
|
||||
}
|
||||
|
||||
export const PART_KINDS: readonly PartKind[];
|
||||
export const PART_HIDDEN: 1;
|
||||
export const PART_HIGHLIGHT: 2;
|
||||
|
||||
/** Whether a pose's `highlight` asks for one: true, or a colour (a non-empty string, or three or four finite numbers). */
|
||||
export function asksHighlight(value: unknown): boolean;
|
||||
|
||||
/** The part table in a node's glTF `extras`; null when it has none. Throws on a malformed table. */
|
||||
export function partTableOf(extras: unknown): PartTable | null;
|
||||
|
||||
/** The glTF JSON of a GLB. Throws when the bytes are not a GLB. */
|
||||
export function glbJson(glb: Uint8Array | ArrayBuffer): Record<string, unknown>;
|
||||
|
||||
/** The part table of a glTF document; null when no node has one. */
|
||||
export function gltfPartTable(gltf: Record<string, unknown>): PartTable | null;
|
||||
|
||||
/** The part table of a GLB's bytes; null for a model without one. */
|
||||
export function readPartTable(glb: Uint8Array | ArrayBuffer): PartTable | null;
|
||||
|
||||
/** Where the scene's first mesh is drawn: its node's transform with its parents', column-major 4×4. */
|
||||
export function gltfMeshMatrix(gltf: Record<string, unknown>): number[];
|
||||
|
||||
/**
|
||||
* Each part's column-major 4×4 matrix for `state` at `timeS` seconds into
|
||||
* `out`, in `_PART` order, in the model's glTF frame. Whether any part is
|
||||
* not at rest.
|
||||
*/
|
||||
export function partMatrices(
|
||||
table: PartTable,
|
||||
state: ModelPartState | null | undefined,
|
||||
timeS: number,
|
||||
out: Float32Array | Float64Array,
|
||||
options?: PartMatricesOptions,
|
||||
): boolean;
|
||||
@@ -0,0 +1,696 @@
|
||||
/**
|
||||
* @module render/modelParts
|
||||
* @description A model's moving parts: the part table a glTF model carries
|
||||
* and the pure maths that turns a model item's `parts` (`ModelPartState`)
|
||||
* into one matrix per part. Plain JavaScript: no fetch, no DOM, no engine.
|
||||
*
|
||||
* **The model.** One glTF mesh whose vertices carry a part index (`_PART`, an
|
||||
* unsigned byte). The root node's glTF `extras.parts` lists the parts in
|
||||
* `_PART` index order: `{name, kind, pivot, axis, limits, rest, parent}`,
|
||||
* glTF Y-up, metres and degrees; index 0 is the body. A model that is only
|
||||
* its body carries no table.
|
||||
*
|
||||
* **Frames.** The table, and the matrices {@link partMatrices} writes, are
|
||||
* in the model's glTF frame (Y up, nose −X, so right is −Z), applied after
|
||||
* the mesh node's own transform (a packed model's dequantization;
|
||||
* {@link gltfMeshMatrix}). Poses are given in `[right, forward, up]` metres,
|
||||
* with yaw (clockwise from above, as a heading), pitch (nose up) and roll
|
||||
* (clockwise looking forward), applied yaw, then pitch, then roll.
|
||||
*
|
||||
* **A part's motion**, about its pivot, innermost first: its deploy
|
||||
* fraction, then its spin, then its pose, then its parent part's whole
|
||||
* motion, so a child rides its parent. A hinge or deploy part's turn about
|
||||
* its axis is clamped to its limits, as is a slide part's travel along its
|
||||
* axis; a part's other motion, and a spin, separable, marker or body part's,
|
||||
* is free.
|
||||
*/
|
||||
|
||||
/** What a part does: what live data drives and what is offered first. */
|
||||
export const PART_KINDS = Object.freeze([
|
||||
'body',
|
||||
'spin',
|
||||
'hinge',
|
||||
'slide',
|
||||
'deploy',
|
||||
'separable',
|
||||
'marker',
|
||||
]);
|
||||
|
||||
/** {@link partMatrices}'s flags per part: not drawn. */
|
||||
export const PART_HIDDEN = 1;
|
||||
/** {@link partMatrices}'s flags per part: highlighted. */
|
||||
export const PART_HIGHLIGHT = 2;
|
||||
|
||||
const isObject = (value) =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
function vec3(value, what) {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
value.length !== 3 ||
|
||||
!value.every((n) => typeof n === 'number' && Number.isFinite(n))
|
||||
)
|
||||
throw new Error(`${what} is not three numbers`);
|
||||
return [value[0], value[1], value[2]];
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table in a node's glTF `extras` (`{parts: [...]}`); null when it
|
||||
* has none (a model that is only its body). Throws on a table that is
|
||||
* malformed: a missing or unknown kind, a repeated name, a parent that is
|
||||
* not an earlier part, a malformed pivot, axis or limits.
|
||||
* @param {unknown} extras
|
||||
* @returns {import('./modelParts').PartTable|null}
|
||||
*/
|
||||
export function partTableOf(extras) {
|
||||
if (!isObject(extras) || extras.parts === undefined) return null;
|
||||
const list = extras.parts;
|
||||
if (!Array.isArray(list) || list.length === 0)
|
||||
throw new Error('parts is not a list of parts');
|
||||
if (list.length > 256)
|
||||
throw new Error(`${list.length} parts: _PART is a byte`);
|
||||
const byName = new Map();
|
||||
const parts = list.map((entry, index) => {
|
||||
if (!isObject(entry)) throw new Error(`part ${index} is not an object`);
|
||||
const { name, kind } = entry;
|
||||
if (typeof name !== 'string' || name === '')
|
||||
throw new Error(`part ${index} has no name`);
|
||||
if (byName.has(name)) throw new Error(`part ${name} is named twice`);
|
||||
if (typeof kind !== 'string' || !PART_KINDS.includes(kind))
|
||||
throw new Error(`part ${name} has kind ${String(kind)}`);
|
||||
if ((index === 0) !== (kind === 'body'))
|
||||
throw new Error(`part ${name}: the body, and only it, is part 0`);
|
||||
const parentName = index === 0 ? null : (entry.parent ?? 'body');
|
||||
if (parentName !== null && typeof parentName !== 'string')
|
||||
throw new Error(`part ${name} has parent ${String(parentName)}`);
|
||||
const parentIndex =
|
||||
parentName === null ? -1 : (byName.get(parentName) ?? -2);
|
||||
if (parentIndex === -2)
|
||||
throw new Error(`part ${name} rides ${parentName}, not an earlier part`);
|
||||
const pivot =
|
||||
entry.pivot === undefined ? [0, 0, 0] : vec3(entry.pivot, name);
|
||||
let axis = null;
|
||||
if (entry.axis !== undefined) {
|
||||
const [x, y, z] = vec3(entry.axis, `${name} axis`);
|
||||
const length = Math.hypot(x, y, z);
|
||||
if (!(length > 0)) throw new Error(`part ${name} has a zero axis`);
|
||||
axis = [x / length, y / length, z / length];
|
||||
}
|
||||
let limits = null;
|
||||
const given = entry.limits;
|
||||
if (given !== undefined) {
|
||||
if (
|
||||
!Array.isArray(given) ||
|
||||
given.length !== 2 ||
|
||||
!given.every((n) => typeof n === 'number' && Number.isFinite(n))
|
||||
)
|
||||
throw new Error(`part ${name} limits are not two numbers`);
|
||||
limits = [given[0], given[1]];
|
||||
}
|
||||
const restGiven = entry.rest;
|
||||
if (
|
||||
restGiven !== undefined &&
|
||||
(typeof restGiven !== 'number' || !Number.isFinite(restGiven))
|
||||
)
|
||||
throw new Error(`part ${name} rest is not a number`);
|
||||
const rest = limits === null ? null : (restGiven ?? limits[0]);
|
||||
byName.set(name, index);
|
||||
return {
|
||||
index,
|
||||
name,
|
||||
kind,
|
||||
parent: parentName,
|
||||
parentIndex,
|
||||
pivot,
|
||||
axis,
|
||||
limits,
|
||||
rest,
|
||||
};
|
||||
});
|
||||
return { parts, byName };
|
||||
}
|
||||
|
||||
/**
|
||||
* The glTF JSON of a GLB (its first chunk). Throws when the bytes are not a
|
||||
* GLB.
|
||||
* @param {Uint8Array|ArrayBuffer} glb
|
||||
* @returns {object}
|
||||
*/
|
||||
export function glbJson(glb) {
|
||||
const bytes = glb instanceof Uint8Array ? glb : new Uint8Array(glb);
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (bytes.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67)
|
||||
throw new Error('not a GLB');
|
||||
const length = view.getUint32(12, true);
|
||||
if (view.getUint32(16, true) !== 0x4e4f534a || 20 + length > bytes.byteLength)
|
||||
throw new Error('GLB has no JSON chunk');
|
||||
const json = JSON.parse(
|
||||
new TextDecoder().decode(bytes.subarray(20, 20 + length)),
|
||||
);
|
||||
if (!isObject(json)) throw new Error('GLB JSON is not an object');
|
||||
return json;
|
||||
}
|
||||
|
||||
/** The scene's root node indices, then every node's, in order. */
|
||||
function nodeOrder(gltf) {
|
||||
const nodes = Array.isArray(gltf.nodes) ? gltf.nodes : [];
|
||||
const scenes = Array.isArray(gltf.scenes) ? gltf.scenes : [];
|
||||
const scene = scenes[typeof gltf.scene === 'number' ? gltf.scene : 0];
|
||||
const roots =
|
||||
isObject(scene) && Array.isArray(scene.nodes) ? scene.nodes : [];
|
||||
return { nodes, order: [...roots, ...nodes.keys()] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table of a glTF document: the first node with `extras.parts`,
|
||||
* the scene's root nodes first. Null when no node has one.
|
||||
* @param {object} gltf
|
||||
* @returns {import('./modelParts').PartTable|null}
|
||||
*/
|
||||
export function gltfPartTable(gltf) {
|
||||
const { nodes, order } = nodeOrder(gltf);
|
||||
for (const index of order) {
|
||||
const node = typeof index === 'number' ? nodes[index] : undefined;
|
||||
if (
|
||||
isObject(node) &&
|
||||
isObject(node.extras) &&
|
||||
node.extras.parts !== undefined
|
||||
)
|
||||
return partTableOf(node.extras);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table of a GLB's bytes; null for a model without one. Throws on
|
||||
* bytes that are not a GLB, or on a malformed table.
|
||||
* @param {Uint8Array|ArrayBuffer} glb
|
||||
* @returns {import('./modelParts').PartTable|null}
|
||||
*/
|
||||
export function readPartTable(glb) {
|
||||
return gltfPartTable(glbJson(glb));
|
||||
}
|
||||
|
||||
/** `a · b`, column-major 4×4, into a new array. */
|
||||
function multiply4(a, b) {
|
||||
const out = new Array(16);
|
||||
for (let col = 0; col < 4; col++)
|
||||
for (let row = 0; row < 4; row++) {
|
||||
let sum = 0;
|
||||
for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[col * 4 + k];
|
||||
out[col * 4 + row] = sum;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A glTF node's local transform, column-major. */
|
||||
function nodeMatrix(node) {
|
||||
if (Array.isArray(node.matrix) && node.matrix.length === 16)
|
||||
return [...node.matrix];
|
||||
const [tx, ty, tz] = node.translation ?? [0, 0, 0];
|
||||
const [x, y, z, w] = node.rotation ?? [0, 0, 0, 1];
|
||||
const [sx, sy, sz] = node.scale ?? [1, 1, 1];
|
||||
return [
|
||||
(1 - 2 * (y * y + z * z)) * sx,
|
||||
2 * (x * y + z * w) * sx,
|
||||
2 * (x * z - y * w) * sx,
|
||||
0,
|
||||
2 * (x * y - z * w) * sy,
|
||||
(1 - 2 * (x * x + z * z)) * sy,
|
||||
2 * (y * z + x * w) * sy,
|
||||
0,
|
||||
2 * (x * z + y * w) * sz,
|
||||
2 * (y * z - x * w) * sz,
|
||||
(1 - 2 * (x * x + y * y)) * sz,
|
||||
0,
|
||||
tx,
|
||||
ty,
|
||||
tz,
|
||||
1,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the first mesh of a glTF document's scene is drawn: its node's
|
||||
* transform with every parent's, column-major 4×4. A vertex of the mesh is
|
||||
* at this matrix times its position in the model's glTF frame, where part
|
||||
* matrices apply. The identity for a document without a mesh.
|
||||
* @param {object} gltf
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function gltfMeshMatrix(gltf) {
|
||||
const { nodes } = nodeOrder(gltf);
|
||||
const scenes = Array.isArray(gltf.scenes) ? gltf.scenes : [];
|
||||
const scene = scenes[typeof gltf.scene === 'number' ? gltf.scene : 0];
|
||||
const roots =
|
||||
isObject(scene) && Array.isArray(scene.nodes)
|
||||
? scene.nodes
|
||||
: [...nodes.keys()];
|
||||
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||
// Depth first, the scene's own order: the first node with a mesh.
|
||||
const stack = roots
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((index) => [index, identity, 0]);
|
||||
while (stack.length) {
|
||||
const [index, parent, depth] = stack.pop();
|
||||
const node = nodes[index];
|
||||
if (!isObject(node) || depth > 64) continue;
|
||||
const world = multiply4(parent, nodeMatrix(node));
|
||||
if (typeof node.mesh === 'number') return world;
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
for (let i = children.length - 1; i >= 0; i--)
|
||||
stack.push([children[i], world, depth + 1]);
|
||||
}
|
||||
return identity;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the maths
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
|
||||
/** The `[right, forward, up]` axes in the glTF frame (nose −X, Y up, right −Z). */
|
||||
const RIGHT_G = [0, 0, -1];
|
||||
const FORWARD_G = [-1, 0, 0];
|
||||
const UP_G = [0, 1, 0];
|
||||
|
||||
/** Scratch quaternions `[x, y, z, w]` and vectors, reused between calls. */
|
||||
const _q = new Float64Array(4);
|
||||
const _p = new Float64Array(4);
|
||||
const _v = new Float64Array(3);
|
||||
/** A part's axis in the scaled model, and the instance's scale. */
|
||||
const _a = new Float64Array(3);
|
||||
const _s = new Float64Array(3);
|
||||
|
||||
/** `out` = the rotation by `deg` about the unit `axis`, right-handed. */
|
||||
function axisAngle(out, axis, deg) {
|
||||
const half = (deg * DEG) / 2;
|
||||
const s = Math.sin(half);
|
||||
out[0] = axis[0] * s;
|
||||
out[1] = axis[1] * s;
|
||||
out[2] = axis[2] * s;
|
||||
out[3] = Math.cos(half);
|
||||
}
|
||||
|
||||
/** `a` = `a · b`. */
|
||||
function multiplyInto(a, b) {
|
||||
const ax = a[0];
|
||||
const ay = a[1];
|
||||
const az = a[2];
|
||||
const aw = a[3];
|
||||
const bx = b[0];
|
||||
const by = b[1];
|
||||
const bz = b[2];
|
||||
const bw = b[3];
|
||||
a[0] = aw * bx + ax * bw + ay * bz - az * by;
|
||||
a[1] = aw * by - ax * bz + ay * bw + az * bx;
|
||||
a[2] = aw * bz + ax * by - ay * bx + az * bw;
|
||||
a[3] = aw * bw - ax * bx - ay * by - az * bz;
|
||||
}
|
||||
|
||||
/** `v` turned by the unit quaternion `q`, in place. */
|
||||
function rotateInto(q, v) {
|
||||
const x = q[0];
|
||||
const y = q[1];
|
||||
const z = q[2];
|
||||
const w = q[3];
|
||||
const tx = 2 * (y * v[2] - z * v[1]);
|
||||
const ty = 2 * (z * v[0] - x * v[2]);
|
||||
const tz = 2 * (x * v[1] - y * v[0]);
|
||||
v[0] = v[0] + w * tx + (y * tz - z * ty);
|
||||
v[1] = v[1] + w * ty + (z * tx - x * tz);
|
||||
v[2] = v[2] + w * tz + (x * ty - y * tx);
|
||||
}
|
||||
|
||||
/** A pose's number, or 0 where it is missing or not finite. */
|
||||
const finite = (value) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||
|
||||
/** Whether a pose turns or moves anything (a value not finite counts as 0). */
|
||||
function isPosed(pose) {
|
||||
const o = pose.offsetM;
|
||||
return (
|
||||
finite(pose.yawDeg) !== 0 ||
|
||||
finite(pose.pitchDeg) !== 0 ||
|
||||
finite(pose.rollDeg) !== 0 ||
|
||||
(Array.isArray(o) &&
|
||||
(finite(o[0]) !== 0 || finite(o[1]) !== 0 || finite(o[2]) !== 0))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `q` = a pose's rotation in the glTF frame: yaw clockwise about up, then
|
||||
* pitch about the new right, then roll about the new forward. `t` = its
|
||||
* offset in the glTF frame.
|
||||
*/
|
||||
function poseInto(q, t, pose) {
|
||||
axisAngle(q, UP_G, -finite(pose.yawDeg));
|
||||
axisAngle(_p, RIGHT_G, finite(pose.pitchDeg));
|
||||
multiplyInto(q, _p);
|
||||
axisAngle(_p, FORWARD_G, finite(pose.rollDeg));
|
||||
multiplyInto(q, _p);
|
||||
const o = pose.offsetM;
|
||||
t[0] = 0;
|
||||
t[1] = 0;
|
||||
t[2] = 0;
|
||||
if (!Array.isArray(o)) return;
|
||||
t[0] = -finite(o[1]);
|
||||
t[1] = finite(o[2]);
|
||||
t[2] = -finite(o[0]);
|
||||
}
|
||||
|
||||
/** `angle` (degrees) as the value nearest `[lo, hi]` among its turns, clamped into it. */
|
||||
function clampAngle(angle, lo, hi) {
|
||||
let best = angle;
|
||||
let bestOut = Infinity;
|
||||
for (const turn of [-360, 0, 360]) {
|
||||
const a = angle + turn;
|
||||
const out = a < lo ? lo - a : a > hi ? a - hi : 0;
|
||||
if (out < bestOut) {
|
||||
best = a;
|
||||
bestOut = out;
|
||||
}
|
||||
}
|
||||
return Math.min(hi, Math.max(lo, best));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp the rotation `q`'s turn about the unit `axis` (its twist, degrees
|
||||
* from rest) so that `rest` plus it stays within `limits`, leaving the rest
|
||||
* of the rotation (its swing) as it is.
|
||||
*/
|
||||
function clampTwist(q, axis, rest, limits) {
|
||||
const d = q[0] * axis[0] + q[1] * axis[1] + q[2] * axis[2];
|
||||
const w = q[3];
|
||||
if (Math.abs(d) < 1e-12 && Math.abs(w) < 1e-12) return;
|
||||
let twist = (2 * Math.atan2(d, w)) / DEG;
|
||||
if (twist > 180) twist -= 360;
|
||||
else if (twist <= -180) twist += 360;
|
||||
const lo = Math.min(limits[0], limits[1]) - rest;
|
||||
const hi = Math.max(limits[0], limits[1]) - rest;
|
||||
const clamped = clampAngle(twist, lo, hi);
|
||||
if (Math.abs(clamped - twist) < 1e-9) return;
|
||||
// q = swing · twist, so q' = q · twist⁻¹ · twist'.
|
||||
axisAngle(_p, axis, clamped - twist);
|
||||
multiplyInto(q, _p);
|
||||
}
|
||||
|
||||
/** The degrees or metres from rest a deploy fraction puts a part at. */
|
||||
function deployedBy(part, fraction) {
|
||||
const limits = part.limits;
|
||||
const f = Math.min(1, Math.max(0, fraction));
|
||||
return limits[0] + (limits[1] - limits[0]) * f - part.rest;
|
||||
}
|
||||
|
||||
/**
|
||||
* World (model frame) rotation and translation per part, 12 numbers each (R
|
||||
* row-major, then t), and whether each is hidden; reused between calls.
|
||||
*/
|
||||
let _world = new Float64Array(12 * 32);
|
||||
let _hidden = new Uint8Array(32);
|
||||
/** A pose's rotation, its translation, and one part's local affine, scratch. */
|
||||
const _r = new Float64Array(4);
|
||||
const _t = new Float64Array(3);
|
||||
const _local = new Float64Array(12);
|
||||
|
||||
const IDENTITY = Float64Array.of(
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
);
|
||||
|
||||
const TURNS = new Set(['spin', 'hinge', 'deploy']);
|
||||
const MOVES = new Set(['slide', 'separable']);
|
||||
|
||||
/** Write the unit quaternion `q` and translation `t` as an affine (R row-major, then t) into `m` at `at`. */
|
||||
function affineInto(q, t, m, at) {
|
||||
const x = q[0];
|
||||
const y = q[1];
|
||||
const z = q[2];
|
||||
const w = q[3];
|
||||
m[at] = 1 - 2 * (y * y + z * z);
|
||||
m[at + 1] = 2 * (x * y - z * w);
|
||||
m[at + 2] = 2 * (x * z + y * w);
|
||||
m[at + 3] = 2 * (x * y + z * w);
|
||||
m[at + 4] = 1 - 2 * (x * x + z * z);
|
||||
m[at + 5] = 2 * (y * z - x * w);
|
||||
m[at + 6] = 2 * (x * z - y * w);
|
||||
m[at + 7] = 2 * (y * z + x * w);
|
||||
m[at + 8] = 1 - 2 * (x * x + y * y);
|
||||
m[at + 9] = t[0];
|
||||
m[at + 10] = t[1];
|
||||
m[at + 11] = t[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a highlight asks for one: true, or a colour (a non-empty string,
|
||||
* or three or four finite numbers). A renderer that cannot read the
|
||||
* colour draws the part without one.
|
||||
*/
|
||||
export function asksHighlight(value) {
|
||||
if (value === true) return true;
|
||||
if (typeof value === 'string') return value.trim() !== '';
|
||||
return (
|
||||
Array.isArray(value) &&
|
||||
(value.length === 3 || value.length === 4) &&
|
||||
value.every((v) => typeof v === 'number' && Number.isFinite(v))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write each part's matrix (4×4, column-major) for a model whose item has
|
||||
* `state` as its `parts`, at `timeS` seconds of the renderer's clock, into
|
||||
* `out`: `table.parts.length` matrices, in `_PART` order, in the model's
|
||||
* glTF frame. A vertex of part k is drawn at matrix k times its position
|
||||
* (after the mesh node's transform). A hidden part's matrix, and every
|
||||
* part's riding it, is all zeros.
|
||||
*
|
||||
* With `options.scale` S (the model drawn stretched along its glTF axes,
|
||||
* `axisScale`), each matrix X is S⁻¹·Part_s·S, where Part_s is the part's
|
||||
* motion worked out in the stretched model (its pivot, axis and moves scaled
|
||||
* by S), so S·X·v = Part_s·S·v: a radar on a hull drawn twice its length
|
||||
* turns without stretching. Limits stay in the model's own units.
|
||||
*
|
||||
* A spin turns its part `rate × timeS` degrees about its axis (any part with
|
||||
* an axis); a deploy fraction puts a hinge or deploy part that far between
|
||||
* its limits, and a slide or separable part as far along its axis. A spin,
|
||||
* deploy or pose naming a part the table does not have is ignored.
|
||||
*
|
||||
* Returns whether any part is not at rest (moved, hidden or highlighted):
|
||||
* false means every matrix written is the identity and every flag 0.
|
||||
* @param {import('./modelParts').PartTable} table
|
||||
* @param {import('./contract/draw').ModelPartState|null|undefined} state
|
||||
* @param {number} timeS
|
||||
* @param {Float32Array|Float64Array} out
|
||||
* @param {import('./modelParts').PartMatricesOptions} [options]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function partMatrices(table, state, timeS, out, options = {}) {
|
||||
const { offset = 0, flags, flagsOffset = 0, scale } = options;
|
||||
let scaled = false;
|
||||
if (scale !== undefined && scale !== null) {
|
||||
_s[0] = scale[0];
|
||||
_s[1] = scale[1];
|
||||
_s[2] = scale[2];
|
||||
// A scale that is not positive along an axis cannot be undone: parts
|
||||
// stay unscaled.
|
||||
scaled =
|
||||
(_s[0] !== 1 || _s[1] !== 1 || _s[2] !== 1) &&
|
||||
_s[0] > 0 &&
|
||||
_s[1] > 0 &&
|
||||
_s[2] > 0;
|
||||
}
|
||||
const parts = table.parts;
|
||||
const n = parts.length;
|
||||
if (_world.length < n * 12) {
|
||||
_world = new Float64Array(n * 12);
|
||||
_hidden = new Uint8Array(n);
|
||||
}
|
||||
const world = _world;
|
||||
const posed = state?.poses;
|
||||
const spin = state?.spin;
|
||||
const deploy = state?.deploy;
|
||||
if (posed == null && spin == null && deploy == null) {
|
||||
// Every part at rest.
|
||||
for (let k = 0; k < n; k++) out.set(IDENTITY, offset + k * 16);
|
||||
flags?.fill(0, flagsOffset, flagsOffset + n);
|
||||
return false;
|
||||
}
|
||||
let anyPosed = false;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const part = parts[k];
|
||||
const name = part.name;
|
||||
const pose = posed?.[name];
|
||||
const parentIndex = part.parentIndex;
|
||||
const hidden =
|
||||
pose?.hidden === true || (parentIndex >= 0 && _hidden[parentIndex] === 1);
|
||||
const highlight = asksHighlight(pose?.highlight);
|
||||
_hidden[k] = hidden ? 1 : 0;
|
||||
if (flags !== undefined)
|
||||
flags[flagsOffset + k] =
|
||||
(hidden ? PART_HIDDEN : 0) | (highlight ? PART_HIGHLIGHT : 0);
|
||||
if (hidden) {
|
||||
out.fill(0, offset + k * 16, offset + k * 16 + 16);
|
||||
anyPosed = true;
|
||||
continue;
|
||||
}
|
||||
anyPosed ||= highlight;
|
||||
// The local motion about the pivot, rotation `_q` and translation `_t`,
|
||||
// in the (stretched) model: deploy, spin, then pose. `axis` is the
|
||||
// part's axis there, `stretch` its length over the model's own.
|
||||
let axis = part.axis;
|
||||
let stretch = 1;
|
||||
if (axis !== null && scaled) {
|
||||
_a[0] = axis[0] * _s[0];
|
||||
_a[1] = axis[1] * _s[1];
|
||||
_a[2] = axis[2] * _s[2];
|
||||
stretch = Math.hypot(_a[0], _a[1], _a[2]);
|
||||
_a[0] /= stretch;
|
||||
_a[1] /= stretch;
|
||||
_a[2] /= stretch;
|
||||
axis = _a;
|
||||
}
|
||||
const rate = spin?.[name];
|
||||
const fraction = deploy?.[name];
|
||||
let moves = false;
|
||||
_q.fill(0);
|
||||
_q[3] = 1;
|
||||
_t.fill(0);
|
||||
if (
|
||||
axis !== null &&
|
||||
typeof rate === 'number' &&
|
||||
rate !== 0 &&
|
||||
Number.isFinite(rate * timeS)
|
||||
) {
|
||||
// Reduced in doubles first: a rate times an epoch clock is a large
|
||||
// number of degrees.
|
||||
axisAngle(_q, axis, (rate * timeS) % 360);
|
||||
moves = true;
|
||||
}
|
||||
if (
|
||||
axis !== null &&
|
||||
part.limits !== null &&
|
||||
typeof fraction === 'number' &&
|
||||
Number.isFinite(fraction)
|
||||
) {
|
||||
const by = deployedBy(part, fraction);
|
||||
if (by !== 0 && TURNS.has(part.kind)) {
|
||||
axisAngle(_p, axis, by);
|
||||
multiplyInto(_q, _p);
|
||||
moves = true;
|
||||
} else if (by !== 0 && MOVES.has(part.kind)) {
|
||||
_t[0] = axis[0] * by * stretch;
|
||||
_t[1] = axis[1] * by * stretch;
|
||||
_t[2] = axis[2] * by * stretch;
|
||||
moves = true;
|
||||
}
|
||||
}
|
||||
if (pose !== undefined && pose !== null && isPosed(pose)) {
|
||||
// Pose over the rest: R = Rpose · R, t = tpose + Rpose · t.
|
||||
poseInto(_r, _v, pose);
|
||||
if (scaled) for (let i = 0; i < 3; i++) _v[i] = _v[i] * _s[i];
|
||||
rotateInto(_r, _t);
|
||||
_t[0] = _t[0] + _v[0];
|
||||
_t[1] = _t[1] + _v[1];
|
||||
_t[2] = _t[2] + _v[2];
|
||||
multiplyInto(_r, _q);
|
||||
_q.set(_r);
|
||||
moves = true;
|
||||
}
|
||||
if (moves && part.limits !== null && axis !== null) {
|
||||
if (part.kind === 'hinge' || part.kind === 'deploy')
|
||||
clampTwist(_q, axis, part.rest, part.limits);
|
||||
else if (part.kind === 'slide') {
|
||||
// Along the axis in the model's own metres, which its limits are in.
|
||||
const along =
|
||||
(_t[0] * axis[0] + _t[1] * axis[1] + _t[2] * axis[2]) / stretch;
|
||||
const lo = Math.min(part.limits[0], part.limits[1]) - part.rest;
|
||||
const hi = Math.max(part.limits[0], part.limits[1]) - part.rest;
|
||||
const shift = (Math.min(hi, Math.max(lo, along)) - along) * stretch;
|
||||
_t[0] = _t[0] + axis[0] * shift;
|
||||
_t[1] = _t[1] + axis[1] * shift;
|
||||
_t[2] = _t[2] + axis[2] * shift;
|
||||
}
|
||||
}
|
||||
anyPosed ||= moves;
|
||||
const w = k * 12;
|
||||
if (moves) {
|
||||
// Local L = R and p + t − R p, about the pivot.
|
||||
let [px, py, pz] = part.pivot;
|
||||
if (scaled) {
|
||||
px *= _s[0];
|
||||
py *= _s[1];
|
||||
pz *= _s[2];
|
||||
}
|
||||
_v[0] = px;
|
||||
_v[1] = py;
|
||||
_v[2] = pz;
|
||||
rotateInto(_q, _v);
|
||||
_t[0] = _t[0] + px - _v[0];
|
||||
_t[1] = _t[1] + py - _v[1];
|
||||
_t[2] = _t[2] + pz - _v[2];
|
||||
}
|
||||
if (parentIndex < 0) affineInto(_q, _t, world, w);
|
||||
else if (!moves)
|
||||
world.copyWithin(w, parentIndex * 12, parentIndex * 12 + 12);
|
||||
else {
|
||||
// World = parent's world · local.
|
||||
affineInto(_q, _t, _local, 0);
|
||||
const b = parentIndex * 12;
|
||||
for (let row = 0; row < 3; row++) {
|
||||
const a0 = world[b + row * 3];
|
||||
const a1 = world[b + row * 3 + 1];
|
||||
const a2 = world[b + row * 3 + 2];
|
||||
world[w + row * 3] = a0 * _local[0] + a1 * _local[3] + a2 * _local[6];
|
||||
world[w + row * 3 + 1] =
|
||||
a0 * _local[1] + a1 * _local[4] + a2 * _local[7];
|
||||
world[w + row * 3 + 2] =
|
||||
a0 * _local[2] + a1 * _local[5] + a2 * _local[8];
|
||||
world[w + 9 + row] =
|
||||
a0 * _local[9] +
|
||||
a1 * _local[10] +
|
||||
a2 * _local[11] +
|
||||
world[b + 9 + row];
|
||||
}
|
||||
}
|
||||
if (!scaled) writeMatrix(world, w, out, offset + k * 16);
|
||||
else {
|
||||
// X = S⁻¹ · World · S.
|
||||
for (let row = 0; row < 3; row++) {
|
||||
for (let col = 0; col < 3; col++)
|
||||
_local[row * 3 + col] =
|
||||
(world[w + row * 3 + col] * _s[col]) / _s[row];
|
||||
_local[9 + row] = world[w + 9 + row] / _s[row];
|
||||
}
|
||||
writeMatrix(_local, 0, out, offset + k * 16);
|
||||
}
|
||||
}
|
||||
return anyPosed;
|
||||
}
|
||||
|
||||
/** Write the affine `m` (12 numbers from `at`: R row-major, then t) as a column-major 4×4 into `out` at `to`. */
|
||||
function writeMatrix(m, at, out, to) {
|
||||
for (let col = 0; col < 3; col++) {
|
||||
out[to + col * 4] = m[at + col];
|
||||
out[to + col * 4 + 1] = m[at + 3 + col];
|
||||
out[to + col * 4 + 2] = m[at + 6 + col];
|
||||
out[to + col * 4 + 3] = 0;
|
||||
}
|
||||
out[to + 12] = m[at + 9];
|
||||
out[to + 13] = m[at + 10];
|
||||
out[to + 14] = m[at + 11];
|
||||
out[to + 15] = 1;
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, test } from 'node:test';
|
||||
|
||||
import {
|
||||
gltfMeshMatrix,
|
||||
PART_HIDDEN,
|
||||
PART_HIGHLIGHT,
|
||||
partMatrices,
|
||||
partTableOf,
|
||||
readPartTable,
|
||||
asksHighlight,
|
||||
} from './modelParts.js';
|
||||
|
||||
/** `m` (column-major 4×4 at `at`) times the point `p`. */
|
||||
function apply(m, at, p) {
|
||||
const out = [0, 0, 0];
|
||||
for (let row = 0; row < 3; row++)
|
||||
out[row] =
|
||||
m[at + row] * p[0] +
|
||||
m[at + 4 + row] * p[1] +
|
||||
m[at + 8 + row] * p[2] +
|
||||
m[at + 12 + row];
|
||||
return out;
|
||||
}
|
||||
|
||||
function close(actual, expected, digits = 6) {
|
||||
assert.equal(actual.length, expected.length);
|
||||
const tolerance = 10 ** -digits / 2;
|
||||
actual.forEach((value, i) =>
|
||||
assert.ok(
|
||||
Math.abs(value - expected[i]) <= tolerance,
|
||||
`[${i}] ${value} is not ${expected[i]}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||
|
||||
/** A model in the glTF frame (nose −X, Y up, right −Z). */
|
||||
const TABLE = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
// Nose gear: stowed at 90, down at 0, turning about +Z through a point ahead and below.
|
||||
{
|
||||
name: 'gear_nose',
|
||||
kind: 'hinge',
|
||||
pivot: [-10, -1, 0],
|
||||
axis: [0, 0, 1],
|
||||
limits: [90, 0],
|
||||
},
|
||||
// A flap about the right axis (−Z), 0 to 40 degrees, drawn at 0.
|
||||
{
|
||||
name: 'flap',
|
||||
kind: 'hinge',
|
||||
pivot: [2, 0, -3],
|
||||
axis: [0, 0, -1],
|
||||
limits: [0, 40],
|
||||
},
|
||||
{ name: 'engine', kind: 'marker', pivot: [0, -2, -5] },
|
||||
{
|
||||
name: 'fan',
|
||||
kind: 'spin',
|
||||
parent: 'engine',
|
||||
pivot: [-2, -2, -5],
|
||||
axis: [1, 0, 0],
|
||||
},
|
||||
{
|
||||
name: 'stage_1',
|
||||
kind: 'separable',
|
||||
pivot: [0, 40, 0],
|
||||
axis: [0, -1, 0],
|
||||
limits: [0, 30],
|
||||
},
|
||||
{
|
||||
name: 'leg_1',
|
||||
kind: 'hinge',
|
||||
parent: 'stage_1',
|
||||
pivot: [1, 1, 0],
|
||||
axis: [0, 0, -1],
|
||||
limits: [0, 110],
|
||||
},
|
||||
{
|
||||
name: 'door',
|
||||
kind: 'slide',
|
||||
pivot: [0, 0, 1],
|
||||
axis: [2, 0, 0],
|
||||
limits: [0, 1.5],
|
||||
},
|
||||
{
|
||||
name: 'panel',
|
||||
kind: 'deploy',
|
||||
pivot: [0, 0, 4],
|
||||
axis: [1, 0, 0],
|
||||
limits: [90, 0],
|
||||
rest: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function matrices(state, timeS = 0) {
|
||||
const out = new Float64Array(TABLE.parts.length * 16);
|
||||
const flags = new Uint8Array(TABLE.parts.length);
|
||||
const posed = partMatrices(TABLE, state, timeS, out, { flags });
|
||||
const at = (name) => TABLE.byName.get(name) * 16;
|
||||
return { out, flags, posed, at };
|
||||
}
|
||||
|
||||
const slice = (out, at) => Array.from(out.subarray(at, at + 16));
|
||||
|
||||
describe('partTableOf', () => {
|
||||
test('reads a table with its defaults', () => {
|
||||
assert.deepEqual(
|
||||
TABLE.parts.map((p) => p.name),
|
||||
[
|
||||
'body',
|
||||
'gear_nose',
|
||||
'flap',
|
||||
'engine',
|
||||
'fan',
|
||||
'stage_1',
|
||||
'leg_1',
|
||||
'door',
|
||||
'panel',
|
||||
],
|
||||
);
|
||||
const body = TABLE.parts[0];
|
||||
assert.equal(body.kind, 'body');
|
||||
assert.equal(body.parent, null);
|
||||
assert.equal(body.parentIndex, -1);
|
||||
assert.deepEqual(body.pivot, [0, 0, 0]);
|
||||
assert.equal(body.axis, null);
|
||||
assert.equal(body.limits, null);
|
||||
assert.equal(body.rest, null);
|
||||
// `rest` is the stowed limit unless given; `parent` is the body unless given.
|
||||
assert.equal(TABLE.parts[1].parent, 'body');
|
||||
assert.equal(TABLE.parts[1].parentIndex, 0);
|
||||
assert.equal(TABLE.parts[1].rest, 90);
|
||||
assert.deepEqual(TABLE.parts[8].limits, [90, 0]);
|
||||
assert.equal(TABLE.parts[8].rest, 0);
|
||||
assert.equal(TABLE.parts[4].parent, 'engine');
|
||||
assert.equal(TABLE.parts[4].parentIndex, 3);
|
||||
assert.equal(TABLE.parts[4].rest, null);
|
||||
// The axis is made unit length.
|
||||
assert.deepEqual(TABLE.parts[7].axis, [1, 0, 0]);
|
||||
assert.equal(TABLE.byName.get('leg_1'), 6);
|
||||
});
|
||||
|
||||
test('a model without a table has none', () => {
|
||||
assert.equal(partTableOf(undefined), null);
|
||||
assert.equal(partTableOf({}), null);
|
||||
assert.equal(partTableOf({ other: 1 }), null);
|
||||
});
|
||||
|
||||
const body = { name: 'body', kind: 'body' };
|
||||
for (const [extras, message] of [
|
||||
[{ parts: [] }, /list of parts/],
|
||||
[{ parts: [{ name: 'hull', kind: 'marker' }] }, /body/],
|
||||
[{ parts: [body, { name: 'x', kind: 'wobble' }] }, /kind wobble/],
|
||||
[{ parts: [body, { name: 'body', kind: 'marker' }] }, /twice/],
|
||||
[
|
||||
{ parts: [body, { name: 'a', kind: 'marker', parent: 'b' }] },
|
||||
/not an earlier part/,
|
||||
],
|
||||
[{ parts: [body, { name: 'a', kind: 'spin', axis: [0, 0] }] }, /axis/],
|
||||
[
|
||||
{ parts: [body, { name: 'a', kind: 'spin', axis: [0, 0, 0] }] },
|
||||
/zero axis/,
|
||||
],
|
||||
[{ parts: [body, { name: 'a', kind: 'hinge', limits: [0] }] }, /limits/],
|
||||
])
|
||||
test(`refuses a malformed table (${message})`, () => {
|
||||
assert.throws(() => partTableOf(extras), message);
|
||||
});
|
||||
});
|
||||
|
||||
/** A GLB of `json` and no binary chunk. */
|
||||
function glb(json) {
|
||||
let text = new TextEncoder().encode(JSON.stringify(json));
|
||||
const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20);
|
||||
padded.set(text);
|
||||
text = padded;
|
||||
const out = new Uint8Array(20 + text.length);
|
||||
const view = new DataView(out.buffer);
|
||||
view.setUint32(0, 0x46546c67, true);
|
||||
view.setUint32(4, 2, true);
|
||||
view.setUint32(8, out.length, true);
|
||||
view.setUint32(12, text.length, true);
|
||||
view.setUint32(16, 0x4e4f534a, true);
|
||||
out.set(text, 20);
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('readPartTable', () => {
|
||||
test('reads the table of the scene’s root node', () => {
|
||||
const extras = {
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'radar', kind: 'spin' },
|
||||
],
|
||||
};
|
||||
const bytes = glb({
|
||||
scene: 0,
|
||||
scenes: [{ nodes: [1] }],
|
||||
nodes: [
|
||||
{ extras: { parts: [{ name: 'body', kind: 'body' }] } },
|
||||
{ mesh: 0, extras },
|
||||
],
|
||||
});
|
||||
assert.deepEqual(
|
||||
readPartTable(bytes).parts.map((p) => p.name),
|
||||
['body', 'radar'],
|
||||
);
|
||||
assert.equal(readPartTable(bytes.buffer).parts.length, 2);
|
||||
});
|
||||
|
||||
test('a model that is only its body has none', () => {
|
||||
assert.equal(
|
||||
readPartTable(glb({ scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }] })),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('refuses bytes that are not a GLB', () => {
|
||||
assert.throws(
|
||||
() => readPartTable(new TextEncoder().encode('glTF but not really')),
|
||||
/GLB/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gltfMeshMatrix', () => {
|
||||
test('the mesh node’s transform with its parents’', () => {
|
||||
const m = gltfMeshMatrix({
|
||||
scenes: [{ nodes: [0] }],
|
||||
nodes: [
|
||||
{ translation: [1, 2, 3], children: [1] },
|
||||
// A packed model's dequantization: a scale and an offset.
|
||||
{ mesh: 0, translation: [0, 2, 0], scale: [10, 10, 10] },
|
||||
],
|
||||
});
|
||||
close(apply(m, 0, [1, 0, 0]), [11, 4, 3]);
|
||||
close(apply(m, 0, [0, -1, 0]), [1, -6, 3]);
|
||||
});
|
||||
|
||||
test('turned by a node’s rotation', () => {
|
||||
// 90 degrees about +Y: +X turns to −Z.
|
||||
const s = Math.SQRT1_2;
|
||||
const m = gltfMeshMatrix({
|
||||
nodes: [{ mesh: 0, rotation: [0, s, 0, s] }],
|
||||
});
|
||||
close(apply(m, 0, [1, 0, 0]), [0, 0, -1]);
|
||||
});
|
||||
|
||||
test('the identity without a mesh', () => {
|
||||
assert.deepEqual(gltfMeshMatrix({ nodes: [{}] }), IDENTITY);
|
||||
});
|
||||
});
|
||||
|
||||
describe('partMatrices', () => {
|
||||
test('no state, or an empty one, leaves every part at rest', () => {
|
||||
for (const state of [null, {}, { poses: {}, spin: {}, deploy: {} }]) {
|
||||
const { out, flags, posed } = matrices(state);
|
||||
assert.equal(posed, false);
|
||||
for (let k = 0; k < TABLE.parts.length; k++)
|
||||
assert.deepEqual(slice(out, k * 16), IDENTITY);
|
||||
assert.deepEqual(
|
||||
Array.from(flags),
|
||||
new Array(TABLE.parts.length).fill(0),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a hinge turns about its pivot, off the origin', () => {
|
||||
// Deployed: from 90 (as drawn) to 0, so −90 degrees about +Z through [-10, -1, 0].
|
||||
const { out, at, posed } = matrices({ deploy: { gear_nose: 1 } });
|
||||
assert.equal(posed, true);
|
||||
close(apply(out, at('gear_nose'), [-10, -1, 0]), [-10, -1, 0]);
|
||||
// 2 m along −Y from the pivot turns to 2 m along −X.
|
||||
close(apply(out, at('gear_nose'), [-10, -3, 0]), [-12, -1, 0]);
|
||||
// Halfway is 45 degrees.
|
||||
const half = matrices({ deploy: { gear_nose: 0.5 } });
|
||||
const s = Math.SQRT1_2 * 2;
|
||||
close(apply(half.out, half.at('gear_nose'), [-10, -3, 0]), [
|
||||
-10 - s,
|
||||
-1 - s,
|
||||
0,
|
||||
]);
|
||||
// Other parts stay at rest.
|
||||
assert.deepEqual(slice(out, at('flap')), IDENTITY);
|
||||
});
|
||||
|
||||
test('a hinge’s pose is clamped to its limits, its swing left free', () => {
|
||||
// The flap's axis is the model's right, so pitch turns it: 0 to 40 degrees.
|
||||
const tip = [3, 0, -3];
|
||||
const turned = (deg) => [
|
||||
2 + Math.cos(deg * (Math.PI / 180)),
|
||||
// Nose up: what is behind the hinge goes down.
|
||||
-Math.sin(deg * (Math.PI / 180)),
|
||||
-3,
|
||||
];
|
||||
for (const [pitch, expected] of [
|
||||
[25, 25],
|
||||
[60, 40],
|
||||
[-10, 0],
|
||||
[400, 40],
|
||||
]) {
|
||||
const { out, at } = matrices({ poses: { flap: { pitchDeg: pitch } } });
|
||||
close(apply(out, at('flap'), tip), turned(expected));
|
||||
}
|
||||
// A roll is about the forward axis, not the hinge's: kept as posed.
|
||||
const rolled = matrices({ poses: { flap: { rollDeg: 90 } } });
|
||||
close(apply(rolled.out, rolled.at('flap'), [2, 1, -3]), [2, 0, -4]);
|
||||
});
|
||||
|
||||
test('the deploy fraction is clamped to 0..1, and a pose adds to it within limits', () => {
|
||||
const over = matrices({ deploy: { gear_nose: 3 } });
|
||||
const full = matrices({ deploy: { gear_nose: 1 } });
|
||||
close(Array.from(over.out), Array.from(full.out));
|
||||
// The gear down (0) and pitched 30 more (−30 about its +Z axis): still
|
||||
// 0, its limit; pitched the other way, it comes 30 back up.
|
||||
const past = matrices({
|
||||
deploy: { gear_nose: 1 },
|
||||
poses: { gear_nose: { pitchDeg: 30 } },
|
||||
});
|
||||
close(Array.from(past.out), Array.from(full.out));
|
||||
const back = matrices({
|
||||
deploy: { gear_nose: 1 },
|
||||
poses: { gear_nose: { pitchDeg: -30 } },
|
||||
});
|
||||
const thirty = matrices({ deploy: { gear_nose: 1 - 30 / 90 } });
|
||||
close(Array.from(back.out), Array.from(thirty.out));
|
||||
// A deploy part drawn deployed (rest 0) stows to 90 about +X.
|
||||
const stowed = matrices({ deploy: { panel: 0 } });
|
||||
close(apply(stowed.out, stowed.at('panel'), [0, 1, 4]), [0, 0, 5]);
|
||||
});
|
||||
|
||||
test('a child part rides its parent', () => {
|
||||
// The engine moved 1 m up: its fan, at rest about its own hub, moves with it.
|
||||
const { out, at } = matrices({ poses: { engine: { offsetM: [0, 0, 1] } } });
|
||||
close(apply(out, at('engine'), [0, -2, -5]), [0, -1, -5]);
|
||||
close(apply(out, at('fan'), [-2, -2, -5]), [-2, -1, -5]);
|
||||
// Spinning too: the hub stays on the moved axis, a blade tip turns about it.
|
||||
const spun = matrices(
|
||||
{ poses: { engine: { offsetM: [0, 0, 1] } }, spin: { fan: 90 } },
|
||||
1,
|
||||
);
|
||||
close(apply(spun.out, spun.at('fan'), [-2, -2, -5]), [-2, -1, -5]);
|
||||
// +90 about +X: +Y turns to +Z.
|
||||
close(apply(spun.out, spun.at('fan'), [-2, -1, -5]), [-2, -1, -4]);
|
||||
});
|
||||
|
||||
test('a child hinge turns about its pivot as carried by its parent', () => {
|
||||
const { out, at } = matrices({ deploy: { stage_1: 1, leg_1: 1 } });
|
||||
// The stage leaves 30 m along −Y; the leg's hinge goes with it and turns 110 about −Z there.
|
||||
close(apply(out, at('leg_1'), [1, 1, 0]), [1, -29, 0]);
|
||||
const deg = 110 * (Math.PI / 180);
|
||||
close(apply(out, at('leg_1'), [1, 2, 0]), [
|
||||
1 + Math.sin(deg),
|
||||
-29 + Math.cos(deg),
|
||||
0,
|
||||
]);
|
||||
});
|
||||
|
||||
test('a spin turns at its rate over time', () => {
|
||||
const tip = [-2, -1, -5];
|
||||
const at = (timeS) => {
|
||||
const m = matrices({ spin: { fan: 90 } }, timeS);
|
||||
return apply(m.out, m.at('fan'), tip);
|
||||
};
|
||||
close(at(0), tip);
|
||||
close(at(1), [-2, -2, -4]);
|
||||
close(at(2), [-2, -3, -5]);
|
||||
close(at(4), tip);
|
||||
// A rate times an epoch clock still lands where it should.
|
||||
close(at(1_700_000_000), tip, 4);
|
||||
close(at(1_700_000_001), [-2, -2, -4], 4);
|
||||
// A spin driving a part with no axis does nothing.
|
||||
assert.equal(matrices({ spin: { engine: 90 } }, 1).posed, false);
|
||||
});
|
||||
|
||||
test('a separable part moves freely: its limits bound only the deploy fraction', () => {
|
||||
const half = matrices({ deploy: { stage_1: 0.5 } });
|
||||
close(apply(half.out, half.at('stage_1'), [0, 40, 0]), [0, 25, 0]);
|
||||
// Posed 500 m right and turned, past any limit (right is −Z).
|
||||
const { out, at } = matrices({
|
||||
poses: { stage_1: { offsetM: [500, 0, -200], yawDeg: 30 } },
|
||||
});
|
||||
close(apply(out, at('stage_1'), [0, 40, 0]), [0, -160, -500]);
|
||||
});
|
||||
|
||||
test('a slide is clamped along its axis, free across it', () => {
|
||||
// The door slides along +X (the model's back) 0 to 1.5 m; offsetM is [right, forward, up].
|
||||
const back = (metres) =>
|
||||
matrices({ poses: { door: { offsetM: [0, -metres, 0] } } });
|
||||
close(apply(back(1).out, back(1).at('door'), [0, 0, 1]), [1, 0, 1]);
|
||||
close(apply(back(9).out, back(9).at('door'), [0, 0, 1]), [1.5, 0, 1]);
|
||||
close(apply(back(-2).out, back(-2).at('door'), [0, 0, 1]), [0, 0, 1]);
|
||||
const up = matrices({ poses: { door: { offsetM: [0, -9, 2] } } });
|
||||
close(apply(up.out, up.at('door'), [0, 0, 1]), [1.5, 2, 1]);
|
||||
});
|
||||
|
||||
test('hidden hides the part and every part riding it', () => {
|
||||
const { out, flags, at, posed } = matrices({
|
||||
poses: { engine: { hidden: true } },
|
||||
});
|
||||
assert.equal(posed, true);
|
||||
assert.deepEqual(slice(out, at('engine')), new Array(16).fill(0));
|
||||
assert.deepEqual(slice(out, at('fan')), new Array(16).fill(0));
|
||||
assert.equal(flags[TABLE.byName.get('engine')], PART_HIDDEN);
|
||||
assert.equal(flags[TABLE.byName.get('fan')], PART_HIDDEN);
|
||||
assert.equal(flags[TABLE.byName.get('flap')], 0);
|
||||
assert.deepEqual(slice(out, at('flap')), IDENTITY);
|
||||
});
|
||||
|
||||
test('highlight marks the part alone, and does not move it', () => {
|
||||
const { out, flags, posed } = matrices({
|
||||
poses: { engine: { highlight: '#ff0' } },
|
||||
});
|
||||
assert.equal(posed, true);
|
||||
assert.equal(flags[TABLE.byName.get('engine')], PART_HIGHLIGHT);
|
||||
assert.equal(flags[TABLE.byName.get('fan')], 0);
|
||||
for (let k = 0; k < TABLE.parts.length; k++)
|
||||
assert.deepEqual(slice(out, k * 16), IDENTITY);
|
||||
assert.equal(
|
||||
matrices({ poses: { engine: { highlight: false } } }).posed,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a highlight is true or a colour; anything else asks for none', () => {
|
||||
for (const value of [true, '#ff0', 'red', [1, 0.5, 0], [1, 0, 0, 0.5]])
|
||||
assert.equal(asksHighlight(value), true, String(value));
|
||||
for (const value of [
|
||||
false,
|
||||
'',
|
||||
' ',
|
||||
0,
|
||||
1,
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
[1, 0],
|
||||
[1, 'x', 0],
|
||||
[NaN, 0, 0],
|
||||
])
|
||||
assert.equal(asksHighlight(value), false, String(value));
|
||||
assert.equal(
|
||||
matrices({ poses: { engine: { highlight: '' } } }).posed,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
matrices({ poses: { engine: { highlight: 0 } } }).posed,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a pose value that is not finite counts as 0', () => {
|
||||
const { out, posed } = matrices({
|
||||
poses: {
|
||||
engine: {
|
||||
yawDeg: NaN,
|
||||
pitchDeg: Infinity,
|
||||
rollDeg: -Infinity,
|
||||
offsetM: [NaN, Infinity, undefined],
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.equal(posed, false);
|
||||
for (let k = 0; k < TABLE.parts.length; k++)
|
||||
assert.deepEqual(slice(out, k * 16), IDENTITY);
|
||||
// Beside a finite one, it is still 0 and no NaN is written.
|
||||
const mixed = matrices({
|
||||
poses: { engine: { yawDeg: 90, pitchDeg: NaN, offsetM: [NaN, 0, 1] } },
|
||||
});
|
||||
assert.equal(mixed.posed, true);
|
||||
assert.ok(mixed.out.every(Number.isFinite));
|
||||
});
|
||||
|
||||
test('names the table does not have are ignored', () => {
|
||||
const { posed } = matrices({
|
||||
poses: { rotor_main: { yawDeg: 30, hidden: true } },
|
||||
spin: { rotor_main: 100 },
|
||||
deploy: { gear_main: 1 },
|
||||
});
|
||||
assert.equal(posed, false);
|
||||
});
|
||||
|
||||
test('writes from an offset, into float32', () => {
|
||||
const out = new Float32Array(16 + TABLE.parts.length * 16).fill(7);
|
||||
const flags = new Uint8Array(3 + TABLE.parts.length).fill(9);
|
||||
partMatrices(TABLE, { poses: { flap: { hidden: true } } }, 0, out, {
|
||||
offset: 16,
|
||||
flags,
|
||||
flagsOffset: 3,
|
||||
});
|
||||
assert.deepEqual(Array.from(out.subarray(0, 16)), new Array(16).fill(7));
|
||||
assert.deepEqual(Array.from(out.subarray(16, 32)), IDENTITY);
|
||||
assert.deepEqual(Array.from(flags.subarray(0, 3)), [9, 9, 9]);
|
||||
assert.equal(flags[3 + TABLE.byName.get('flap')], PART_HIDDEN);
|
||||
});
|
||||
});
|
||||
|
||||
describe('partMatrices on a stretched model', () => {
|
||||
/** Where `p` is drawn by a model stretched `scale` whose part is `out`'s matrix at `at`: S · X · p. */
|
||||
const drawnAt = (out, at, scale, p) => {
|
||||
const x = apply(out, at, p);
|
||||
return [x[0] * scale[0], x[1] * scale[1], x[2] * scale[2]];
|
||||
};
|
||||
const RADAR = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'radar', kind: 'spin', pivot: [5, 3, 0], axis: [0, 1, 0] },
|
||||
],
|
||||
});
|
||||
const length = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
||||
|
||||
test('a radar on a hull drawn twice its length keeps its length at every angle', () => {
|
||||
const scale = [2, 1, 1];
|
||||
const hub = [5, 3, 0];
|
||||
const tip = [6, 3, 0];
|
||||
const state = { spin: { radar: 30 } };
|
||||
for (let timeS = 0; timeS < 12; timeS++) {
|
||||
const out = new Float64Array(32);
|
||||
partMatrices(RADAR, state, timeS, out, { scale });
|
||||
const h = drawnAt(out, 16, scale, hub);
|
||||
const t = drawnAt(out, 16, scale, tip);
|
||||
// The hub stays where the stretched hull draws it; the 1 m arm is drawn 2 m long.
|
||||
close(h, [10, 3, 0]);
|
||||
assert.ok(Math.abs(length(t, h) - 2) < 1e-9);
|
||||
}
|
||||
// Unscaled matrices under the same stretch distort it: 1 m long across the hull.
|
||||
const naive = new Float64Array(32);
|
||||
partMatrices(RADAR, state, 3, naive);
|
||||
const h = drawnAt(naive, 16, scale, hub);
|
||||
const t = drawnAt(naive, 16, scale, tip);
|
||||
assert.ok(Math.abs(length(t, h) - 1) < 1e-9);
|
||||
});
|
||||
|
||||
test('a hinge turns rigidly about its stretched pivot', () => {
|
||||
const scale = [1, 3, 1];
|
||||
const out = new Float64Array(TABLE.parts.length * 16);
|
||||
partMatrices(TABLE, { deploy: { gear_nose: 1 } }, 0, out, { scale });
|
||||
const at = TABLE.byName.get('gear_nose') * 16;
|
||||
close(drawnAt(out, at, scale, [-10, -1, 0]), [-10, -3, 0]);
|
||||
close(drawnAt(out, at, scale, [-10, -3, 0]), [-16, -3, 0]);
|
||||
});
|
||||
|
||||
test('a slide keeps its limits in the model’s own metres', () => {
|
||||
const scale = [2, 1, 1];
|
||||
const out = new Float64Array(TABLE.parts.length * 16);
|
||||
// Offsets are stretched with the model: 9 m back asked, 1.5 m allowed, drawn 3 m.
|
||||
partMatrices(TABLE, { poses: { door: { offsetM: [0, -9, 0] } } }, 0, out, {
|
||||
scale,
|
||||
});
|
||||
close(
|
||||
drawnAt(out, TABLE.byName.get('door') * 16, scale, [0, 0, 1]),
|
||||
[3, 0, 1],
|
||||
);
|
||||
});
|
||||
|
||||
test('a scale of one, or none, writes the same matrices', () => {
|
||||
const state = {
|
||||
deploy: { gear_nose: 0.3, stage_1: 1, leg_1: 0.5 },
|
||||
spin: { fan: 33 },
|
||||
poses: { engine: { offsetM: [1, 2, 3], yawDeg: 10 } },
|
||||
};
|
||||
const a = new Float64Array(TABLE.parts.length * 16);
|
||||
const b = new Float64Array(TABLE.parts.length * 16);
|
||||
partMatrices(TABLE, state, 1.5, a);
|
||||
partMatrices(TABLE, state, 1.5, b, { scale: [1, 1, 1] });
|
||||
assert.deepEqual(Array.from(b), Array.from(a));
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,7 @@ const NEUTRAL = [
|
||||
'./render/vectorBase',
|
||||
'./render/iconSegment',
|
||||
'./render/recession',
|
||||
'./render/modelParts',
|
||||
'./render/windStreamlines',
|
||||
'./render/weather',
|
||||
'./weather/effects',
|
||||
|
||||
+118
-24
@@ -1,10 +1,33 @@
|
||||
import { readSnapshotTimeline } from '../sources/live/contract.js';
|
||||
import { TIMELINE_HELD_MS } from './timelineFixes.js';
|
||||
import { fixesReachMs, TIMELINE_HELD_MS } from './timelineFixes.js';
|
||||
|
||||
/** The longest play waits on a snapshot before it goes on without it. */
|
||||
export const SNAPSHOT_WAIT_MS = 8_000;
|
||||
/** How long a snapshot that failed to load waits before it is asked again. */
|
||||
export const SNAPSHOT_RETRY_MS = 5_000;
|
||||
/**
|
||||
* How much play keeps of the loaded fixes after the newest snapshot: it holds
|
||||
* this far short of their end (at most half of them), so a contact never
|
||||
* reaches the end of its fixes while the next snapshot loads.
|
||||
*/
|
||||
export const SNAPSHOT_HOLD_MARGIN_MS = 60_000;
|
||||
/**
|
||||
* How far ahead, in real time at the clock's rate, play asks for snapshots:
|
||||
* at a high rate it asks several steps before the time needs them.
|
||||
*/
|
||||
export const SNAPSHOT_PREFETCH_MS = 4_000;
|
||||
|
||||
/**
|
||||
* What a layer's `load` answers once it applied `snapshot`: `{ reachMs }`,
|
||||
* how far its records' fixes reach (fixesReachMs), when they carry fixes;
|
||||
* else true.
|
||||
* @param {{records?: Array<{fixes?: unknown}>}} snapshot
|
||||
* @returns {true|{reachMs: number}}
|
||||
*/
|
||||
export function snapshotAnswer(snapshot) {
|
||||
const reachMs = fixesReachMs(snapshot?.records);
|
||||
return reachMs === null ? true : { reachMs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Let a layer of live contacts (flights, military aircraft, vessels) follow
|
||||
@@ -26,7 +49,10 @@ export const SNAPSHOT_RETRY_MS = 5_000;
|
||||
* are applied as polls are (`replace: false`), so contacts move on smoothly.
|
||||
* - When the source's timeline declares `spanMs`, its records carry their
|
||||
* fixes from `spanMs` before a snapshot's time to `spanMs` after it, and
|
||||
* the layer places each contact on them by the clock. A seek or a move
|
||||
* the layer places each contact on them by the clock. Playing on, it asks
|
||||
* for the next step SNAPSHOT_PREFETCH_MS of play ahead (at least a step),
|
||||
* and play holds only SNAPSHOT_HOLD_MARGIN_MS short of the end of the
|
||||
* newest snapshot's fixes, not at the step still loading. A seek or a move
|
||||
* back that stays within the fixes the loaded snapshots carry is then no
|
||||
* jump: nothing is cleared, play does not wait, and contacts move to the
|
||||
* time smoothly. A move to a step before the newest loaded asks for that
|
||||
@@ -36,17 +62,23 @@ export const SNAPSHOT_RETRY_MS = 5_000;
|
||||
* fixes after the newest asks for the snapshot there (`replace: false`).
|
||||
* - Outside the source's coverage the layer is `clear()`ed and nothing loads;
|
||||
* while the coverage is not known yet nothing loads and nothing is cleared.
|
||||
* - Back at live, the layer is `clear()`ed and `resumeLive()` polls at once.
|
||||
* - Back at live, `resumeLive()` polls at once and its snapshot takes the
|
||||
* place of every contact: those it has move on from where they are drawn,
|
||||
* and only those it lacks go. The contacts stay until it answers; when it
|
||||
* answers anything but true (it could not be had), the layer is `clear()`ed.
|
||||
* A rejection named AbortError (a newer poll took its place) clears nothing.
|
||||
*
|
||||
* `load` resolves true once the snapshot is applied and false (or rejects)
|
||||
* when it could not be; it must not apply anything once `signal` aborts. A
|
||||
* `load` resolves true once the snapshot is applied, or `{ reachMs }` when its
|
||||
* records carry fixes, the newest of them (`fixesReachMs`), and false (or
|
||||
* rejects) when it could not be; it must not apply anything once `signal` aborts. A
|
||||
* rejection named AbortError is a request the source dropped for a newer
|
||||
* one: it is not a failure, and nothing is cleared.
|
||||
*
|
||||
* @param {{id: string, clock: ReturnType<typeof import('./worldClock.js').createWorldClock>,
|
||||
* source: () => object|null,
|
||||
* load: (atMs: number, options: {signal: AbortSignal, replace: boolean}) => Promise<boolean>,
|
||||
* clear: () => void, resumeLive: () => void,
|
||||
* load: (atMs: number, options: {signal: AbortSignal, replace: boolean}) =>
|
||||
* Promise<boolean|{reachMs: number}>,
|
||||
* clear: () => void, resumeLive: () => boolean|Promise<boolean>,
|
||||
* now?: () => number, setTimeout?: typeof globalThis.setTimeout,
|
||||
* clearTimeout?: typeof globalThis.clearTimeout}} options `source`
|
||||
* returns the layer's current source; it is read when the layer starts.
|
||||
@@ -86,6 +118,10 @@ export function createSnapshotTimeline({
|
||||
let gated;
|
||||
let failedUntil = -Infinity;
|
||||
let retryTimer = null;
|
||||
// Each return to live; an answer to an older one is dropped.
|
||||
let handovers = 0;
|
||||
// How far the fixes of each snapshot applied since the last jump reach.
|
||||
const reaches = new Map();
|
||||
|
||||
const span = () => {
|
||||
let covered;
|
||||
@@ -194,7 +230,7 @@ export function createSnapshotTimeline({
|
||||
return;
|
||||
}
|
||||
inflight = null;
|
||||
held(atMs, replace);
|
||||
held(atMs, replace, applied?.reachMs);
|
||||
empty = false;
|
||||
capped = false;
|
||||
stopWaiting();
|
||||
@@ -218,24 +254,27 @@ export function createSnapshotTimeline({
|
||||
// afresh: the contacts have no fixes for the time between. The stretch is
|
||||
// kept to TIMELINE_HELD_MS, from the end just loaded, which every
|
||||
// contact's fixes still cover.
|
||||
function held(atMs, replace) {
|
||||
function held(atMs, replace, reachMs) {
|
||||
const reach = 2 * (timeline.spanMs || 0);
|
||||
scrubbed = null;
|
||||
if (
|
||||
replace ||
|
||||
lead === null ||
|
||||
atMs > lead + reach ||
|
||||
atMs < base - reach
|
||||
) {
|
||||
const afresh =
|
||||
replace || lead === null || atMs > lead + reach || atMs < base - reach;
|
||||
if (afresh) reaches.clear();
|
||||
if (Number.isFinite(reachMs)) reaches.set(atMs, reachMs);
|
||||
else reaches.delete(atMs);
|
||||
if (afresh) {
|
||||
lead = atMs;
|
||||
base = atMs;
|
||||
return;
|
||||
}
|
||||
lead = Math.max(lead, atMs);
|
||||
base = Math.min(base, atMs);
|
||||
if (lead - base <= TIMELINE_HELD_MS) return;
|
||||
if (atMs === lead) base = lead - TIMELINE_HELD_MS;
|
||||
else lead = base + TIMELINE_HELD_MS;
|
||||
if (lead - base > TIMELINE_HELD_MS) {
|
||||
if (atMs === lead) base = lead - TIMELINE_HELD_MS;
|
||||
else lead = base + TIMELINE_HELD_MS;
|
||||
}
|
||||
for (const at of reaches.keys())
|
||||
if (at < base || at > lead) reaches.delete(at);
|
||||
}
|
||||
|
||||
// Ask again for what the time needs, after a failure or a dropped load:
|
||||
@@ -316,8 +355,12 @@ export function createSnapshotTimeline({
|
||||
clearOnce();
|
||||
return;
|
||||
}
|
||||
const hold = lead === null ? null : holdAt(covered);
|
||||
if (inflight) {
|
||||
if (playsOn(state) && timeMs >= inflight.atMs && !inflight.quiet)
|
||||
// With fixes past the newest snapshot, play waits only at their end.
|
||||
const waitsAt =
|
||||
timeline.spanMs > 0 && hold !== null ? hold : inflight.atMs;
|
||||
if (playsOn(state) && timeMs >= waitsAt && !inflight.quiet)
|
||||
startWaiting();
|
||||
return;
|
||||
}
|
||||
@@ -331,8 +374,8 @@ export function createSnapshotTimeline({
|
||||
return;
|
||||
}
|
||||
const step = timeline.stepMs;
|
||||
if (lead - timeMs >= step) {
|
||||
setGate(lead);
|
||||
if (lead - timeMs >= prefetchMs(state)) {
|
||||
setGate(hold);
|
||||
return;
|
||||
}
|
||||
const next = Math.min(
|
||||
@@ -343,13 +386,62 @@ export function createSnapshotTimeline({
|
||||
setGate(null);
|
||||
return;
|
||||
}
|
||||
setGate(capped ? null : next);
|
||||
setGate(capped ? null : timeline.spanMs > 0 ? hold : next);
|
||||
// Past what the loaded fixes reach (play went on without waiting), the
|
||||
// contacts have no fixes for the time between: the step stands in for
|
||||
// them all.
|
||||
request(next, timeline.spanMs > 0 && next > lead + 2 * timeline.spanMs);
|
||||
}
|
||||
|
||||
// Where play holds while the next snapshot loads: the newest loaded,
|
||||
// or, with fixes past it, SNAPSHOT_HOLD_MARGIN_MS short of where they
|
||||
// end: as far as that snapshot's fixes reach, at most the declared span
|
||||
// (never past the coverage).
|
||||
function holdAt(covered) {
|
||||
const reach = timeline.spanMs || 0;
|
||||
if (reach <= 0) return lead;
|
||||
const margin = Math.min(SNAPSHOT_HOLD_MARGIN_MS, reach / 2);
|
||||
const carried = reaches.get(lead);
|
||||
const end = Number.isFinite(carried)
|
||||
? Math.min(lead + reach, carried)
|
||||
: lead + reach;
|
||||
return Math.max(lead, Math.min(covered.end, end - margin));
|
||||
}
|
||||
|
||||
// How far ahead of the time play asks for the next step: a step, or with
|
||||
// fixes past each snapshot, SNAPSHOT_PREFETCH_MS of play at the clock's
|
||||
// rate, up to where play holds.
|
||||
function prefetchMs(state) {
|
||||
const step = timeline.stepMs;
|
||||
const reach = timeline.spanMs || 0;
|
||||
if (reach <= 0) return step;
|
||||
const rate = Number.isFinite(state.rate) ? Math.abs(state.rate) : 1;
|
||||
const margin = Math.min(SNAPSHOT_HOLD_MARGIN_MS, reach / 2);
|
||||
return Math.max(
|
||||
step,
|
||||
Math.min(reach - margin, rate * SNAPSHOT_PREFETCH_MS),
|
||||
);
|
||||
}
|
||||
|
||||
// Back at live: the first live snapshot takes the place of every contact,
|
||||
// which stay drawn until it does; one that cannot be had clears them.
|
||||
function handOver() {
|
||||
const mine = ++handovers;
|
||||
const current = () => mine === handovers && started && clock.isLive();
|
||||
Promise.resolve()
|
||||
.then(() => resumeLive())
|
||||
.then(
|
||||
(applied) => {
|
||||
if (current() && applied !== true) clear();
|
||||
},
|
||||
(error) => {
|
||||
if (!current() || error?.name === 'AbortError') return;
|
||||
console.warn(`Live snapshot failed: ${id}`, error);
|
||||
clear();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function follow(state) {
|
||||
if (!started) return;
|
||||
if (state.live) {
|
||||
@@ -363,10 +455,11 @@ export function createSnapshotTimeline({
|
||||
base = null;
|
||||
empty = false;
|
||||
failedUntil = -Infinity;
|
||||
clear();
|
||||
resumeLive();
|
||||
handOver();
|
||||
return;
|
||||
}
|
||||
// Away from live, a return to it still answering no longer applies.
|
||||
handovers += 1;
|
||||
const timeMs = state.timeMs;
|
||||
// Away from live already: a move may stay within the loaded fixes.
|
||||
const wasFollowing = wasActive;
|
||||
@@ -432,6 +525,7 @@ export function createSnapshotTimeline({
|
||||
stop() {
|
||||
if (!started) return;
|
||||
started = false;
|
||||
handovers += 1;
|
||||
cancel();
|
||||
setGate(null);
|
||||
wasActive = false;
|
||||
|
||||
@@ -3,14 +3,23 @@ import assert from 'node:assert/strict';
|
||||
import { createWorldClock } from './worldClock.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
SNAPSHOT_HOLD_MARGIN_MS,
|
||||
SNAPSHOT_PREFETCH_MS,
|
||||
SNAPSHOT_RETRY_MS,
|
||||
SNAPSHOT_WAIT_MS,
|
||||
snapshotAnswer,
|
||||
} from './snapshotTimeline.js';
|
||||
|
||||
const STEP = 10_000;
|
||||
const WALL = Date.UTC(2026, 10, 1, 12);
|
||||
|
||||
function harness({ timeline = true, coverage, spanMs } = {}) {
|
||||
function harness({
|
||||
timeline = true,
|
||||
coverage,
|
||||
spanMs,
|
||||
stepMs = STEP,
|
||||
live = () => true,
|
||||
} = {}) {
|
||||
const t = {
|
||||
wall: WALL,
|
||||
mono: 1_000,
|
||||
@@ -33,7 +42,7 @@ function harness({ timeline = true, coverage, spanMs } = {}) {
|
||||
...(timeline && {
|
||||
timeline: {
|
||||
coverage: () => span,
|
||||
stepMs: STEP,
|
||||
stepMs,
|
||||
...(spanMs && { spanMs }),
|
||||
subscribe(listener) {
|
||||
coverageListeners.add(listener);
|
||||
@@ -62,7 +71,10 @@ function harness({ timeline = true, coverage, spanMs } = {}) {
|
||||
pending.push({ atMs, replace, signal, resolve, reject });
|
||||
}),
|
||||
clear: () => calls.push({ type: 'clear' }),
|
||||
resumeLive: () => calls.push({ type: 'live' }),
|
||||
resumeLive: () => {
|
||||
calls.push({ type: 'live' });
|
||||
return live();
|
||||
},
|
||||
now: () => t.mono,
|
||||
...timers,
|
||||
});
|
||||
@@ -248,7 +260,7 @@ test('outside coverage the layer is cleared and nothing loads; unknown coverage
|
||||
assert.equal(h.coverageListeners.size, 0);
|
||||
});
|
||||
|
||||
test('back at live the layer is cleared and polls at once', async () => {
|
||||
test('back at live the layer polls at once and keeps its contacts for the live snapshot', async () => {
|
||||
const h = harness();
|
||||
h.follower.start();
|
||||
h.clock.seek(WALL - 600_000);
|
||||
@@ -257,11 +269,72 @@ test('back at live the layer is cleared and polls at once', async () => {
|
||||
h.clock.goLive();
|
||||
await flush();
|
||||
assert.equal(inflight.signal.aborted, true);
|
||||
assert.deepEqual(h.calls.slice(-2), [{ type: 'clear' }, { type: 'live' }]);
|
||||
assert.deepEqual(h.calls.at(-1), { type: 'live' });
|
||||
assert.equal(
|
||||
h.calls.some((call) => call.type === 'clear'),
|
||||
false,
|
||||
'the live snapshot takes the place of the contacts; nothing is cleared',
|
||||
);
|
||||
assert.equal(h.follower.active(), false);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('back at live, a live snapshot that cannot be had clears the layer', async () => {
|
||||
for (const answer of [
|
||||
() => false,
|
||||
() => Promise.resolve(false),
|
||||
() => Promise.reject(new Error('down')),
|
||||
]) {
|
||||
const h = harness({ live: answer });
|
||||
h.follower.start();
|
||||
h.clock.seek(WALL - 600_000);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.goLive();
|
||||
await flush();
|
||||
assert.deepEqual(h.calls.slice(-2), [{ type: 'live' }, { type: 'clear' }]);
|
||||
h.follower.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live, a live poll dropped for a newer one, or answered after leaving live, clears nothing', async () => {
|
||||
const dropped = harness({
|
||||
live: () =>
|
||||
Promise.reject(
|
||||
Object.assign(new Error('dropped'), { name: 'AbortError' }),
|
||||
),
|
||||
});
|
||||
dropped.follower.start();
|
||||
dropped.clock.seek(WALL - 600_000);
|
||||
await flush();
|
||||
await dropped.answer();
|
||||
dropped.clock.goLive();
|
||||
await flush();
|
||||
assert.deepEqual(dropped.calls.at(-1), { type: 'live' });
|
||||
dropped.follower.stop();
|
||||
|
||||
let fail;
|
||||
const late = harness({
|
||||
live: () => new Promise((resolve) => (fail = () => resolve(false))),
|
||||
});
|
||||
late.follower.start();
|
||||
late.clock.seek(WALL - 600_000);
|
||||
await flush();
|
||||
await late.answer();
|
||||
late.clock.goLive();
|
||||
await flush();
|
||||
late.clock.seek(WALL - 1_200_000);
|
||||
await flush();
|
||||
fail();
|
||||
await flush();
|
||||
assert.equal(
|
||||
late.calls.some((call) => call.type === 'clear'),
|
||||
false,
|
||||
'the time shown now is not cleared by the old live answer',
|
||||
);
|
||||
late.follower.stop();
|
||||
});
|
||||
|
||||
test('a load the source drops for a newer one is no failure: nothing clears, it is asked again', async () => {
|
||||
const h = harness();
|
||||
h.follower.start();
|
||||
@@ -450,8 +523,9 @@ test('a snapshot the loaded fixes do not reach starts the held stretch afresh',
|
||||
h.advance(100);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
// The next step is slow: play goes on without it, far past the fixes.
|
||||
h.advance(2 * STEP);
|
||||
// The next step is slow: play holds near the end of the fixes, then goes
|
||||
// on without it, far past them.
|
||||
h.advance(SPAN);
|
||||
h.clock.coverageChanged();
|
||||
h.advance(SNAPSHOT_WAIT_MS);
|
||||
h.advance(30 * STEP);
|
||||
@@ -548,3 +622,119 @@ test('a step a move back asked for that fails clears nothing and is asked again
|
||||
});
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('with fixes past each snapshot, play holds near their end, not at the step still loading', async () => {
|
||||
const SPAN = 600_000;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 1_800_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.play();
|
||||
h.advance(100);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
assert.deepEqual(loads(h.calls).at(-1), {
|
||||
type: 'load',
|
||||
atMs: at + STEP,
|
||||
replace: false,
|
||||
});
|
||||
// Past the step still loading: the newest snapshot's fixes carry them.
|
||||
h.advance(3 * STEP);
|
||||
h.clock.coverageChanged();
|
||||
assert.ok(h.clock.now() > at + 3 * STEP);
|
||||
assert.equal(h.clock.getState().buffering, false);
|
||||
// Play holds a margin short of the end of those fixes, and waits there.
|
||||
h.advance(SPAN);
|
||||
assert.equal(h.clock.now(), at + SPAN - SNAPSHOT_HOLD_MARGIN_MS);
|
||||
h.clock.coverageChanged();
|
||||
assert.equal(h.clock.getState().buffering, true);
|
||||
await h.answer();
|
||||
assert.equal(h.clock.getState().buffering, false);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('with fixes past each snapshot, a fast play asks for steps well ahead of the time', async () => {
|
||||
const SPAN = 600_000;
|
||||
const RATE = 60;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 1_800_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.setRate(RATE);
|
||||
h.clock.play();
|
||||
h.advance(100);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
// Each step answered asks for the next until they reach far enough ahead.
|
||||
while (h.pending.length) await h.answer();
|
||||
const ahead = RATE * SNAPSHOT_PREFETCH_MS;
|
||||
const newest = loads(h.calls).at(-1).atMs;
|
||||
const time = h.clock.now();
|
||||
assert.ok(newest - time >= ahead, 'steps asked for ahead of the time');
|
||||
assert.ok(newest - time < ahead + STEP, 'and no further');
|
||||
assert.ok(
|
||||
loads(h.calls).every((call, k) => k === 0 || call.replace === false),
|
||||
'each in step with the last, moving contacts on',
|
||||
);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('without fixes past each snapshot, a fast play still asks a step at a time', async () => {
|
||||
const h = harness();
|
||||
h.follower.start();
|
||||
const at = WALL - 1_800_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
await h.answer();
|
||||
h.clock.setRate(60);
|
||||
h.clock.play();
|
||||
h.advance(10);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
assert.equal(loads(h.calls).at(-1).atMs, at + STEP);
|
||||
await h.answer();
|
||||
assert.equal(h.pending.length, 1);
|
||||
assert.equal(loads(h.calls).at(-1).atMs, at + 2 * STEP);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('play holds short of where the applied snapshot’s fixes actually reach, when that is short of the span', async () => {
|
||||
const SPAN = 600_000;
|
||||
const h = harness({ spanMs: SPAN });
|
||||
h.follower.start();
|
||||
const at = WALL - 1_800_000;
|
||||
h.clock.seek(at);
|
||||
await flush();
|
||||
// Its records' fixes end two minutes after its time, not ten.
|
||||
await h.answer(0, { reachMs: at + 120_000 });
|
||||
h.clock.play();
|
||||
h.advance(100);
|
||||
h.clock.coverageChanged();
|
||||
await flush();
|
||||
h.advance(SPAN);
|
||||
assert.equal(h.clock.now(), at + 120_000 - SNAPSHOT_HOLD_MARGIN_MS);
|
||||
h.follower.stop();
|
||||
});
|
||||
|
||||
test('a layer answers how far an applied snapshot’s fixes reach', () => {
|
||||
assert.equal(snapshotAnswer({ records: [{ id: 'a' }] }), true);
|
||||
assert.deepEqual(
|
||||
snapshotAnswer({
|
||||
records: [
|
||||
{ fixes: [{ atMs: 3 }, { atMs: 9 }] },
|
||||
{ fixes: [{ atMs: 12 }, { atMs: 'x' }] },
|
||||
{ id: 'b' },
|
||||
],
|
||||
}),
|
||||
{ reachMs: 12 },
|
||||
);
|
||||
// One record reaching far ahead does not stand for the rest.
|
||||
const records = Array.from({ length: 20 }, (_, k) => ({
|
||||
fixes: [{ atMs: k === 0 ? 900 : 100 + k }],
|
||||
}));
|
||||
assert.deepEqual(snapshotAnswer({ records }), { reachMs: 118 });
|
||||
});
|
||||
@@ -59,6 +59,33 @@ export function readTimelineFixes(value) {
|
||||
return fixes;
|
||||
}
|
||||
|
||||
/** The share of records whose fixes reach no further than fixesReachMs. */
|
||||
export const FIXES_REACH_SHARE = 0.9;
|
||||
|
||||
/**
|
||||
* How far the fixes a snapshot's records carry reach: the time by which
|
||||
* FIXES_REACH_SHARE of them have their newest fix, so a few reaching far
|
||||
* ahead do not stand for the rest (those whose fixes end sooner left), or
|
||||
* null when none carries fixes.
|
||||
* @param {Array<{fixes?: unknown}>|undefined} records
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function fixesReachMs(records) {
|
||||
const reaches = [];
|
||||
for (const record of records ?? []) {
|
||||
if (!Array.isArray(record?.fixes)) continue;
|
||||
let reach = -Infinity;
|
||||
for (const fix of record.fixes) {
|
||||
const atMs = Number(fix?.atMs);
|
||||
if (Number.isFinite(atMs) && atMs > reach) reach = atMs;
|
||||
}
|
||||
if (reach > -Infinity) reaches.push(reach);
|
||||
}
|
||||
if (!reaches.length) return null;
|
||||
reaches.sort((a, b) => a - b);
|
||||
return reaches[Math.ceil(FIXES_REACH_SHARE * reaches.length) - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Two runs of entries in time order (`timeOf` reads an entry's epoch ms) as
|
||||
* one: `newer` stands in for the entries of `older` within the time it
|
||||
|
||||
Reference in new issue
Block a user