Stop Navara's memory growth on engine switches, hide polygon zones reliably, and drop the Cesium camera rig

- Navara 0.2.1 never frees pick batch ids, and the mover banks rebuilt
  their instanced meshes on each attach, leaking about 260 KiB of
  WebAssembly memory per switch. A per-view pool hands released ids back
  out; the long soak now asserts native growth of at most 32 KiB per switch.
- Navara 0.2.1 sometimes drops the first show:false update on a new
  vector layer, so a zone turned off right after a switch back stayed
  drawn. Polygon displays hide by deleting their layers and rebuild them
  when shown.
- Camera verbs drive both engines through the globe contract; the Cesium
  viewer rig and the tests of states it can no longer reach are gone.
- Flights and military tracking share src/layers/aircraft/tracking.js.
- The geo import scenario reads movers only where the engine has them.
- Add the Navara section to docs/CURRENT-STATE.md and a changelog fragment.
This commit is contained in:
German Khokhlov committed 2026-11-05 21:18:23 +04:00
1 parent 7abf74518f
commit a6c64713ee
46 files changed
+2367 -2894

No files matched your search

+1 -2
View File
@@ -34,10 +34,9 @@ function stationFeature(reading, radius) {
/** One native GeoJSON layer per AQHI colour, independent of station count. */
export function createAirQualityNavaraRenderer(engine, { view }) {
const display = createNavaraPolygonDisplay(engine, view, (color, show) => ({
const display = createNavaraPolygonDisplay(engine, view, (color) => ({
polygon: {
color,
show,
transparent: true,
opacity: 0.35,
clampToGround: true,
+2 -3
View File
@@ -31,7 +31,7 @@ function observedShell(t) {
}
// What the tracking modules do around follow.start on a resume or a share
// restore (flights, military and satellites tracking.js).
// restore (the shared aircraft tracking.js and satellites tracking.js).
function follow(trackedEntityChanged, entity, restoring) {
if (restoring) entity.gevRestoring = true;
try {
@@ -150,8 +150,7 @@ test('an engine switch resumes the aircraft with the origin it was selected by',
test('every follow of a resumed or share-restored subject is marked while it starts', () => {
for (const [file, resume] of [
['flights/tracking.js', 'resume'],
['military/tracking.js', 'resume'],
['aircraft/tracking.js', 'resume'],
['satellites/tracking.js', 'resuming'],
]) {
const source = readLayerSource(new URL(`../${file}`, import.meta.url));
File diff suppressed because it is too large. Load diff
+157
View File
@@ -0,0 +1,157 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../../geo/index.js';
import { createTracking as createFlightsTracking } from '../flights/tracking.js';
import { createTracking as createMilitaryTracking } from '../military/tracking.js';
// Both observed aircraft layers build their tracking from the shared aircraft
// tracking; each must still reach it with its own identity and rules.
const LAYERS = [
{
name: 'flights',
createTracking: createFlightsTracking,
layerId: 'flights',
layerName: 'Live Flights',
focusId: 'flights',
floorsTrail: false,
backfillLeadAltM: 10000,
thinsBackfill: false,
},
{
name: 'military',
createTracking: createMilitaryTracking,
layerId: 'military',
layerName: 'Military Flights',
focusId: 'militaryFlights',
floorsTrail: true,
backfillLeadAltM: 50,
thinsBackfill: true,
},
];
const GROUND_M = 300;
function harness(layer, { groundM = null, track = [] } = {}) {
const calls = { registered: [], focusCleared: [] };
const flightState = {
enabled: true,
feed: {
_lastSource: 'Fixture aircraft',
_source: { getTrack: async () => ({ records: track }) },
},
records: { data: new Map(), missingPolls: new Map() },
lifetime: new AbortController(),
_billboards: new Map(),
_trackedIcao: null,
_trailPositions: [],
_trailBackfillToken: 0,
_renderer: {
engine: {},
follow: { onChanged: () => () => {} },
},
};
const services = {
context: {},
aircraftPresentation: { tr3bTypeLabel: (id, type) => type },
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: () => groundM,
// The production floor rule: lift onto a known floor, else pass through.
floorAltitudeM: (altM, floorM) => {
const hasAlt = Number.isFinite(altM);
const hasFloor = Number.isFinite(floorM);
if (hasAlt && hasFloor) return Math.max(altM, floorM);
if (hasAlt) return altM;
if (hasFloor) return floorM;
return null;
},
},
focus: { clearFocusTarget: (id) => calls.focusCleared.push(id) },
militaryRegistry: {},
readout: {},
selection: {
selectionDispatcherFor: () => ({
register: (id) => {
calls.registered.push(id);
return () => {};
},
}),
},
};
const parts = {
queries: {
_describeFlight: () => ({ callsign: 'ABC1', track: 90 }),
_contactLabel: () => 'ABC1',
_toCleanText: (value) => value || '',
_formatAltitude: () => '',
},
};
const tracking = layer.createTracking({
flightState,
services,
parts,
layer: {},
});
return { tracking, flightState, calls };
}
const heightOf = (position) => geo.cartographic.fromCartesian(position).height;
for (const layer of LAYERS) {
test(`${layer.name} tracking publishes its own layer identity`, () => {
const { tracking, calls } = harness(layer);
const context = tracking._contextSubjectMetadata('abc123');
assert.equal(context.layerId, layer.layerId);
assert.equal(context.layerName, layer.layerName);
// The route line is the civil layer's: military contexts carry none.
assert.equal('route' in context.properties, layer.name === 'flights');
tracking._installClickHandler();
assert.deepEqual(calls.registered, [layer.layerId]);
tracking._clearTracking();
assert.deepEqual(calls.focusCleared, [layer.focusId]);
});
test(`${layer.name} trail ${layer.floorsTrail ? 'lifts' : 'keeps'} a fix below the warm ground`, () => {
const { tracking, flightState } = harness(layer, { groundM: GROUND_M });
assert.equal('_trailFloorPosition' in tracking, layer.floorsTrail);
tracking._appendTrailFix(geo.cartesian3.fromDegrees(-106.6, 35.05, 10));
const height = heightOf(flightState._trailPositions[0]);
assert.ok(
Math.abs(height - (layer.floorsTrail ? GROUND_M : 10)) < 0.01,
`trail height ${height}`,
);
});
test(`${layer.name} backfill places and thins history by its own rules`, async () => {
const leading = harness(layer, {
track: [{ observedAtMs: 1000, latitude: 35, longitude: -106 }],
});
leading.flightState._trackedIcao = 'abc123';
await leading.tracking._backfillTrail('abc123', 0, Infinity);
assert.equal(leading.flightState._trailPositions.length, 1);
assert.ok(
Math.abs(
heightOf(leading.flightState._trailPositions[0]) -
layer.backfillLeadAltM,
) < 0.01,
);
const long = harness(layer, {
track: Array.from({ length: 1000 }, (_, index) => ({
observedAtMs: 1000 + index * 1000,
latitude: 35 + index * 0.001,
longitude: -106,
baroAltitudeM: 3000,
})),
});
long.flightState._trackedIcao = 'abc123';
await long.tracking._backfillTrail('abc123', 0, Infinity);
// 1000 points into a 400-vertex trail: stride-thinned (every 3rd) or
// only the newest 400 kept.
assert.equal(
long.flightState._trailPositions.length,
layer.thinsBackfill ? 334 : 400,
);
});
}
+2 -3
View File
@@ -22,11 +22,10 @@ const zeroCounts = () => ({
const world = ([lon, lat]) => geo.cartesian3.fromDegrees(lon, lat);
export function createCyclonesNavaraRenderer(engine, view, { overlayHost }) {
const display = createNavaraPolygonDisplay(engine, view, (color, show) => ({
polyline: { color, show, width: 2.5, clampToGround: true },
const display = createNavaraPolygonDisplay(engine, view, (color) => ({
polyline: { color, width: 2.5, clampToGround: true },
polygon: {
color,
show,
opacity: 0.16,
transparent: true,
clampToGround: true,
+1 -2
View File
@@ -1401,9 +1401,8 @@ export function createDirectionsLayer({
}
function flyCurrentRoute() {
if (!_route || (!_viewer && !_engine)) return false;
if (!_route || !_engine) return false;
cancelOwnedFlight('directions-refly');
if (_viewer) services.camera.initCameraVerbs(_viewer);
const seams = _shellSeams;
const result = services.camera.flyRoute(
[
File diff suppressed because it is too large. Load diff
+12 -17
View File
@@ -31,23 +31,18 @@ export function createInfrastructureNavaraRenderer(
sourceId: id,
host: services.overlayHost,
});
const display = createNavaraPolygonDisplay(
engine,
native.view,
(tint, show) => ({
polyline: { color: tint, show, width: 2, clampToGround: true },
polygon: {
color: tint,
show,
opacity: 0.3,
transparent: true,
clampToGround: true,
outline: true,
outlineColor: tint,
outlineWidth: 2,
},
}),
);
const display = createNavaraPolygonDisplay(engine, native.view, (tint) => ({
polyline: { color: tint, width: 2, clampToGround: true },
polygon: {
color: tint,
opacity: 0.3,
transparent: true,
clampToGround: true,
outline: true,
outlineColor: tint,
outlineWidth: 2,
},
}));
let dataset = null,
records = new Map(),
active = new Set(),
File diff suppressed because it is too large. Load diff
+40 -27
View File
@@ -1,7 +1,13 @@
/** GeoJSON features grouped by paint. Swap complete batches so a failed
* source or layer allocation cannot wipe the last rendered result. */
* source or layer allocation cannot wipe the last rendered result.
*
* Hidden means no layers at all: Navara 0.2.1 sometimes drops the first
* `layer.update({ show: false })` after a layer is added (a zone turned off
* right after an engine switch stayed drawn), while a deleted layer always
* goes. Showing again rebuilds the batches from the last groups. */
export function createNavaraPolygonDisplay(engine, view, style) {
let visible = false;
let groups = new Map();
let batches = [];
function release(items) {
for (const { layer, source } of items) {
@@ -9,43 +15,50 @@ export function createNavaraPolygonDisplay(engine, view, style) {
source.delete();
}
}
function build(next) {
const built = [];
try {
for (const [css, features] of next) {
const color = Number.parseInt(css.slice(1), 16);
const source = view.addSource({
type: 'geojson',
data: { type: 'FeatureCollection', features },
});
const batch = { source };
built.push(batch);
batch.layer = view.addLayer({
type: 'vector',
source,
...style(color),
});
}
} catch (error) {
release(built);
throw error;
}
release(batches);
batches = built;
}
return {
setVisible(show) {
if (visible === show) return;
visible = show;
for (const { color, source, layer } of batches) {
layer.update({ type: 'vector', source, ...style(color, show) });
if (show) build(groups);
else {
release(batches);
batches = [];
}
visible = show;
engine.render.request('polygon-visibility');
},
replace(groups) {
const next = [];
try {
for (const [css, features] of groups) {
const color = Number.parseInt(css.slice(1), 16);
const source = view.addSource({
type: 'geojson',
data: { type: 'FeatureCollection', features },
});
const batch = { source, color };
next.push(batch);
batch.layer = view.addLayer({
type: 'vector',
source,
...style(color, visible),
});
}
} catch (error) {
release(next);
throw error;
}
release(batches);
batches = next;
replace(next) {
if (visible) build(next);
groups = next;
engine.render.request('polygon-data');
},
destroy() {
release(batches);
batches = [];
groups = new Map();
engine.render.request('polygon-destroy');
},
};
@@ -0,0 +1,82 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createNavaraPolygonDisplay } from './navaraPolygons.js';
function fakeView({ failOn = null } = {}) {
const live = new Set();
let added = 0;
const handle = (kind, description) => {
const item = {
kind,
description,
delete: () => live.delete(item),
update: () => assert.fail('the display never updates a layer in place'),
};
live.add(item);
return item;
};
return {
live,
layers: () => [...live].filter((item) => item.kind === 'layer'),
addSource: (description) => handle('source', description),
addLayer: (description) => {
if (++added === failOn) throw new Error('layer allocation failed');
return handle('layer', description);
},
};
}
const engine = { render: { request() {} } };
const groups = (...colors) =>
new Map(colors.map((css) => [css, [{ type: 'Feature', id: css }]]));
test('a hidden display holds no Navara layers, and showing it rebuilds them', () => {
const view = fakeView();
const display = createNavaraPolygonDisplay(engine, view, (color) => ({
polygon: { color },
}));
display.replace(groups('#ff0000', '#00ff00'));
assert.equal(view.live.size, 0, 'nothing is built while hidden');
display.setVisible(true);
assert.deepEqual(
view.layers().map((layer) => layer.description.polygon.color),
[0xff0000, 0x00ff00],
);
// Navara 0.2.1 may drop a show:false update on a new layer: hiding deletes.
display.setVisible(false);
assert.equal(view.live.size, 0);
display.setVisible(true);
assert.equal(view.layers().length, 2);
display.destroy();
assert.equal(view.live.size, 0);
});
test('a visible display swaps whole batches and keeps the last on a failure', () => {
const view = fakeView({ failOn: 3 });
const display = createNavaraPolygonDisplay(engine, view, (color) => ({
polygon: { color },
}));
display.setVisible(true);
display.replace(groups('#ff0000'));
display.replace(groups('#0000ff'));
assert.deepEqual(
view.layers().map((layer) => layer.description.polygon.color),
[0x0000ff],
);
assert.throws(
() => display.replace(groups('#00ff00')),
/layer allocation failed/,
);
assert.deepEqual(
view.layers().map((layer) => layer.description.polygon.color),
[0x0000ff],
);
assert.equal(view.live.size, 2, 'the failed batch released its source');
// The failed rows were not adopted: hiding and showing redraws the last.
display.setVisible(false);
display.setVisible(true);
assert.deepEqual(
view.layers().map((layer) => layer.description.polygon.color),
[0x0000ff],
);
});
+1 -3
View File
@@ -14,17 +14,15 @@ export function createZonesNavaraRenderer(
{ idPrefix, colorOf },
) {
let polygons = [];
const display = createNavaraPolygonDisplay(engine, view, (color, show) => ({
const display = createNavaraPolygonDisplay(engine, view, (color) => ({
polygon: {
color,
show,
clampToGround: true,
transparent: true,
opacity: 0.25,
},
polyline: {
color,
show,
clampToGround: true,
width: 2,
transparent: true,