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
|
||||
|
||||
Reference in new issue
Block a user