mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
Cut duplicated and dead code across the engines, the layers and the QA scripts
- src/geo drops the ported debug argument checks and the tests that bitExact already covers; package boundaries accept a directory entry, so src/geo/ is listed once per group. - Cesium no longer carries movers and lines nobody draws with: they are optional engine capabilities. The fake engine and the Cesium camera use the shared cameraMath; unused contract tables, clock.ticked, the 'finest' surface detail and Navara click statistics are gone. - ALPR keeps one overlay core and one presentation model for both engines, bikeshare one station bookkeeping, the Navara ground effects one definition helper; image atlases, view centres, mover banks and colours are shared. - The legacy switch route, the clock offset and rate controls and other unused exports are removed. - The acceptance runs the Navara draw, geo import and scope checks; scenarios use the harness switch and page helpers; the main chunk check keeps the size budget only and runs once in CI.
This commit is contained in:
1 parent
c502404e1d
commit
7abf74518f
272 files changed
+4828
-10213
No files matched your search
@@ -1,7 +1,6 @@
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../../data/aircraftModelLighting.js';
|
||||
// The aircraft renderer on Cesium (contract: ./contract.js): the Cesium
|
||||
// objects the aircraft layers used to build themselves, moved here one for
|
||||
// one — the fleet BillboardCollection and its sprite-order slot, the model
|
||||
// objects the aircraft layers draw with — the fleet BillboardCollection and its sprite-order slot, the model
|
||||
// PrimitiveCollection and its glTF loads, the tracked Entity (billboard with
|
||||
// per-frame CallbackProperties, followed through viewer.trackedEntity and
|
||||
// the one exact tracked frame), the trail entity and its live head
|
||||
@@ -19,7 +18,7 @@ import { horizonOccluder } from '../../../data/iconOrientation.js';
|
||||
import { engineFromViewer } from '../../../globe/cesium/engineFromViewer.js';
|
||||
import { applyTrackedCameraFrame } from '../../../globe/cesium/follow.js';
|
||||
|
||||
// The model shader of the IR boost (owner playtest 2026-08-16): boosted
|
||||
// The model shader of the IR boost: boosted
|
||||
// models render UNLIT so a side-lit airframe does not go black in FLIR/NVG.
|
||||
// Assigning a customShader to a ready model is a silent no-op, so the layer
|
||||
// reloads boosted models and the shader is set at creation. One stateless
|
||||
|
||||
@@ -3,7 +3,6 @@ import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createAircraftCesiumRenderer } from './cesium.js';
|
||||
import { missingAircraftRendererMembers } from './contract.js';
|
||||
import { CYAN, nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
|
||||
/** A viewer with what the renderer touches: primitives, entities, camera. */
|
||||
@@ -60,9 +59,8 @@ const renderer = (viewer, options = {}) =>
|
||||
...options,
|
||||
});
|
||||
|
||||
test('the Cesium aircraft renderer has every member of the contract', () => {
|
||||
test('the Cesium aircraft renderer reports its kind', () => {
|
||||
const { viewer } = stubViewer();
|
||||
assert.deepEqual(missingAircraftRendererMembers(renderer(viewer)), []);
|
||||
assert.equal(renderer(viewer).kind, 'cesium');
|
||||
});
|
||||
|
||||
|
||||
@@ -88,73 +88,3 @@
|
||||
* What a vertical surface probe must not hit: the layer's own drawings.
|
||||
* @property {() => void} destroy
|
||||
*/
|
||||
|
||||
/** The members every aircraft renderer has (shape checks, tests). */
|
||||
export const AIRCRAFT_RENDERER_SHAPE = Object.freeze({
|
||||
view: [
|
||||
'frameNumber',
|
||||
'viewportHeightPx',
|
||||
'frustumTester',
|
||||
'horizon',
|
||||
'worldToWindow',
|
||||
'requestRender',
|
||||
'on',
|
||||
'holdFrames',
|
||||
'closeFrameLatch',
|
||||
'releaseFrames',
|
||||
],
|
||||
fleet: [
|
||||
'attach',
|
||||
'detach',
|
||||
'attached',
|
||||
'visible',
|
||||
'setVisible',
|
||||
'add',
|
||||
'remove',
|
||||
'restoreOrder',
|
||||
'restoreOrderOnEnable',
|
||||
],
|
||||
models: [
|
||||
'live',
|
||||
'setVisible',
|
||||
'loadFleet',
|
||||
'loadTracked',
|
||||
'preload',
|
||||
'add',
|
||||
'remove',
|
||||
'destroy',
|
||||
'setPose',
|
||||
],
|
||||
tracked: [
|
||||
'create',
|
||||
'remove',
|
||||
'isLive',
|
||||
'setImage',
|
||||
'setViewFrom',
|
||||
'billboardSize',
|
||||
],
|
||||
follow: [
|
||||
'start',
|
||||
'refocus',
|
||||
'release',
|
||||
'isFollowing',
|
||||
'current',
|
||||
'onChanged',
|
||||
],
|
||||
trails: ['create', 'createHead', 'removeHead'],
|
||||
});
|
||||
|
||||
/**
|
||||
* The members of AIRCRAFT_RENDERER_SHAPE that `renderer` lacks
|
||||
* (['group.member', …]); empty for a complete renderer.
|
||||
*/
|
||||
export function missingAircraftRendererMembers(renderer) {
|
||||
const missing = [];
|
||||
for (const key of ['kind', 'view', 'surfaceExclusions', 'destroy'])
|
||||
if (renderer?.[key] === undefined) missing.push(key);
|
||||
for (const [group, members] of Object.entries(AIRCRAFT_RENDERER_SHAPE))
|
||||
for (const member of members)
|
||||
if (typeof renderer?.[group]?.[member] !== 'function')
|
||||
missing.push(`${group}.${member}`);
|
||||
return missing;
|
||||
}
|
||||
@@ -23,39 +23,33 @@ import {
|
||||
drawAircraftIconAtlas,
|
||||
} from '../../../data/aircraftIcons.js';
|
||||
import { createEngineLayerView } from '../../shared/render/engineView.js';
|
||||
import { rgbaFromCss } from '../../shared/color.js';
|
||||
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
|
||||
import {
|
||||
createMoverBank,
|
||||
StoredColor,
|
||||
writeFields,
|
||||
} from '../../shared/render/navaraMoverBank.js';
|
||||
|
||||
const BASE_SIZE_PX = 20;
|
||||
|
||||
/**
|
||||
* The model frame → glTF scene axes on Navara: Cesium's own glTF axis
|
||||
* correction, Y_UP_TO_Z_UP × Z_UP_TO_X_UP (data/modelVisualAnchor.js).
|
||||
* Navara's glTF loader is three's GLTFLoader, which keeps the scene Y-up.
|
||||
* (10b used Z_UP_TO_X_UP alone, on the belief that the loader turned the
|
||||
* scene Z-up: every fleet model drew 90° off its heading — side by side
|
||||
* with Cesium at the near pose, 10b review item 3.)
|
||||
* Navara's glTF loader is three's GLTFLoader, which keeps the scene Y-up,
|
||||
* so Z_UP_TO_X_UP alone would draw every model 90° off its heading.
|
||||
*/
|
||||
// Cesium's Axis.Y_UP_TO_Z_UP × Axis.Z_UP_TO_X_UP, column-major.
|
||||
const NAVARA_GLTF_AXIS = [0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1];
|
||||
const FIRST_CAPACITY = 1024;
|
||||
const ATLAS_PAD = 2;
|
||||
const TRAIL_ALPHA = 0.85;
|
||||
const TRAIL_OCCLUDED_ALPHA = 0.4;
|
||||
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Banks of mover sets
|
||||
// Sprite fields
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Reused set() arguments (set() copies them; no object per write).
|
||||
const fieldsNoPick = {
|
||||
position: undefined,
|
||||
orientation: undefined,
|
||||
color: undefined,
|
||||
rotation: undefined,
|
||||
scale: undefined,
|
||||
cell: undefined,
|
||||
show: undefined,
|
||||
};
|
||||
const scratchColor = new Float64Array(4);
|
||||
// Sprite setters write synchronously into the mover store; reuse their
|
||||
// field records rather than allocating one per contact and assignment.
|
||||
@@ -64,102 +58,6 @@ const spriteShowField = { show: true };
|
||||
const spriteRotationField = { rotation: 0 };
|
||||
const spriteScaleField = { scale: 1 };
|
||||
const spriteColorField = { color: scratchColor };
|
||||
function writeFields(set, index, fields) {
|
||||
const scratch = fieldsNoPick;
|
||||
for (const key in fields) scratch[key] = fields[key];
|
||||
set.set(index, scratch);
|
||||
for (const key in fields) scratch[key] = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A growing bank of one kind of mover: handles hold an index; removal moves
|
||||
* the last handle into the hole. `options(capacity, generation)` gives the
|
||||
* createSet options; `write(handle, set, index)` writes a handle whole.
|
||||
*/
|
||||
export function createMoverBank(engine, { options, write, onCommit }) {
|
||||
const handles = [];
|
||||
let set = null;
|
||||
let generation = 0;
|
||||
let capacity = 0;
|
||||
let visible = true;
|
||||
let dirty = false;
|
||||
const build = (wanted) => {
|
||||
const next = engine.movers.createSet(options(wanted, ++generation));
|
||||
set?.destroy();
|
||||
set = next;
|
||||
capacity = wanted;
|
||||
handles.forEach((handle, index) => write(handle, set, index));
|
||||
set.setCount(visible ? handles.length : 0);
|
||||
};
|
||||
const bank = {
|
||||
handles,
|
||||
get set() {
|
||||
return set;
|
||||
},
|
||||
ready: () => Boolean(set?.ready()),
|
||||
add(handle) {
|
||||
if (handle.gevBank === bank) return;
|
||||
handle.gevBank?.remove(handle);
|
||||
handle.gevBank = bank;
|
||||
handle.gevIndex = handles.length;
|
||||
handles.push(handle);
|
||||
if (!set || handles.length > capacity)
|
||||
build(Math.max(FIRST_CAPACITY, capacity * 2, handles.length));
|
||||
else {
|
||||
write(handle, set, handle.gevIndex);
|
||||
if (visible) set.setCount(handles.length);
|
||||
}
|
||||
bank.touch();
|
||||
},
|
||||
remove(handle) {
|
||||
if (handle.gevBank !== bank) return;
|
||||
const index = handle.gevIndex;
|
||||
const last = handles.pop();
|
||||
if (last !== handle) {
|
||||
handles[index] = last;
|
||||
last.gevIndex = index;
|
||||
write(last, set, index);
|
||||
}
|
||||
handle.gevBank = null;
|
||||
handle.gevIndex = -1;
|
||||
set?.setCount(visible ? handles.length : 0);
|
||||
bank.touch();
|
||||
},
|
||||
/** Writes `fields` of one handle (when it is in this bank). */
|
||||
update(handle, fields) {
|
||||
if (handle.gevBank !== bank || !set) return;
|
||||
writeFields(set, handle.gevIndex, fields);
|
||||
bank.touch();
|
||||
},
|
||||
setVisible(next) {
|
||||
visible = next;
|
||||
set?.setCount(visible ? handles.length : 0);
|
||||
bank.touch();
|
||||
},
|
||||
visible: () => visible,
|
||||
touch() {
|
||||
if (!dirty) {
|
||||
dirty = true;
|
||||
onCommit(bank);
|
||||
}
|
||||
},
|
||||
commit() {
|
||||
if (!dirty) return;
|
||||
dirty = false;
|
||||
set?.commit();
|
||||
},
|
||||
destroy() {
|
||||
for (const handle of handles) {
|
||||
handle.gevBank = null;
|
||||
handle.gevIndex = -1;
|
||||
}
|
||||
handles.length = 0;
|
||||
set?.destroy();
|
||||
set = null;
|
||||
},
|
||||
};
|
||||
return bank;
|
||||
}
|
||||
|
||||
const rgbaOf = (color, result = scratchColor) => {
|
||||
result[0] = color?.red ?? 1;
|
||||
@@ -169,20 +67,6 @@ const rgbaOf = (color, result = scratchColor) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
/** Plain colour copy (the stored value a handle's colour getter returns). */
|
||||
class StoredColor {
|
||||
constructor(color) {
|
||||
this.red = color?.red ?? 1;
|
||||
this.green = color?.green ?? 1;
|
||||
this.blue = color?.blue ?? 1;
|
||||
this.alpha = color?.alpha ?? 1;
|
||||
}
|
||||
|
||||
withAlpha(alpha) {
|
||||
return new StoredColor({ ...this, alpha });
|
||||
}
|
||||
}
|
||||
|
||||
const depthKey = (distance) =>
|
||||
distance === Number.POSITIVE_INFINITY
|
||||
? 'always'
|
||||
@@ -826,13 +710,9 @@ export function createAircraftNavaraRenderer({
|
||||
|
||||
// --- trails ----------------------------------------------------------------
|
||||
let lineSeq = 0;
|
||||
const rgbaFromCss = (css) => {
|
||||
const hex = String(css).replace('#', '');
|
||||
return [0, 2, 4].map((at) => parseInt(hex.slice(at, at + 2), 16) / 255);
|
||||
};
|
||||
const trails = {
|
||||
create({ color, width = 2.5 }) {
|
||||
const [r, g, b] = rgbaFromCss(color);
|
||||
const [r, g, b] = rgbaFromCss(color).rgba();
|
||||
const id = `gev-trail:${layerId}-${++lineSeq}`;
|
||||
let line = null;
|
||||
let visible = true;
|
||||
@@ -880,7 +760,7 @@ export function createAircraftNavaraRenderer({
|
||||
};
|
||||
},
|
||||
createHead({ id, show, positions, color, width = 2.5 }) {
|
||||
const [r, g, b] = rgbaFromCss(color);
|
||||
const [r, g, b] = rgbaFromCss(color).rgba();
|
||||
const line = engine.lines.createLine({
|
||||
id: `${id}`,
|
||||
widthPx: width,
|
||||
@@ -946,5 +826,23 @@ export function createAircraftNavaraRenderer({
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Navara registry factory (src/app/layers/renderers.js) of one aircraft
|
||||
* layer: its sprite slot (data/spriteOrder's order on Cesium) and its
|
||||
* model's nose offset.
|
||||
* @param {string} layerId
|
||||
* @param {number} headingOffsetDeg
|
||||
*/
|
||||
export function aircraftLayerNavaraRenderer(layerId, headingOffsetDeg) {
|
||||
/** @param {import('../../../globe/contract.js').GlobeEngine} engine */
|
||||
return (engine) =>
|
||||
createAircraftNavaraRenderer({
|
||||
engine,
|
||||
layerId,
|
||||
order: SPRITE_LAYER_ORDER.indexOf(layerId),
|
||||
headingOffsetDeg,
|
||||
});
|
||||
}
|
||||
|
||||
// The glyph atlas helpers, re-exported for tests.
|
||||
export { aircraftIconAtlasLayout as aircraftAtlasLayout, aircraftIconCells };
|
||||
@@ -10,7 +10,6 @@ import * as geo from '../../../geo/index.js';
|
||||
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../../data/aircraftIcons.js';
|
||||
import { CYAN, WHITE, nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
import { missingAircraftRendererMembers } from './contract.js';
|
||||
import {
|
||||
aircraftAtlasLayout,
|
||||
aircraftIconCells,
|
||||
@@ -39,9 +38,8 @@ async function setup() {
|
||||
const setsOf = (engine, prefix) =>
|
||||
engine.movers.list().filter(({ id }) => id.startsWith(prefix));
|
||||
|
||||
test('the Navara aircraft renderer has every member of the contract', async () => {
|
||||
test('the Navara aircraft renderer reports its kind', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
assert.deepEqual(missingAircraftRendererMembers(renderer), []);
|
||||
assert.equal(renderer.kind, 'navara');
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
import * as geo from '../../geo/index.js';
|
||||
import {
|
||||
MAX_CANVAS_FRUSTUMS,
|
||||
MARKER_ICON_SIZE,
|
||||
SELECTED_MARKER_ICON_SIZE,
|
||||
MARKER_FLOOR_LIFT_M,
|
||||
ANCHOR_SAMPLES_PER_PAINT,
|
||||
SURFACE_BELOW_FLOOR_M,
|
||||
SURFACE_ABOVE_FLOOR_M,
|
||||
SURFACE_SAMPLES_PER_PAINT,
|
||||
} from './policy.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
BRACKETS_IMAGE,
|
||||
directionWedgePositions,
|
||||
markerScale,
|
||||
paintDirectionWedge,
|
||||
validAlprGroundHeight,
|
||||
} from './visuals.js';
|
||||
|
||||
/**
|
||||
* Canvas artwork for the nearest ALPR cameras over each engine's native
|
||||
* markers, with bounded surface refinement. The engine adapter owns marker
|
||||
* lookup and appearance, surface sampling, the camera pose and projection.
|
||||
* @param {object} options
|
||||
* @param {object} options.state Layer state.
|
||||
* @param {object} options.services Layer services.
|
||||
* @param {function(): void} [options.onSurfaceChange] Map stack changed.
|
||||
* @param {object} options.engine Engine adapter.
|
||||
*/
|
||||
export function createAlprOverlayCore({
|
||||
state,
|
||||
services,
|
||||
onSurfaceChange = () => {},
|
||||
engine,
|
||||
}) {
|
||||
let lane,
|
||||
removeMapListener,
|
||||
retryTimer,
|
||||
retryUntil = 0;
|
||||
let records = [],
|
||||
hits = [],
|
||||
images = [],
|
||||
destroyed = false,
|
||||
lastCamera = null;
|
||||
const requestPaint = () => {
|
||||
if (!destroyed && state.enabled) lane?.requestPaint();
|
||||
};
|
||||
|
||||
function nativeVisible(marker, visible) {
|
||||
if (!marker) return;
|
||||
engine.canvasOwned(marker, !visible);
|
||||
engine.setShown(marker, visible);
|
||||
}
|
||||
|
||||
function resetAnchors() {
|
||||
for (const marker of engine.markers()) {
|
||||
marker.gevAlprCanvasPosition = null;
|
||||
marker.gevAlprWedge = null;
|
||||
engine.setDisplayPosition(marker, null);
|
||||
nativeVisible(marker, true);
|
||||
}
|
||||
state.lastAnchorSampleAt = 0;
|
||||
retryUntil = Date.now() + 15000;
|
||||
requestPaint();
|
||||
}
|
||||
|
||||
function anchorFor(record, marker, budget) {
|
||||
if (marker.gevAlprCanvasPosition) return marker.gevAlprCanvasPosition;
|
||||
// A floor-placed marker anchors where its native badge sits; only a
|
||||
// marker still waiting for its floor samples the rendered surface, and
|
||||
// each paint samples a few at most.
|
||||
let height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
|
||||
else if (engine.surfaceSupported()) {
|
||||
if (budget.samples <= 0) return null;
|
||||
budget.samples -= 1;
|
||||
try {
|
||||
height = engine.sampleHeight(record, marker);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
}
|
||||
if (!validAlprGroundHeight(height)) height = engine.terrainHeight(record);
|
||||
if (!validAlprGroundHeight(height)) return null;
|
||||
setAnchor(record, marker, height);
|
||||
return marker.gevAlprCanvasPosition;
|
||||
}
|
||||
|
||||
function floorHeightAt(latitude, longitude) {
|
||||
const floor = services.groundFloor.cachedGroundFloor(latitude, longitude);
|
||||
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
|
||||
}
|
||||
|
||||
function setAnchor(record, marker, height) {
|
||||
engine.placeAnchor(marker, record, height);
|
||||
marker.gevAlprWedge = directionWedgePositions(
|
||||
record,
|
||||
height,
|
||||
floorHeightAt,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace floor anchors with the rendered surface under each overlay camera.
|
||||
* Floors come from ~111 m cells, so on a slope a badge could float or sink
|
||||
* by tens of metres. Runs only while the camera is still and tiles have
|
||||
* settled, a few surface samples per paint, and each anchor at most once;
|
||||
* samples far outside the floor prior (a roof or a streaming tile) are
|
||||
* rejected. Returns whether anchors remain to check.
|
||||
*/
|
||||
function refineAnchors(budget) {
|
||||
const camera = engine.cameraPose();
|
||||
const still =
|
||||
lastCamera &&
|
||||
camera.position &&
|
||||
geo.cartesian3.equalsEpsilon(
|
||||
camera.position,
|
||||
lastCamera.position,
|
||||
0,
|
||||
0.05,
|
||||
) &&
|
||||
geo.cartesian3.equalsEpsilon(
|
||||
camera.direction,
|
||||
lastCamera.direction,
|
||||
0,
|
||||
1e-6,
|
||||
);
|
||||
if (camera.position && camera.direction)
|
||||
lastCamera = {
|
||||
position: geo.cartesian3.clone(camera.position),
|
||||
direction: geo.cartesian3.clone(camera.direction),
|
||||
};
|
||||
if (!engine.surfaceSupported()) return false;
|
||||
let pending = false;
|
||||
for (const record of records) {
|
||||
const marker = engine.marker(record.id);
|
||||
const anchor = marker?.gevAlprCanvasPosition;
|
||||
if (!anchor || marker.gevAlprSurfaceCheckedFor === anchor) continue;
|
||||
if (!still || !engine.surfaceSettled() || budget.samples <= 0) {
|
||||
pending = true;
|
||||
continue;
|
||||
}
|
||||
budget.samples -= 1;
|
||||
let sample;
|
||||
try {
|
||||
sample = engine.sampleHeight(record, marker);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
const current = geo.cartographic.fromCartesian(anchor).height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
const accepted =
|
||||
validAlprGroundHeight(sample) &&
|
||||
(!validAlprGroundHeight(floor) ||
|
||||
(sample >= floor - SURFACE_BELOW_FLOOR_M &&
|
||||
sample <= floor + SURFACE_ABOVE_FLOOR_M));
|
||||
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
|
||||
setAnchor(record, marker, sample + MARKER_FLOOR_LIFT_M);
|
||||
marker.gevAlprSurfaceCheckedFor = marker.gevAlprCanvasPosition;
|
||||
if (marker.id === state.selectedId)
|
||||
engine.setDisplayPosition(marker, marker.gevAlprCanvasPosition);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
function paint(frame) {
|
||||
const { ctx, width, height, keyhole } = frame;
|
||||
hits = [];
|
||||
if (!state.enabled || destroyed) return;
|
||||
const { horizonVisible, project } = engine.projector(frame);
|
||||
let unresolved = false;
|
||||
const painted = [];
|
||||
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
|
||||
for (const record of records) {
|
||||
const marker = engine.marker(record.id);
|
||||
if (!marker) continue;
|
||||
const selected = record.id === state.selectedId;
|
||||
const image = images[selected ? 1 : 0];
|
||||
if (
|
||||
!image?.complete ||
|
||||
!image.naturalWidth ||
|
||||
(selected && !images[2]?.naturalWidth)
|
||||
) {
|
||||
nativeVisible(marker, true);
|
||||
continue;
|
||||
}
|
||||
const anchor = anchorFor(record, marker, budget);
|
||||
if (!anchor) {
|
||||
nativeVisible(marker, true);
|
||||
unresolved = true;
|
||||
continue;
|
||||
}
|
||||
engine.canvasOwned(marker, true);
|
||||
if (!horizonVisible(anchor)) {
|
||||
engine.setShown(marker, false);
|
||||
continue;
|
||||
}
|
||||
const origin = project(anchor);
|
||||
if (!origin) {
|
||||
engine.setShown(marker, false);
|
||||
continue;
|
||||
}
|
||||
const alpha =
|
||||
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
|
||||
if (!(alpha > 0)) {
|
||||
engine.setShown(marker, false);
|
||||
continue;
|
||||
}
|
||||
const wedge = marker.gevAlprWedge;
|
||||
if (wedge) {
|
||||
const left = project(wedge[1]);
|
||||
const right = project(wedge[2]);
|
||||
if (
|
||||
left &&
|
||||
right &&
|
||||
(!engine.cullOffscreenWedges ||
|
||||
(Math.max(origin.x, left.x, right.x) >= -3 &&
|
||||
Math.min(origin.x, left.x, right.x) <= width + 3 &&
|
||||
Math.max(origin.y, left.y, right.y) >= -3 &&
|
||||
Math.min(origin.y, left.y, right.y) <= height + 3))
|
||||
) {
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
paintDirectionWedge(ctx, origin, left, right, selected);
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
if (
|
||||
origin.x < -60 ||
|
||||
origin.x > width + 60 ||
|
||||
origin.y < -60 ||
|
||||
origin.y > height + 60
|
||||
) {
|
||||
engine.setShown(marker, false);
|
||||
continue;
|
||||
}
|
||||
engine.setShown(marker, true);
|
||||
painted.push({
|
||||
record,
|
||||
origin,
|
||||
selected,
|
||||
image,
|
||||
alpha,
|
||||
scale: markerScale(
|
||||
geo.cartesian3.distance(engine.cameraPosition(), anchor),
|
||||
),
|
||||
});
|
||||
if (selected) engine.setDisplayPosition(marker, anchor);
|
||||
}
|
||||
// Paint all glyphs after the wedges so one camera's cone cannot wash out another.
|
||||
for (const { record, origin, selected, image, alpha, scale } of painted) {
|
||||
const size =
|
||||
(selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE) * scale;
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
ctx.drawImage(
|
||||
image,
|
||||
origin.x - size / 2,
|
||||
origin.y - size / 2,
|
||||
size,
|
||||
size,
|
||||
);
|
||||
if (selected)
|
||||
ctx.drawImage(
|
||||
images[2],
|
||||
origin.x - size / 2,
|
||||
origin.y - size / 2,
|
||||
size,
|
||||
size,
|
||||
);
|
||||
ctx.restore();
|
||||
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
|
||||
}
|
||||
const refining = refineAnchors({
|
||||
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT),
|
||||
});
|
||||
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
requestPaint();
|
||||
}, 250);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
init() {
|
||||
destroyed = false;
|
||||
removeMapListener = services.overlays?.subscribeMapStack?.((event) => {
|
||||
if (event.detail?.status !== 'ready' || !state.enabled) return;
|
||||
// Same-regime provider changes also invalidate absolute placements.
|
||||
onSurfaceChange();
|
||||
resetAnchors();
|
||||
});
|
||||
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
|
||||
return;
|
||||
lane = services.overlays.registerPaintLane('selected', paint, {
|
||||
id: `alpr-${engine.createId()}`,
|
||||
active: false,
|
||||
});
|
||||
images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => {
|
||||
const image = new Image();
|
||||
image.onload = requestPaint;
|
||||
image.onerror = requestPaint;
|
||||
image.src = src;
|
||||
return image;
|
||||
});
|
||||
},
|
||||
sync(visible) {
|
||||
if (!lane) return;
|
||||
for (const record of records)
|
||||
nativeVisible(engine.marker(record.id), true);
|
||||
const position = engine.cameraPosition();
|
||||
records = visible
|
||||
.filter(
|
||||
(record) =>
|
||||
Number.isFinite(record.directionDeg) &&
|
||||
record.id !== state.selectedId,
|
||||
)
|
||||
.map((record) => ({
|
||||
record,
|
||||
distance: position
|
||||
? geo.cartesian3.distanceSquared(
|
||||
position,
|
||||
geo.cartesian3.fromDegrees(record.longitude, record.latitude),
|
||||
)
|
||||
: 0,
|
||||
}))
|
||||
.sort((a, b) => a.distance - b.distance)
|
||||
.slice(0, MAX_CANVAS_FRUSTUMS)
|
||||
.map((item) => item.record);
|
||||
const selected = visible.find((record) => record.id === state.selectedId);
|
||||
if (selected) {
|
||||
if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop();
|
||||
records.push(selected);
|
||||
}
|
||||
hits = [];
|
||||
retryUntil = Date.now() + 15000;
|
||||
lane.setActive(state.enabled && records.length > 0);
|
||||
requestPaint();
|
||||
},
|
||||
pick(position) {
|
||||
if (!state.enabled || !position) return null;
|
||||
let closest,
|
||||
distance = Infinity;
|
||||
for (const hit of hits) {
|
||||
const next = (hit.x - position.x) ** 2 + (hit.y - position.y) ** 2;
|
||||
if (next <= hit.radius ** 2 && next <= distance) {
|
||||
closest = hit.id;
|
||||
distance = next;
|
||||
}
|
||||
}
|
||||
return closest || null;
|
||||
},
|
||||
clear() {
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = null;
|
||||
for (const record of records)
|
||||
nativeVisible(engine.marker(record.id), true);
|
||||
records = [];
|
||||
hits = [];
|
||||
lane?.setActive(false);
|
||||
},
|
||||
destroy() {
|
||||
this.clear();
|
||||
destroyed = true;
|
||||
removeMapListener?.();
|
||||
removeMapListener = null;
|
||||
lane?.unregister();
|
||||
lane = null;
|
||||
for (const image of images) {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
}
|
||||
images = [];
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -197,8 +197,8 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
|
||||
});
|
||||
|
||||
test('repeated paints of a still view never rewrite marker properties', (t) => {
|
||||
// Each Entity write raises definitionChanged; paint used to hide then show
|
||||
// every overlay camera's native marker on every frame.
|
||||
// Each Entity write raises definitionChanged, so a still view must not hide
|
||||
// and re-show every overlay camera's native marker on every frame.
|
||||
const h = harness(t, 3);
|
||||
h.overlay.sync(h.records);
|
||||
h.paint();
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
import { boxContains } from './model.js';
|
||||
import {
|
||||
LAYER_ID,
|
||||
MAX_RENDERED,
|
||||
MAX_VIEWPORT_DEGREES,
|
||||
SELECTED_MARKER_ICON_SIZE,
|
||||
} from './policy.js';
|
||||
import { alprDisplayId, alprLabelDetails } from './visuals.js';
|
||||
|
||||
/**
|
||||
* Bounded nearby coverage around the ground point at the centre of the view.
|
||||
* The horizon rectangle is unstable during low-angle orbits and can exclude
|
||||
* that point; the camera-to-ground range keeps zoom-out queries capped.
|
||||
* @param {{latitude:number, longitude:number}} location Focus, radians.
|
||||
* @param {number} range Camera-to-focus distance in metres.
|
||||
* @returns {{south:number, west:number, north:number, east:number}|null}
|
||||
*/
|
||||
export function alprFocusBox(location, range) {
|
||||
const radius = Math.max(1000, 2 * range);
|
||||
const latitude = geo.math.toDegrees(location.latitude);
|
||||
const longitude = geo.math.toDegrees(location.longitude);
|
||||
const latSpan = radius / 111000;
|
||||
const lonSpan = latSpan / Math.cos(location.latitude);
|
||||
if (
|
||||
!Number.isFinite(latSpan + lonSpan) ||
|
||||
2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES ||
|
||||
Math.abs(latitude) + latSpan > 90 ||
|
||||
Math.abs(longitude) + lonSpan > 180
|
||||
)
|
||||
return null;
|
||||
return {
|
||||
south: latitude - latSpan,
|
||||
west: longitude - lonSpan,
|
||||
north: latitude + latSpan,
|
||||
east: longitude + lonSpan,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a view box would display, nearest the box centre first when over
|
||||
* the render cap.
|
||||
* @param {Array<object>} records Candidate records.
|
||||
* @param {object|null} box Viewport box in degrees.
|
||||
* @returns {{visible: Array<object>, capped: boolean}}
|
||||
*/
|
||||
export function alprViewRecords(records, box) {
|
||||
if (!box) return { visible: [], capped: false };
|
||||
let visible = records.filter((record) =>
|
||||
boxContains(box, {
|
||||
south: record.latitude,
|
||||
north: record.latitude,
|
||||
west: record.longitude,
|
||||
east: record.longitude,
|
||||
}),
|
||||
);
|
||||
const capped = visible.length > MAX_RENDERED;
|
||||
if (capped) {
|
||||
const lat = (box.south + box.north) / 2;
|
||||
const lon = (box.west + box.east) / 2;
|
||||
const scale = Math.cos((lat * Math.PI) / 180);
|
||||
const distance = (record) =>
|
||||
(record.latitude - lat) ** 2 + ((record.longitude - lon) * scale) ** 2;
|
||||
visible = visible
|
||||
.map((record) => ({ record, d: distance(record) }))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
.slice(0, MAX_RENDERED)
|
||||
.map((item) => item.record);
|
||||
}
|
||||
return { visible, capped };
|
||||
}
|
||||
|
||||
/** The selected-camera card shown beside a marker. */
|
||||
export function alprLabelModel(record, source, { accent, startedAt }) {
|
||||
return {
|
||||
title: alprDisplayId(record),
|
||||
details: alprLabelDetails(record, source),
|
||||
accent,
|
||||
cardStyle: 'tactical',
|
||||
selected: true,
|
||||
leaderStyle: 'elbow',
|
||||
leaderAnimationMs: 440,
|
||||
leaderAnimationStartedAt: startedAt,
|
||||
leaderDrawRatio: 0.68,
|
||||
anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2,
|
||||
anchorRadiusScale: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Entity-context fields for one camera record. */
|
||||
export function alprEntityContext(record, source) {
|
||||
return {
|
||||
id: record.id,
|
||||
layerId: LAYER_ID,
|
||||
layerName: 'ALPR Cameras',
|
||||
source: source.attribution?.description || source.label || 'Camera source',
|
||||
label: msg('ALPR camera'),
|
||||
latitude: record.latitude,
|
||||
longitude: record.longitude,
|
||||
properties: {
|
||||
operator: record.operator,
|
||||
manufacturer: record.manufacturer,
|
||||
cameraType: record.cameraType,
|
||||
zone: record.zone,
|
||||
directionDeg: record.directionDeg,
|
||||
ref: record.ref,
|
||||
lastVerified: record.lastVerified,
|
||||
osmId: record.osmId,
|
||||
sourceTag: record.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,23 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
MAX_CANVAS_FRUSTUMS,
|
||||
MARKER_ICON_SIZE,
|
||||
SELECTED_MARKER_ICON_SIZE,
|
||||
MARKER_FLOOR_LIFT_M,
|
||||
ANCHOR_SAMPLES_PER_PAINT,
|
||||
SURFACE_BELOW_FLOOR_M,
|
||||
SURFACE_ABOVE_FLOOR_M,
|
||||
SURFACE_SAMPLES_PER_PAINT,
|
||||
} from '../policy.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
BRACKETS_IMAGE,
|
||||
directionWedgePositions,
|
||||
markerScale,
|
||||
paintDirectionWedge,
|
||||
validAlprGroundHeight,
|
||||
} from '../visuals.js';
|
||||
import { createAlprOverlayCore } from '../overlay.js';
|
||||
|
||||
/** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */
|
||||
export function createAlprOverlay({
|
||||
@@ -26,24 +8,9 @@ export function createAlprOverlay({
|
||||
services,
|
||||
onSurfaceChange = () => {},
|
||||
}) {
|
||||
let lane,
|
||||
removeMapListener,
|
||||
retryTimer,
|
||||
retryUntil = 0;
|
||||
let records = [],
|
||||
hits = [],
|
||||
images = [],
|
||||
destroyed = false,
|
||||
lastCamera = null;
|
||||
const requestPaint = () => {
|
||||
if (!destroyed && state.enabled) lane?.requestPaint();
|
||||
};
|
||||
|
||||
function nativeVisible(entity, visible) {
|
||||
if (!entity) return;
|
||||
canvasOwned(entity, !visible);
|
||||
setShown(entity, visible);
|
||||
}
|
||||
const scene = () => native.viewer.scene;
|
||||
const location = (record) =>
|
||||
Cesium.Cartographic.fromDegrees(record.longitude, record.latitude);
|
||||
|
||||
/** Swap a marker between its native look and a faint canvas pick target. */
|
||||
function canvasOwned(entity, owned) {
|
||||
@@ -76,8 +43,7 @@ export function createAlprOverlay({
|
||||
}
|
||||
|
||||
// Assign only on change: each Entity property write mints a new property
|
||||
// and raises definitionChanged, which paint used to do for every overlay
|
||||
// camera on every frame.
|
||||
// and raises definitionChanged.
|
||||
function setShown(entity, visible) {
|
||||
if (entity.gevAlprShown === visible) return;
|
||||
entity.gevAlprShown = visible;
|
||||
@@ -86,360 +52,57 @@ export function createAlprOverlay({
|
||||
if (entity.polygon) entity.polygon.show = visible;
|
||||
}
|
||||
|
||||
function resetAnchors() {
|
||||
for (const entity of native.dataSource.entities.values) {
|
||||
entity.gevAlprCanvasPosition = null;
|
||||
entity.gevAlprWedge = null;
|
||||
entity.gevAlprDisplayPosition = null;
|
||||
nativeVisible(entity, true);
|
||||
}
|
||||
state.lastAnchorSampleAt = 0;
|
||||
retryUntil = Date.now() + 15000;
|
||||
requestPaint();
|
||||
}
|
||||
|
||||
function anchorFor(record, entity, budget) {
|
||||
if (entity.gevAlprCanvasPosition) return entity.gevAlprCanvasPosition;
|
||||
const scene = native.viewer.scene;
|
||||
const location = Cesium.Cartographic.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
);
|
||||
// A floor-placed marker anchors where its native badge sits; only a
|
||||
// marker still waiting for its floor samples the rendered surface, and
|
||||
// each paint samples a few at most (each sample is a depth render).
|
||||
let height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
|
||||
else if (scene.sampleHeightSupported) {
|
||||
if (budget.samples <= 0) return null;
|
||||
budget.samples -= 1;
|
||||
try {
|
||||
height = scene.sampleHeight(location, [entity]);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
}
|
||||
if (!validAlprGroundHeight(height) && scene.globe.show)
|
||||
height = scene.globe.getHeight?.(location);
|
||||
if (!validAlprGroundHeight(height)) return null;
|
||||
setAnchor(record, entity, height);
|
||||
return entity.gevAlprCanvasPosition;
|
||||
}
|
||||
|
||||
function floorHeightAt(latitude, longitude) {
|
||||
const floor = services.groundFloor.cachedGroundFloor(latitude, longitude);
|
||||
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
|
||||
}
|
||||
|
||||
function setAnchor(record, entity, height) {
|
||||
entity.gevAlprCanvasPosition = Cesium.Cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
height,
|
||||
);
|
||||
entity.gevAlprWedge = directionWedgePositions(
|
||||
record,
|
||||
height,
|
||||
floorHeightAt,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the visible photoreal tiles (or globe) have finished streaming. */
|
||||
function surfaceSettled(scene) {
|
||||
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
|
||||
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
|
||||
const primitive = scene.primitives.get(i);
|
||||
function surfaceSettled() {
|
||||
const { globe, primitives } = scene();
|
||||
if (globe?.show) return globe.tilesLoaded !== false;
|
||||
for (let i = 0; i < (primitives?.length || 0); i++) {
|
||||
const primitive = primitives.get(i);
|
||||
if (primitive?.show && primitive.tilesLoaded === false) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace floor anchors with the rendered surface under each overlay camera.
|
||||
* Floors come from ~111 m cells, so on a slope a badge could float or sink
|
||||
* by tens of metres. Runs only while the camera is still and tiles have
|
||||
* settled, a few depth samples per paint, and each anchor at most once;
|
||||
* samples far outside the floor prior (a roof or a streaming tile) are
|
||||
* rejected. Returns whether anchors remain to check.
|
||||
*/
|
||||
function refineAnchors(budget) {
|
||||
const camera = native.viewer.camera;
|
||||
const scene = native.viewer.scene;
|
||||
const still =
|
||||
lastCamera &&
|
||||
camera.positionWC &&
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
camera.positionWC,
|
||||
lastCamera.position,
|
||||
0,
|
||||
0.05,
|
||||
) &&
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
camera.directionWC,
|
||||
lastCamera.direction,
|
||||
0,
|
||||
1e-6,
|
||||
);
|
||||
if (camera.positionWC && camera.directionWC)
|
||||
lastCamera = {
|
||||
position: Cesium.Cartesian3.clone(camera.positionWC),
|
||||
direction: Cesium.Cartesian3.clone(camera.directionWC),
|
||||
};
|
||||
if (!scene.sampleHeightSupported) return false;
|
||||
let pending = false;
|
||||
for (const record of records) {
|
||||
const entity = native.dataSource.entities.getById(record.id);
|
||||
const anchor = entity?.gevAlprCanvasPosition;
|
||||
if (!anchor || entity.gevAlprSurfaceCheckedFor === anchor) continue;
|
||||
if (!still || !surfaceSettled(scene) || budget.samples <= 0) {
|
||||
pending = true;
|
||||
continue;
|
||||
}
|
||||
budget.samples -= 1;
|
||||
let sample;
|
||||
try {
|
||||
sample = scene.sampleHeight(
|
||||
Cesium.Cartographic.fromDegrees(record.longitude, record.latitude),
|
||||
[entity],
|
||||
return createAlprOverlayCore({
|
||||
state,
|
||||
services,
|
||||
onSurfaceChange,
|
||||
engine: {
|
||||
marker: (id) => native.dataSource?.entities.getById(id),
|
||||
markers: () => native.dataSource.entities.values,
|
||||
canvasOwned,
|
||||
setShown,
|
||||
setDisplayPosition(entity, position) {
|
||||
entity.gevAlprDisplayPosition = position;
|
||||
},
|
||||
placeAnchor(entity, record, height) {
|
||||
entity.gevAlprCanvasPosition = Cesium.Cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
height,
|
||||
);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
const current = Cesium.Cartographic.fromCartesian(anchor).height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
const accepted =
|
||||
validAlprGroundHeight(sample) &&
|
||||
(!validAlprGroundHeight(floor) ||
|
||||
(sample >= floor - SURFACE_BELOW_FLOOR_M &&
|
||||
sample <= floor + SURFACE_ABOVE_FLOOR_M));
|
||||
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
|
||||
setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M);
|
||||
entity.gevAlprSurfaceCheckedFor = entity.gevAlprCanvasPosition;
|
||||
if (entity.id === state.selectedId)
|
||||
entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition;
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
function paint({ ctx, width, height, keyhole, occluder }) {
|
||||
hits = [];
|
||||
if (!state.enabled || destroyed) return;
|
||||
let unresolved = false;
|
||||
const painted = [];
|
||||
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
|
||||
for (const record of records) {
|
||||
const entity = native.dataSource.entities.getById(record.id);
|
||||
if (!entity) continue;
|
||||
const selected = record.id === state.selectedId;
|
||||
const image = images[selected ? 1 : 0];
|
||||
if (
|
||||
!image?.complete ||
|
||||
!image.naturalWidth ||
|
||||
(selected && !images[2]?.naturalWidth)
|
||||
) {
|
||||
nativeVisible(entity, true);
|
||||
continue;
|
||||
}
|
||||
const anchor = anchorFor(record, entity, budget);
|
||||
if (!anchor) {
|
||||
nativeVisible(entity, true);
|
||||
unresolved = true;
|
||||
continue;
|
||||
}
|
||||
canvasOwned(entity, true);
|
||||
if (occluder && !occluder.isPointVisible(anchor)) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const scene = native.viewer.scene;
|
||||
const origin = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
anchor,
|
||||
);
|
||||
if (!origin) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const alpha =
|
||||
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
|
||||
if (!(alpha > 0)) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const wedge = entity.gevAlprWedge;
|
||||
if (wedge) {
|
||||
const left = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
wedge[1],
|
||||
);
|
||||
const right = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
wedge[2],
|
||||
);
|
||||
if (left && right) {
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
paintDirectionWedge(ctx, origin, left, right, selected);
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
if (
|
||||
origin.x < -60 ||
|
||||
origin.x > width + 60 ||
|
||||
origin.y < -60 ||
|
||||
origin.y > height + 60
|
||||
) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
setShown(entity, true);
|
||||
painted.push({
|
||||
record,
|
||||
origin,
|
||||
selected,
|
||||
image,
|
||||
alpha,
|
||||
scale: markerScale(
|
||||
Cesium.Cartesian3.distance(native.viewer.camera.positionWC, anchor),
|
||||
),
|
||||
});
|
||||
if (selected) entity.gevAlprDisplayPosition = anchor;
|
||||
}
|
||||
// Paint all glyphs after the wedges so one camera's cone cannot wash out another.
|
||||
for (const { record, origin, selected, image, alpha, scale } of painted) {
|
||||
const size =
|
||||
(selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE) * scale;
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
ctx.drawImage(
|
||||
image,
|
||||
origin.x - size / 2,
|
||||
origin.y - size / 2,
|
||||
size,
|
||||
size,
|
||||
);
|
||||
if (selected)
|
||||
ctx.drawImage(
|
||||
images[2],
|
||||
origin.x - size / 2,
|
||||
origin.y - size / 2,
|
||||
size,
|
||||
size,
|
||||
);
|
||||
ctx.restore();
|
||||
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
|
||||
}
|
||||
const refining = refineAnchors({
|
||||
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT),
|
||||
});
|
||||
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
requestPaint();
|
||||
}, 250);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
init() {
|
||||
destroyed = false;
|
||||
removeMapListener = services.overlays?.subscribeMapStack?.((event) => {
|
||||
if (event.detail?.status !== 'ready' || !state.enabled) return;
|
||||
// Same-regime provider changes also invalidate absolute placements.
|
||||
onSurfaceChange();
|
||||
resetAnchors();
|
||||
});
|
||||
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
|
||||
return;
|
||||
lane = services.overlays.registerPaintLane('selected', paint, {
|
||||
id: `alpr-${Cesium.createGuid()}`,
|
||||
active: false,
|
||||
});
|
||||
images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => {
|
||||
const image = new Image();
|
||||
image.onload = requestPaint;
|
||||
image.onerror = requestPaint;
|
||||
image.src = src;
|
||||
return image;
|
||||
});
|
||||
},
|
||||
surfaceSupported: () => scene().sampleHeightSupported,
|
||||
// Each sample is a depth render.
|
||||
sampleHeight: (record, entity) =>
|
||||
scene().sampleHeight(location(record), [entity]),
|
||||
terrainHeight: (record) =>
|
||||
scene().globe.show
|
||||
? scene().globe.getHeight?.(location(record))
|
||||
: undefined,
|
||||
surfaceSettled,
|
||||
cameraPose: () => ({
|
||||
position: native.viewer.camera.positionWC,
|
||||
direction: native.viewer.camera.directionWC,
|
||||
}),
|
||||
cameraPosition: () => native.viewer.camera.positionWC,
|
||||
projector: ({ occluder }) => ({
|
||||
horizonVisible: (point) => !occluder || occluder.isPointVisible(point),
|
||||
project: (point) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(scene(), point),
|
||||
}),
|
||||
cullOffscreenWedges: false,
|
||||
createId: () => Cesium.createGuid(),
|
||||
},
|
||||
sync(visible) {
|
||||
if (!lane) return;
|
||||
for (const record of records)
|
||||
nativeVisible(native.dataSource.entities.getById(record.id), true);
|
||||
const position = native.viewer.camera.positionWC;
|
||||
records = visible
|
||||
.filter(
|
||||
(record) =>
|
||||
Number.isFinite(record.directionDeg) &&
|
||||
record.id !== state.selectedId,
|
||||
)
|
||||
.map((record) => ({
|
||||
record,
|
||||
distance: position
|
||||
? Cesium.Cartesian3.distanceSquared(
|
||||
position,
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
),
|
||||
)
|
||||
: 0,
|
||||
}))
|
||||
.sort((a, b) => a.distance - b.distance)
|
||||
.slice(0, MAX_CANVAS_FRUSTUMS)
|
||||
.map((item) => item.record);
|
||||
const selected = visible.find((record) => record.id === state.selectedId);
|
||||
if (selected) {
|
||||
if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop();
|
||||
records.push(selected);
|
||||
}
|
||||
hits = [];
|
||||
retryUntil = Date.now() + 15000;
|
||||
lane.setActive(state.enabled && records.length > 0);
|
||||
requestPaint();
|
||||
},
|
||||
pick(position) {
|
||||
if (!state.enabled || !position) return null;
|
||||
let closest,
|
||||
distance = Infinity;
|
||||
for (const hit of hits) {
|
||||
const next = (hit.x - position.x) ** 2 + (hit.y - position.y) ** 2;
|
||||
if (next <= hit.radius ** 2 && next <= distance) {
|
||||
closest = hit.id;
|
||||
distance = next;
|
||||
}
|
||||
}
|
||||
return closest || null;
|
||||
},
|
||||
clear() {
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = null;
|
||||
for (const record of records)
|
||||
nativeVisible(native.dataSource?.entities.getById(record.id), true);
|
||||
records = [];
|
||||
hits = [];
|
||||
lane?.setActive(false);
|
||||
},
|
||||
destroy() {
|
||||
this.clear();
|
||||
destroyed = true;
|
||||
removeMapListener?.();
|
||||
removeMapListener = null;
|
||||
lane?.unregister();
|
||||
lane = null;
|
||||
for (const image of images) {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
}
|
||||
images = [];
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { isPointerFree } from '../../../data/inputOwnership.js';
|
||||
import {
|
||||
LAYER_ID,
|
||||
MAX_VIEWPORT_DEGREES,
|
||||
MAX_RENDERED,
|
||||
ALPR_COLOR,
|
||||
ALPR_SELECTED_COLOR,
|
||||
MARKER_ICON_SIZE,
|
||||
@@ -12,15 +11,17 @@ import {
|
||||
MARKER_FLOOR_LIFT_M,
|
||||
MARKER_SCALE_BY_DISTANCE,
|
||||
} from '../policy.js';
|
||||
import { boxContains } from '../model.js';
|
||||
import {
|
||||
alprEntityContext,
|
||||
alprFocusBox,
|
||||
alprLabelModel,
|
||||
alprViewRecords,
|
||||
} from '../presentation.js';
|
||||
import { createAlprFloorResolver } from '../floors.js';
|
||||
import { createAlprOverlay } from './cesiumOverlay.js';
|
||||
import { msg } from '../../../i18n/index.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
alprDisplayId,
|
||||
alprLabelDetails,
|
||||
validAlprGroundHeight,
|
||||
} from '../visuals.js';
|
||||
|
||||
@@ -71,32 +72,8 @@ export function createAlprPresentation({ state, native, services, source }) {
|
||||
}
|
||||
|
||||
/** Records the current view would display (viewport box, nearest first when capped). */
|
||||
function viewRecords(records) {
|
||||
const box = viewportBox(native.viewer);
|
||||
if (!box) return { box, visible: [], capped: false };
|
||||
let visible = records.filter((record) =>
|
||||
boxContains(box, {
|
||||
south: record.latitude,
|
||||
north: record.latitude,
|
||||
west: record.longitude,
|
||||
east: record.longitude,
|
||||
}),
|
||||
);
|
||||
const capped = visible.length > MAX_RENDERED;
|
||||
if (capped) {
|
||||
const lat = (box.south + box.north) / 2;
|
||||
const lon = (box.west + box.east) / 2;
|
||||
const scale = Math.cos((lat * Math.PI) / 180);
|
||||
const distance = (record) =>
|
||||
(record.latitude - lat) ** 2 + ((record.longitude - lon) * scale) ** 2;
|
||||
visible = visible
|
||||
.map((record) => ({ record, d: distance(record) }))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
.slice(0, MAX_RENDERED)
|
||||
.map((item) => item.record);
|
||||
}
|
||||
return { box, visible, capped };
|
||||
}
|
||||
const viewRecords = (records) =>
|
||||
alprViewRecords(records, viewportBox(native.viewer));
|
||||
|
||||
/**
|
||||
* Resolve the floor cells of the records this view will display, waiting at
|
||||
@@ -249,9 +226,6 @@ export function createAlprPresentation({ state, native, services, source }) {
|
||||
return Cesium.Color.fromCssColorString(ALPR_COLOR);
|
||||
}
|
||||
|
||||
// The horizon rectangle is unstable during low-angle orbits and can exclude
|
||||
// the ground point in the center of the screen. Bound nearby coverage around
|
||||
// that point instead; the camera-to-ground range keeps zoom-out queries capped.
|
||||
function viewportBox(viewer) {
|
||||
const camera = viewer?.camera;
|
||||
const canvas = viewer?.scene.canvas;
|
||||
@@ -264,26 +238,10 @@ export function createAlprPresentation({ state, native, services, source }) {
|
||||
viewer.scene.globe.ellipsoid,
|
||||
);
|
||||
if (!focus) return null;
|
||||
const location = Cesium.Cartographic.fromCartesian(focus);
|
||||
const range = Cesium.Cartesian3.distance(camera.positionWC, focus);
|
||||
const radius = Math.max(1000, 2 * range);
|
||||
const latitude = Cesium.Math.toDegrees(location.latitude);
|
||||
const longitude = Cesium.Math.toDegrees(location.longitude);
|
||||
const latSpan = radius / 111000;
|
||||
const lonSpan = latSpan / Math.cos(location.latitude);
|
||||
if (
|
||||
!Number.isFinite(latSpan + lonSpan) ||
|
||||
2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES ||
|
||||
Math.abs(latitude) + latSpan > 90 ||
|
||||
Math.abs(longitude) + lonSpan > 180
|
||||
)
|
||||
return null;
|
||||
return {
|
||||
south: latitude - latSpan,
|
||||
west: longitude - lonSpan,
|
||||
north: latitude + latSpan,
|
||||
east: longitude + lonSpan,
|
||||
};
|
||||
return alprFocusBox(
|
||||
Cesium.Cartographic.fromCartesian(focus),
|
||||
Cesium.Cartesian3.distance(camera.positionWC, focus),
|
||||
);
|
||||
}
|
||||
// Rectangle-only viewers retain the same bounded-area contract.
|
||||
const rectangle = viewer?.camera?.computeViewRectangle(
|
||||
@@ -432,41 +390,14 @@ export function createAlprPresentation({ state, native, services, source }) {
|
||||
// at most once per second, through Cesium's public height APIs.
|
||||
entity.gevAlprDisplayPosition ??= null;
|
||||
entity.gevDisplayPosition = () => entity.gevAlprDisplayPosition;
|
||||
entity.gevLabelModel = {
|
||||
title: alprDisplayId(record),
|
||||
details: alprLabelDetails(record, source),
|
||||
entity.gevLabelModel = alprLabelModel(record, source, {
|
||||
accent: color.toCssColorString(),
|
||||
cardStyle: 'tactical',
|
||||
selected: true,
|
||||
leaderStyle: 'elbow',
|
||||
leaderAnimationMs: 440,
|
||||
leaderAnimationStartedAt: selected ? selectionStartedAt : 0,
|
||||
leaderDrawRatio: 0.68,
|
||||
anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2,
|
||||
anchorRadiusScale: null,
|
||||
};
|
||||
startedAt: selected ? selectionStartedAt : 0,
|
||||
});
|
||||
updateAppearance(entity, selected);
|
||||
registerEntityContext(entity, {
|
||||
id: record.id,
|
||||
layerId: LAYER_ID,
|
||||
...alprEntityContext(record, source),
|
||||
dataSource: native.dataSource,
|
||||
layerName: 'ALPR Cameras',
|
||||
source:
|
||||
source.attribution?.description || source.label || 'Camera source',
|
||||
label: msg('ALPR camera'),
|
||||
latitude: record.latitude,
|
||||
longitude: record.longitude,
|
||||
properties: {
|
||||
operator: record.operator,
|
||||
manufacturer: record.manufacturer,
|
||||
cameraType: record.cameraType,
|
||||
zone: record.zone,
|
||||
directionDeg: record.directionDeg,
|
||||
ref: record.ref,
|
||||
lastVerified: record.lastVerified,
|
||||
osmId: record.osmId,
|
||||
sourceTag: record.source,
|
||||
},
|
||||
});
|
||||
}
|
||||
native.dataSource.entities.resumeEvents();
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import { msg } from '../../../i18n/index.js';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { distanceScale } from '../../../globe/cpuPicks.js';
|
||||
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
|
||||
import { resolvePickId } from '../../../data/pickRegistry.js';
|
||||
import { boxContains, alprCreditMarkup } from '../model.js';
|
||||
import { alprCreditMarkup } from '../model.js';
|
||||
import {
|
||||
alprEntityContext,
|
||||
alprFocusBox,
|
||||
alprLabelModel,
|
||||
alprViewRecords,
|
||||
} from '../presentation.js';
|
||||
import { createAlprFloorResolver } from '../floors.js';
|
||||
import { createAlprNavaraOverlay } from './navaraOverlay.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
alprDisplayId,
|
||||
alprLabelDetails,
|
||||
validAlprGroundHeight,
|
||||
} from '../visuals.js';
|
||||
import {
|
||||
LAYER_ID,
|
||||
MAX_VIEWPORT_DEGREES,
|
||||
MAX_RENDERED,
|
||||
ALPR_COLOR,
|
||||
ALPR_SELECTED_COLOR,
|
||||
@@ -80,58 +82,12 @@ export function createAlprNavaraRenderer(engine, { state, services, source }) {
|
||||
if (!width || !height) return null;
|
||||
const focus = engine.camera.pickEllipsoid({ x: width / 2, y: height / 2 });
|
||||
if (!focus) return null;
|
||||
const location = geo.cartographic.fromCartesian(focus);
|
||||
const radius = Math.max(
|
||||
1000,
|
||||
2 * geo.cartesian3.distance(engine.camera.livePosition, focus),
|
||||
return alprFocusBox(
|
||||
geo.cartographic.fromCartesian(focus),
|
||||
geo.cartesian3.distance(engine.camera.livePosition, focus),
|
||||
);
|
||||
const latitude = geo.math.toDegrees(location.latitude);
|
||||
const longitude = geo.math.toDegrees(location.longitude);
|
||||
const latSpan = radius / 111000;
|
||||
const lonSpan = latSpan / Math.cos(location.latitude);
|
||||
if (
|
||||
!Number.isFinite(latSpan + lonSpan) ||
|
||||
2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES ||
|
||||
Math.abs(latitude) + latSpan > 90 ||
|
||||
Math.abs(longitude) + lonSpan > 180
|
||||
)
|
||||
return null;
|
||||
return {
|
||||
south: latitude - latSpan,
|
||||
west: longitude - lonSpan,
|
||||
north: latitude + latSpan,
|
||||
east: longitude + lonSpan,
|
||||
};
|
||||
}
|
||||
function viewRecords(records) {
|
||||
const box = viewportBox();
|
||||
if (!box) return { visible: [], capped: false };
|
||||
let visible = records.filter((r) =>
|
||||
boxContains(box, {
|
||||
south: r.latitude,
|
||||
north: r.latitude,
|
||||
west: r.longitude,
|
||||
east: r.longitude,
|
||||
}),
|
||||
);
|
||||
const capped = visible.length > MAX_RENDERED;
|
||||
if (capped) {
|
||||
const lat = (box.south + box.north) / 2,
|
||||
lon = (box.west + box.east) / 2;
|
||||
const scale = Math.cos((lat * Math.PI) / 180);
|
||||
visible = visible
|
||||
.map((record) => ({
|
||||
record,
|
||||
d:
|
||||
(record.latitude - lat) ** 2 +
|
||||
((record.longitude - lon) * scale) ** 2,
|
||||
}))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
.slice(0, MAX_RENDERED)
|
||||
.map(({ record }) => record);
|
||||
}
|
||||
return { visible, capped };
|
||||
}
|
||||
const viewRecords = (records) => alprViewRecords(records, viewportBox());
|
||||
function syncMarker(marker) {
|
||||
if (!initialized) return;
|
||||
const position =
|
||||
@@ -321,41 +277,14 @@ export function createAlprNavaraRenderer(engine, { state, services, source }) {
|
||||
const record = marker.record;
|
||||
marker.gevTrackedId = record.id;
|
||||
marker.gevDisplayPosition = () => marker.displayPosition;
|
||||
marker.gevLabelModel = {
|
||||
title: alprDisplayId(record),
|
||||
details: alprLabelDetails(record, source),
|
||||
marker.gevLabelModel = alprLabelModel(record, source, {
|
||||
accent: ALPR_COLOR,
|
||||
cardStyle: 'tactical',
|
||||
selected: true,
|
||||
leaderStyle: 'elbow',
|
||||
leaderAnimationMs: 440,
|
||||
leaderAnimationStartedAt:
|
||||
record.id === state.selectedId ? selectionStartedAt : 0,
|
||||
leaderDrawRatio: 0.68,
|
||||
anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2,
|
||||
anchorRadiusScale: null,
|
||||
};
|
||||
services.context.registerEntityContext(marker, {
|
||||
id: record.id,
|
||||
layerId: LAYER_ID,
|
||||
layerName: 'ALPR Cameras',
|
||||
source:
|
||||
source.attribution?.description || source.label || 'Camera source',
|
||||
label: msg('ALPR camera'),
|
||||
latitude: record.latitude,
|
||||
longitude: record.longitude,
|
||||
properties: {
|
||||
operator: record.operator,
|
||||
manufacturer: record.manufacturer,
|
||||
cameraType: record.cameraType,
|
||||
zone: record.zone,
|
||||
directionDeg: record.directionDeg,
|
||||
ref: record.ref,
|
||||
lastVerified: record.lastVerified,
|
||||
osmId: record.osmId,
|
||||
sourceTag: record.source,
|
||||
},
|
||||
startedAt: record.id === state.selectedId ? selectionStartedAt : 0,
|
||||
});
|
||||
services.context.registerEntityContext(
|
||||
marker,
|
||||
alprEntityContext(record, source),
|
||||
);
|
||||
}
|
||||
function countOnScreen() {
|
||||
const { width, height } = engine.host.size();
|
||||
|
||||
@@ -1,23 +1,5 @@
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
MAX_CANVAS_FRUSTUMS,
|
||||
MARKER_ICON_SIZE,
|
||||
SELECTED_MARKER_ICON_SIZE,
|
||||
MARKER_FLOOR_LIFT_M,
|
||||
ANCHOR_SAMPLES_PER_PAINT,
|
||||
SURFACE_BELOW_FLOOR_M,
|
||||
SURFACE_ABOVE_FLOOR_M,
|
||||
SURFACE_SAMPLES_PER_PAINT,
|
||||
} from '../policy.js';
|
||||
import {
|
||||
MARKER_IMAGE,
|
||||
SELECTED_IMAGE,
|
||||
BRACKETS_IMAGE,
|
||||
directionWedgePositions,
|
||||
markerScale,
|
||||
paintDirectionWedge,
|
||||
validAlprGroundHeight,
|
||||
} from '../visuals.js';
|
||||
import { createAlprOverlayCore } from '../overlay.js';
|
||||
|
||||
/** Canvas artwork over Navara pick sprites, with bounded surface refinement. */
|
||||
export function createAlprNavaraOverlay({
|
||||
@@ -29,396 +11,73 @@ export function createAlprNavaraOverlay({
|
||||
services,
|
||||
onSurfaceChange = () => {},
|
||||
}) {
|
||||
let lane,
|
||||
removeMapListener,
|
||||
retryTimer,
|
||||
retryUntil = 0;
|
||||
let records = [],
|
||||
hits = [],
|
||||
images = [],
|
||||
destroyed = false,
|
||||
lastCamera = null;
|
||||
const requestPaint = () => {
|
||||
if (!destroyed && state.enabled) lane?.requestPaint();
|
||||
};
|
||||
|
||||
function nativeVisible(entity, visible) {
|
||||
if (!entity) return;
|
||||
canvasOwned(entity, !visible);
|
||||
setShown(entity, visible);
|
||||
}
|
||||
|
||||
function canvasOwned(marker, owned) {
|
||||
if (marker.canvasOwned === owned) return;
|
||||
marker.canvasOwned = owned;
|
||||
syncMarker(marker);
|
||||
}
|
||||
|
||||
function setShown(marker, visible) {
|
||||
if (marker.shown === visible) return;
|
||||
marker.shown = visible;
|
||||
syncMarker(marker);
|
||||
}
|
||||
|
||||
function resetAnchors() {
|
||||
for (const entity of markers.values()) {
|
||||
entity.gevAlprCanvasPosition = null;
|
||||
entity.gevAlprWedge = null;
|
||||
entity.displayPosition = null;
|
||||
nativeVisible(entity, true);
|
||||
}
|
||||
state.lastAnchorSampleAt = 0;
|
||||
retryUntil = Date.now() + 15000;
|
||||
requestPaint();
|
||||
}
|
||||
|
||||
function anchorFor(record, entity, budget) {
|
||||
if (entity.gevAlprCanvasPosition) return entity.gevAlprCanvasPosition;
|
||||
const location = geo.cartographic.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
);
|
||||
// A floor-placed marker anchors where its native badge sits; only a
|
||||
// marker still waiting for its floor samples the rendered surface, and
|
||||
// each paint samples a few at most (Navara raycasts the loaded surface).
|
||||
let height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
|
||||
else if (engine.surface.supported) {
|
||||
if (budget.samples <= 0) return null;
|
||||
budget.samples -= 1;
|
||||
try {
|
||||
height = sampleHeight(location);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
}
|
||||
if (!validAlprGroundHeight(height) && engine.surface.terrainHeightSupported)
|
||||
height = engine.surface.terrainHeight(location);
|
||||
if (!validAlprGroundHeight(height)) return null;
|
||||
setAnchor(record, entity, height);
|
||||
return entity.gevAlprCanvasPosition;
|
||||
}
|
||||
|
||||
function floorHeightAt(latitude, longitude) {
|
||||
const floor = services.groundFloor.cachedGroundFloor(latitude, longitude);
|
||||
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
|
||||
}
|
||||
|
||||
function setAnchor(record, entity, height) {
|
||||
entity.gevAlprCanvasPosition = geo.cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
height,
|
||||
);
|
||||
entity.resolved = true;
|
||||
syncMarker(entity);
|
||||
entity.gevAlprWedge = directionWedgePositions(
|
||||
record,
|
||||
height,
|
||||
floorHeightAt,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace floor anchors with the rendered surface under each overlay camera.
|
||||
* Floors come from ~111 m cells, so on a slope a badge could float or sink
|
||||
* by tens of metres. Runs only while the camera is still and tiles have
|
||||
* settled, a few surface samples per paint, and each anchor at most once;
|
||||
* samples far outside the floor prior (a roof or a streaming tile) are
|
||||
* rejected. Returns whether anchors remain to check.
|
||||
*/
|
||||
function refineAnchors(budget) {
|
||||
const camera = engine.camera.pose();
|
||||
const still =
|
||||
lastCamera &&
|
||||
camera.position &&
|
||||
geo.cartesian3.equalsEpsilon(
|
||||
camera.position,
|
||||
lastCamera.position,
|
||||
0,
|
||||
0.05,
|
||||
) &&
|
||||
geo.cartesian3.equalsEpsilon(
|
||||
camera.direction,
|
||||
lastCamera.direction,
|
||||
0,
|
||||
1e-6,
|
||||
);
|
||||
if (camera.position && camera.direction)
|
||||
lastCamera = {
|
||||
position: geo.cartesian3.clone(camera.position),
|
||||
direction: geo.cartesian3.clone(camera.direction),
|
||||
};
|
||||
if (!engine.surface.supported) return false;
|
||||
let pending = false;
|
||||
for (const record of records) {
|
||||
const entity = markers.get(record.id);
|
||||
const anchor = entity?.gevAlprCanvasPosition;
|
||||
if (!anchor || entity.gevAlprSurfaceCheckedFor === anchor) continue;
|
||||
if (!still || !engine.surface.tilesLoaded() || budget.samples <= 0) {
|
||||
pending = true;
|
||||
continue;
|
||||
}
|
||||
budget.samples -= 1;
|
||||
let sample;
|
||||
try {
|
||||
sample = sampleHeight(
|
||||
geo.cartographic.fromDegrees(record.longitude, record.latitude),
|
||||
const location = (record) =>
|
||||
geo.cartographic.fromDegrees(record.longitude, record.latitude);
|
||||
return createAlprOverlayCore({
|
||||
state,
|
||||
services,
|
||||
onSurfaceChange,
|
||||
engine: {
|
||||
marker: (id) => markers.get(id),
|
||||
markers: () => markers.values(),
|
||||
canvasOwned(marker, owned) {
|
||||
if (marker.canvasOwned === owned) return;
|
||||
marker.canvasOwned = owned;
|
||||
syncMarker(marker);
|
||||
},
|
||||
setShown(marker, visible) {
|
||||
if (marker.shown === visible) return;
|
||||
marker.shown = visible;
|
||||
syncMarker(marker);
|
||||
},
|
||||
setDisplayPosition(marker, position) {
|
||||
marker.displayPosition = position;
|
||||
},
|
||||
placeAnchor(marker, record, height) {
|
||||
marker.gevAlprCanvasPosition = geo.cartesian3.fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
height,
|
||||
);
|
||||
} catch {
|
||||
/* streaming tiles */
|
||||
}
|
||||
const current = geo.cartographic.fromCartesian(anchor).height;
|
||||
const floor = services.groundFloor.cachedGroundFloor(
|
||||
record.latitude,
|
||||
record.longitude,
|
||||
);
|
||||
const accepted =
|
||||
validAlprGroundHeight(sample) &&
|
||||
(!validAlprGroundHeight(floor) ||
|
||||
(sample >= floor - SURFACE_BELOW_FLOOR_M &&
|
||||
sample <= floor + SURFACE_ABOVE_FLOOR_M));
|
||||
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
|
||||
setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M);
|
||||
entity.gevAlprSurfaceCheckedFor = entity.gevAlprCanvasPosition;
|
||||
if (entity.id === state.selectedId)
|
||||
entity.displayPosition = entity.gevAlprCanvasPosition;
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
function paint({
|
||||
ctx,
|
||||
width,
|
||||
height,
|
||||
keyhole,
|
||||
viewProjectionMatrix: matrix,
|
||||
}) {
|
||||
hits = [];
|
||||
if (!state.enabled || destroyed) return;
|
||||
// The host already captured the camera and CSS viewport for this frame.
|
||||
// Reuse it for every wedge vertex instead of rereading DOM geometry.
|
||||
const project = ({ x, y, z }) => {
|
||||
const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
|
||||
if (!(w > 0)) return null;
|
||||
return {
|
||||
x:
|
||||
(((matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) / w +
|
||||
1) *
|
||||
width) /
|
||||
2,
|
||||
y:
|
||||
((1 -
|
||||
(matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) / w) *
|
||||
height) /
|
||||
2,
|
||||
};
|
||||
};
|
||||
let unresolved = false;
|
||||
const painted = [];
|
||||
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
|
||||
for (const record of records) {
|
||||
const entity = markers.get(record.id);
|
||||
if (!entity) continue;
|
||||
const selected = record.id === state.selectedId;
|
||||
const image = images[selected ? 1 : 0];
|
||||
if (
|
||||
!image?.complete ||
|
||||
!image.naturalWidth ||
|
||||
(selected && !images[2]?.naturalWidth)
|
||||
) {
|
||||
nativeVisible(entity, true);
|
||||
continue;
|
||||
}
|
||||
const anchor = anchorFor(record, entity, budget);
|
||||
if (!anchor) {
|
||||
nativeVisible(entity, true);
|
||||
unresolved = true;
|
||||
continue;
|
||||
}
|
||||
canvasOwned(entity, true);
|
||||
if (!engine.projector.horizonVisible(anchor)) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const origin = project(anchor);
|
||||
if (!origin) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const alpha =
|
||||
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
|
||||
if (!(alpha > 0)) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
const wedge = entity.gevAlprWedge;
|
||||
if (wedge) {
|
||||
const left = project(wedge[1]);
|
||||
const right = project(wedge[2]);
|
||||
if (
|
||||
left &&
|
||||
right &&
|
||||
Math.max(origin.x, left.x, right.x) >= -3 &&
|
||||
Math.min(origin.x, left.x, right.x) <= width + 3 &&
|
||||
Math.max(origin.y, left.y, right.y) >= -3 &&
|
||||
Math.min(origin.y, left.y, right.y) <= height + 3
|
||||
) {
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
paintDirectionWedge(ctx, origin, left, right, selected);
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
if (
|
||||
origin.x < -60 ||
|
||||
origin.x > width + 60 ||
|
||||
origin.y < -60 ||
|
||||
origin.y > height + 60
|
||||
) {
|
||||
setShown(entity, false);
|
||||
continue;
|
||||
}
|
||||
setShown(entity, true);
|
||||
painted.push({
|
||||
record,
|
||||
origin,
|
||||
selected,
|
||||
image,
|
||||
alpha,
|
||||
scale: markerScale(
|
||||
geo.cartesian3.distance(engine.camera.livePosition, anchor),
|
||||
),
|
||||
});
|
||||
if (selected) entity.displayPosition = anchor;
|
||||
}
|
||||
// Paint all glyphs after the wedges so one camera's cone cannot wash out another.
|
||||
for (const { record, origin, selected, image, alpha, scale } of painted) {
|
||||
const size =
|
||||
(selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE) * scale;
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha;
|
||||
ctx.drawImage(
|
||||
image,
|
||||
origin.x - size / 2,
|
||||
origin.y - size / 2,
|
||||
size,
|
||||
size,
|
||||
);
|
||||
if (selected)
|
||||
ctx.drawImage(
|
||||
images[2],
|
||||
origin.x - size / 2,
|
||||
origin.y - size / 2,
|
||||
size,
|
||||
size,
|
||||
);
|
||||
ctx.restore();
|
||||
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
|
||||
}
|
||||
const refining = refineAnchors({
|
||||
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT),
|
||||
});
|
||||
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
requestPaint();
|
||||
}, 250);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
init() {
|
||||
destroyed = false;
|
||||
removeMapListener = services.overlays?.subscribeMapStack?.((event) => {
|
||||
if (event.detail?.status !== 'ready' || !state.enabled) return;
|
||||
// Same-regime provider changes also invalidate absolute placements.
|
||||
onSurfaceChange();
|
||||
resetAnchors();
|
||||
});
|
||||
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
|
||||
return;
|
||||
lane = services.overlays.registerPaintLane('selected', paint, {
|
||||
id: `alpr-${crypto.randomUUID()}`,
|
||||
active: false,
|
||||
});
|
||||
images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => {
|
||||
const image = new Image();
|
||||
image.onload = requestPaint;
|
||||
image.onerror = requestPaint;
|
||||
image.src = src;
|
||||
return image;
|
||||
});
|
||||
marker.resolved = true;
|
||||
syncMarker(marker);
|
||||
},
|
||||
surfaceSupported: () => engine.surface.supported,
|
||||
// Navara raycasts the loaded surface.
|
||||
sampleHeight: (record) => sampleHeight(location(record)),
|
||||
terrainHeight: (record) =>
|
||||
engine.surface.terrainHeightSupported
|
||||
? engine.surface.terrainHeight(location(record))
|
||||
: undefined,
|
||||
surfaceSettled: () => engine.surface.tilesLoaded(),
|
||||
cameraPose: () => engine.camera.pose(),
|
||||
cameraPosition: () => engine.camera.livePosition,
|
||||
projector: ({ width, height, viewProjectionMatrix: matrix }) => ({
|
||||
horizonVisible: (point) => engine.projector.horizonVisible(point),
|
||||
// The host already captured the camera and CSS viewport for this
|
||||
// frame; reuse it for every wedge vertex instead of rereading DOM
|
||||
// geometry.
|
||||
project({ x, y, z }) {
|
||||
const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
|
||||
if (!(w > 0)) return null;
|
||||
return {
|
||||
x:
|
||||
(((matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) /
|
||||
w +
|
||||
1) *
|
||||
width) /
|
||||
2,
|
||||
y:
|
||||
((1 -
|
||||
(matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) /
|
||||
w) *
|
||||
height) /
|
||||
2,
|
||||
};
|
||||
},
|
||||
}),
|
||||
cullOffscreenWedges: true,
|
||||
createId: () => crypto.randomUUID(),
|
||||
},
|
||||
sync(visible) {
|
||||
if (!lane) return;
|
||||
for (const record of records) nativeVisible(markers.get(record.id), true);
|
||||
const position = engine.camera.livePosition;
|
||||
records = visible
|
||||
.filter(
|
||||
(record) =>
|
||||
Number.isFinite(record.directionDeg) &&
|
||||
record.id !== state.selectedId,
|
||||
)
|
||||
.map((record) => ({
|
||||
record,
|
||||
distance: position
|
||||
? geo.cartesian3.distanceSquared(
|
||||
position,
|
||||
geo.cartesian3.fromDegrees(record.longitude, record.latitude),
|
||||
)
|
||||
: 0,
|
||||
}))
|
||||
.sort((a, b) => a.distance - b.distance)
|
||||
.slice(0, MAX_CANVAS_FRUSTUMS)
|
||||
.map((item) => item.record);
|
||||
const selected = visible.find((record) => record.id === state.selectedId);
|
||||
if (selected) {
|
||||
if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop();
|
||||
records.push(selected);
|
||||
}
|
||||
hits = [];
|
||||
retryUntil = Date.now() + 15000;
|
||||
lane.setActive(state.enabled && records.length > 0);
|
||||
requestPaint();
|
||||
},
|
||||
pick(position) {
|
||||
if (!state.enabled || !position) return null;
|
||||
let closest,
|
||||
distance = Infinity;
|
||||
for (const hit of hits) {
|
||||
const next = (hit.x - position.x) ** 2 + (hit.y - position.y) ** 2;
|
||||
if (next <= hit.radius ** 2 && next <= distance) {
|
||||
closest = hit.id;
|
||||
distance = next;
|
||||
}
|
||||
}
|
||||
return closest || null;
|
||||
},
|
||||
clear() {
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = null;
|
||||
for (const record of records) nativeVisible(markers.get(record.id), true);
|
||||
records = [];
|
||||
hits = [];
|
||||
lane?.setActive(false);
|
||||
},
|
||||
destroy() {
|
||||
this.clear();
|
||||
destroyed = true;
|
||||
removeMapListener?.();
|
||||
removeMapListener = null;
|
||||
lane?.unregister();
|
||||
lane = null;
|
||||
for (const image of images) {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
}
|
||||
images = [];
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -4,15 +4,14 @@
|
||||
// Each surface pixel's distance from the subject along the Earth sets where
|
||||
// it lies within the range, and the same pulse lines, halos and inward band
|
||||
// as Cesium's material are drawn there. Nothing above the surface is touched.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Matrix4, Uniform, Vector3, Vector4 } from 'three';
|
||||
import {
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
|
||||
const KEY = 'gevAwarenessPulses';
|
||||
const registeredViews = new WeakSet();
|
||||
const MEAN_EARTH_RADIUS_M = 6_371_000;
|
||||
|
||||
const fragmentShader = /* glsl */ `
|
||||
@@ -84,82 +83,68 @@ void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
}
|
||||
`;
|
||||
|
||||
function pulseEffectClass(EffectDesc, NavaraEffect) {
|
||||
return class AwarenessPulseEffectDesc extends EffectDesc {
|
||||
static key = KEY;
|
||||
static insertAfter = [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'gevFirmsHeat',
|
||||
'gevFirmsGround',
|
||||
'toneMapping',
|
||||
];
|
||||
static insertBefore = [
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[KEY].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevAwarenessPulses', fragmentShader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
['uCenter', new Uniform(new Vector3(1, 0, 0))],
|
||||
['uRadiusAngle', new Uniform(1)],
|
||||
['uColor', new Uniform(new Vector4())],
|
||||
['uLineColor', new Uniform(new Vector4())],
|
||||
['uHaloColor', new Uniform(new Vector4())],
|
||||
['uRadii', new Uniform(new Vector4())],
|
||||
['uAlphas', new Uniform(new Vector4())],
|
||||
['uDepth', new Uniform(0.35)],
|
||||
['uLineWidth', new Uniform(3)],
|
||||
['uHaloWidth', new Uniform(1)],
|
||||
['uPixelRatio', new Uniform(1)],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
const owner = this.owner,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
const u = this.effect.uniforms;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
u.get('uCenter').value.copy(owner.center);
|
||||
u.get('uRadiusAngle').value = owner.radiusAngle;
|
||||
u.get('uColor').value.fromArray(owner.color);
|
||||
u.get('uLineColor').value.fromArray(owner.lineColor);
|
||||
u.get('uHaloColor').value.fromArray(owner.haloColor);
|
||||
u.get('uRadii').value.fromArray(owner.radii);
|
||||
u.get('uAlphas').value.fromArray(owner.alphas);
|
||||
u.get('uDepth').value = owner.depth;
|
||||
u.get('uLineWidth').value = owner.lineWidth;
|
||||
u.get('uHaloWidth').value = owner.haloWidth;
|
||||
// Buffer pixels per CSS pixel: the pass can run above the canvas's
|
||||
// CSS size, and the pulse widths are in CSS pixels.
|
||||
const cssWidth = owner.cssWidth();
|
||||
u.get('uPixelRatio').value =
|
||||
cssWidth > 0
|
||||
? this.ctx.getInputBuffer().width / cssWidth
|
||||
: globalThis.devicePixelRatio || 1;
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
const pulseEffect = defineGroundEffect({
|
||||
key: KEY,
|
||||
name: 'GevAwarenessPulses',
|
||||
fragmentShader,
|
||||
insertAfter: [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'gevFirmsHeat',
|
||||
'gevFirmsGround',
|
||||
'toneMapping',
|
||||
],
|
||||
insertBefore: [
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
['uCenter', new Uniform(new Vector3(1, 0, 0))],
|
||||
['uRadiusAngle', new Uniform(1)],
|
||||
['uColor', new Uniform(new Vector4())],
|
||||
['uLineColor', new Uniform(new Vector4())],
|
||||
['uHaloColor', new Uniform(new Vector4())],
|
||||
['uRadii', new Uniform(new Vector4())],
|
||||
['uAlphas', new Uniform(new Vector4())],
|
||||
['uDepth', new Uniform(0.35)],
|
||||
['uLineWidth', new Uniform(3)],
|
||||
['uHaloWidth', new Uniform(1)],
|
||||
['uPixelRatio', new Uniform(1)],
|
||||
],
|
||||
update() {
|
||||
const owner = this.owner,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
const u = this.effect.uniforms;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
u.get('uCenter').value.copy(owner.center);
|
||||
u.get('uRadiusAngle').value = owner.radiusAngle;
|
||||
u.get('uColor').value.fromArray(owner.color);
|
||||
u.get('uLineColor').value.fromArray(owner.lineColor);
|
||||
u.get('uHaloColor').value.fromArray(owner.haloColor);
|
||||
u.get('uRadii').value.fromArray(owner.radii);
|
||||
u.get('uAlphas').value.fromArray(owner.alphas);
|
||||
u.get('uDepth').value = owner.depth;
|
||||
u.get('uLineWidth').value = owner.lineWidth;
|
||||
u.get('uHaloWidth').value = owner.haloWidth;
|
||||
// Buffer pixels per CSS pixel: the pass can run above the canvas's
|
||||
// CSS size, and the pulse widths are in CSS pixels.
|
||||
const cssWidth = owner.cssWidth();
|
||||
u.get('uPixelRatio').value =
|
||||
cssWidth > 0
|
||||
? this.ctx.getInputBuffer().width / cssWidth
|
||||
: globalThis.devicePixelRatio || 1;
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The pulse disc on one Navara view around `center` (Earth-fixed metres):
|
||||
@@ -172,10 +157,7 @@ export function createAwarenessPulseDisc(
|
||||
{ view, EffectDesc, NavaraEffect },
|
||||
{ center, radiusM, color, lineColor, haloColor, depth, lineWidth, haloWidth },
|
||||
) {
|
||||
if (!registeredViews.has(view)) {
|
||||
view.registerEffect(KEY, pulseEffectClass(EffectDesc, NavaraEffect));
|
||||
registeredViews.add(view);
|
||||
}
|
||||
pulseEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
const owner = {
|
||||
cssWidth: () => engine.host?.canvas?.clientWidth ?? 0,
|
||||
center: new Vector3(),
|
||||
|
||||
@@ -2,22 +2,12 @@ import * as Cesium from 'cesium';
|
||||
import {
|
||||
COLOR_NEUTRAL,
|
||||
POINT_HEIGHT_OFFSET_M,
|
||||
MAX_TOTAL_POINTS,
|
||||
COLOR_OUTLINE,
|
||||
} from '../../policy.js';
|
||||
import {
|
||||
capacityToPixelSize,
|
||||
resolveCapacity,
|
||||
statusToColor,
|
||||
} from '../../presentation.js';
|
||||
import { createStationPoints } from '../../stationPoints.js';
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
services,
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { governorRequestRender } = services.render;
|
||||
export function createRendering(context) {
|
||||
const { state: layerState } = context;
|
||||
|
||||
/**
|
||||
* Create a Cartesian3 position for a station, terrain-clamped when possible.
|
||||
@@ -44,59 +34,13 @@ export function createRendering({
|
||||
return Cesium.Cartesian3.fromDegrees(lon, lat, height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create the runtime tracking object for a city.
|
||||
* @param {string} cityId - City identifier.
|
||||
* @returns {{ stationKeys: Set<string> }} City runtime object.
|
||||
*/
|
||||
|
||||
function ensureCityRuntime(cityId) {
|
||||
if (layerState._cityRuntime.has(cityId))
|
||||
return layerState._cityRuntime.get(cityId);
|
||||
const runtime = { stationKeys: new Set() };
|
||||
layerState._cityRuntime.set(cityId, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure point primitives exist for all stations in a city.
|
||||
* Creates new points for stations not yet rendered; skips existing ones.
|
||||
* Respects the MAX_TOTAL_POINTS global cap to prevent GPU overload.
|
||||
* @param {string} cityId - City identifier.
|
||||
* @param {Map<string, Object>} stationMap - Parsed station info map for the city.
|
||||
*/
|
||||
|
||||
function ensureCityPoints(cityId, stationMap) {
|
||||
// Deferred debounce/fetch completions mutate point primitives after the
|
||||
// camera settled — each commit needs one frame in idle mode. (perf wave 2 fix)
|
||||
governorRequestRender('bikeshare-points');
|
||||
const runtime = ensureCityRuntime(cityId);
|
||||
|
||||
for (const station of stationMap.values()) {
|
||||
const key = parts.model.stationKey(cityId, station.stationId);
|
||||
if (layerState._stationRenderMap.has(key)) {
|
||||
runtime.stationKeys.add(key);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Enforce global point cap
|
||||
if (layerState._stationRenderMap.size >= MAX_TOTAL_POINTS) {
|
||||
if (!layerState._limitWarned) {
|
||||
layerState._limitWarned = true;
|
||||
console.warn(
|
||||
`[Data:Bikeshare] Point cap reached (${MAX_TOTAL_POINTS}).`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const position = createStationPosition(station);
|
||||
if (!position) continue;
|
||||
|
||||
// Add a point primitive with distance-based scale and translucency falloff
|
||||
const point = layerState._pointCollection.add({
|
||||
return createStationPoints(context, {
|
||||
position: createStationPosition,
|
||||
// A point primitive with distance-based scale and translucency falloff
|
||||
create: (record, { position, pixelSize }) =>
|
||||
layerState._pointCollection.add({
|
||||
position,
|
||||
pixelSize: capacityToPixelSize(station.capacity),
|
||||
pixelSize,
|
||||
color: COLOR_NEUTRAL,
|
||||
outlineColor: COLOR_OUTLINE,
|
||||
outlineWidth: 1,
|
||||
@@ -108,113 +52,8 @@ export function createRendering({
|
||||
0.15,
|
||||
),
|
||||
disableDepthTestDistance: 2500,
|
||||
id: key,
|
||||
});
|
||||
|
||||
layerState._stationRenderMap.set(key, {
|
||||
key,
|
||||
cityId,
|
||||
stationId: station.stationId,
|
||||
stationName: station.name,
|
||||
point,
|
||||
capacity: parts.model.toNonNegativeInteger(station.capacity),
|
||||
publishedCapacity: parts.model.toNonNegativeInteger(station.capacity),
|
||||
bikesAvailable: null,
|
||||
docksAvailable: null,
|
||||
isInstalled: station.isInstalled,
|
||||
isRenting: station.isRenting,
|
||||
isReturning: station.isReturning,
|
||||
});
|
||||
|
||||
runtime.stationKeys.add(key);
|
||||
}
|
||||
|
||||
layerState._count = layerState._stationRenderMap.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all rendered point primitives for a city and clean up runtime state.
|
||||
* Also clears any active selection if it belongs to this city.
|
||||
* @param {string} cityId - City identifier to remove.
|
||||
*/
|
||||
|
||||
function removeCityPoints(cityId) {
|
||||
const runtime = layerState._cityRuntime.get(cityId);
|
||||
if (!runtime) return;
|
||||
|
||||
// Clear selection if it belongs to the city being removed
|
||||
if (
|
||||
layerState._selectedKey &&
|
||||
runtime.stationKeys.has(layerState._selectedKey)
|
||||
) {
|
||||
parts.selection._clearSelection();
|
||||
}
|
||||
|
||||
for (const key of runtime.stationKeys) {
|
||||
const record = layerState._stationRenderMap.get(key);
|
||||
if (!record) continue;
|
||||
layerState._pointCollection.remove(record.point);
|
||||
layerState._stationRenderMap.delete(key);
|
||||
}
|
||||
|
||||
layerState._cityRuntime.delete(cityId);
|
||||
layerState._count = layerState._stationRenderMap.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply real-time status data to rendered station points for a city.
|
||||
* Updates each point's color (availability ratio) and pixel size (capacity),
|
||||
* and refreshes the render record's cached availability fields.
|
||||
* @param {string} cityId - City identifier.
|
||||
* @param {Map<string, Object>} statusMap - Parsed station status map.
|
||||
*/
|
||||
|
||||
function applyStatusToPoints(cityId, statusMap) {
|
||||
governorRequestRender('bikeshare-status');
|
||||
const runtime = layerState._cityRuntime.get(cityId);
|
||||
if (!runtime) return;
|
||||
|
||||
for (const key of runtime.stationKeys) {
|
||||
const record = layerState._stationRenderMap.get(key);
|
||||
if (!record) continue;
|
||||
|
||||
const status = statusMap.get(record.stationId) || null;
|
||||
// Resolve from the published capacity, not last poll's derived value.
|
||||
const capacity = resolveCapacity(
|
||||
parts.model,
|
||||
record.publishedCapacity,
|
||||
status,
|
||||
);
|
||||
record.capacity = capacity;
|
||||
|
||||
record.bikesAvailable = parts.model.toNonNegativeInteger(
|
||||
status?.bikesAvailable,
|
||||
);
|
||||
record.docksAvailable = parts.model.toNonNegativeInteger(
|
||||
status?.docksAvailable,
|
||||
);
|
||||
record.isInstalled = parts.model.normalizeGbfsBool(
|
||||
status?.isInstalled,
|
||||
true,
|
||||
);
|
||||
record.isRenting = parts.model.normalizeGbfsBool(status?.isRenting, true);
|
||||
record.isReturning = parts.model.normalizeGbfsBool(
|
||||
status?.isReturning,
|
||||
true,
|
||||
);
|
||||
|
||||
// Update visual properties based on current status
|
||||
record.point.pixelSize = capacityToPixelSize(capacity);
|
||||
record.point.color = statusToColor(parts.model, status, capacity);
|
||||
}
|
||||
parts.selection.refreshSelectedCard();
|
||||
}
|
||||
return {
|
||||
capacityToPixelSize,
|
||||
createStationPosition,
|
||||
ensureCityRuntime,
|
||||
ensureCityPoints,
|
||||
removeCityPoints,
|
||||
applyStatusToPoints,
|
||||
};
|
||||
id: record.key,
|
||||
}),
|
||||
remove: (record) => layerState._pointCollection.remove(record.point),
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from '../../../../data/inputOwnership.js';
|
||||
import {
|
||||
buildBikeshareSelectionLabel,
|
||||
createBikeshareSelectedOverlayEntry,
|
||||
} from '../../selectionModel.js';
|
||||
import { createBikeshareSelectedOverlayEntry } from '../../selectionModel.js';
|
||||
import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
@@ -140,8 +137,6 @@ export function createSelection({
|
||||
}
|
||||
return {
|
||||
refreshSelectedCard,
|
||||
buildSelectionLabel: buildBikeshareSelectionLabel,
|
||||
createBikeshareSelectedOverlayEntry,
|
||||
_clearSelection,
|
||||
_selectStation,
|
||||
_installClickHandler,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
|
||||
import { CYAN } from '../../shared/color.js';
|
||||
import { viewRectangleCenter } from '../../shared/viewRectangle.js';
|
||||
import { createViewport } from '../viewport.js';
|
||||
import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
@@ -10,15 +11,9 @@ import {
|
||||
MAX_TOTAL_POINTS,
|
||||
POINT_HEIGHT_OFFSET_M,
|
||||
} from '../policy.js';
|
||||
import {
|
||||
capacityToPixelSize,
|
||||
resolveCapacity,
|
||||
statusToColor,
|
||||
} from '../presentation.js';
|
||||
import {
|
||||
buildBikeshareSelectionLabel,
|
||||
createBikeshareSelectedOverlayEntry,
|
||||
} from '../selectionModel.js';
|
||||
import { capacityToPixelSize } from '../presentation.js';
|
||||
import { createBikeshareSelectedOverlayEntry } from '../selectionModel.js';
|
||||
import { createStationPoints } from '../stationPoints.js';
|
||||
|
||||
const LAYER_ID = 'bikeshare';
|
||||
|
||||
@@ -36,8 +31,6 @@ function pointSet(engine, { id, capacity, order, depthTest, point }) {
|
||||
}
|
||||
|
||||
export function createBikeshareNavaraRenderer(engine, context) {
|
||||
if (!engine?.movers || !engine?.camera?.viewRectangle)
|
||||
throw new TypeError('Bikeshare requires a Navara globe engine');
|
||||
const { state, services, parts } = context;
|
||||
const normalSet = pointSet(engine, {
|
||||
id: LAYER_ID,
|
||||
@@ -85,13 +78,8 @@ export function createBikeshareNavaraRenderer(engine, context) {
|
||||
};
|
||||
const request = (reason) => services.render.governorRequestRender(reason);
|
||||
|
||||
const rendering = {
|
||||
resolveCapacity: (capacity, status) =>
|
||||
resolveCapacity(parts.model, capacity, status),
|
||||
capacityToPixelSize,
|
||||
statusToColor: (status, capacity) =>
|
||||
statusToColor(parts.model, status, capacity),
|
||||
createStationPosition(station) {
|
||||
const rendering = createStationPoints(context, {
|
||||
position(station) {
|
||||
const lon = Number(station?.lon);
|
||||
const lat = Number(station?.lat);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
||||
@@ -105,122 +93,22 @@ export function createBikeshareNavaraRenderer(engine, context) {
|
||||
(Number.isFinite(sampled) ? sampled : 0) + POINT_HEIGHT_OFFSET_M;
|
||||
return geo.cartesian3.fromDegrees(lon, lat, height);
|
||||
},
|
||||
ensureCityRuntime(cityId) {
|
||||
let runtime = state._cityRuntime.get(cityId);
|
||||
if (!runtime) {
|
||||
runtime = { stationKeys: new Set() };
|
||||
state._cityRuntime.set(cityId, runtime);
|
||||
}
|
||||
return runtime;
|
||||
create(record, { position, pixelSize }) {
|
||||
record.index = state._stationRenderMap.size;
|
||||
record.point = { position, pixelSize, color: COLOR_NEUTRAL, show: true };
|
||||
syncPoint(record);
|
||||
return record.point;
|
||||
},
|
||||
ensureCityPoints(cityId, stationMap) {
|
||||
request('bikeshare-points');
|
||||
const runtime = this.ensureCityRuntime(cityId);
|
||||
for (const station of stationMap.values()) {
|
||||
const key = parts.model.stationKey(cityId, station.stationId);
|
||||
if (state._stationRenderMap.has(key)) {
|
||||
runtime.stationKeys.add(key);
|
||||
continue;
|
||||
}
|
||||
if (state._stationRenderMap.size >= MAX_TOTAL_POINTS) {
|
||||
if (!state._limitWarned) {
|
||||
state._limitWarned = true;
|
||||
console.warn(
|
||||
`[Data:Bikeshare] Point cap reached (${MAX_TOTAL_POINTS}).`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
const position = this.createStationPosition(station);
|
||||
if (!position) continue;
|
||||
const record = {
|
||||
key,
|
||||
cityId,
|
||||
stationId: station.stationId,
|
||||
stationName: station.name,
|
||||
index: state._stationRenderMap.size,
|
||||
point: {
|
||||
position,
|
||||
pixelSize: capacityToPixelSize(station.capacity),
|
||||
color: COLOR_NEUTRAL,
|
||||
show: true,
|
||||
},
|
||||
capacity: parts.model.toNonNegativeInteger(station.capacity),
|
||||
publishedCapacity: parts.model.toNonNegativeInteger(station.capacity),
|
||||
bikesAvailable: null,
|
||||
docksAvailable: null,
|
||||
isInstalled: station.isInstalled,
|
||||
isRenting: station.isRenting,
|
||||
isReturning: station.isReturning,
|
||||
};
|
||||
state._stationRenderMap.set(key, record);
|
||||
runtime.stationKeys.add(key);
|
||||
syncPoint(record);
|
||||
}
|
||||
afterAdd() {
|
||||
normalSet.setCount(state._stationRenderMap.size);
|
||||
normalSet.commit();
|
||||
state._count = state._stationRenderMap.size;
|
||||
},
|
||||
removeCityPoints(cityId) {
|
||||
const runtime = state._cityRuntime.get(cityId);
|
||||
if (!runtime) return;
|
||||
if (state._selectedKey && runtime.stationKeys.has(state._selectedKey))
|
||||
selection._clearSelection();
|
||||
for (const key of runtime.stationKeys)
|
||||
state._stationRenderMap.delete(key);
|
||||
state._cityRuntime.delete(cityId);
|
||||
resetNormalSet();
|
||||
},
|
||||
applyStatusToPoints(cityId, statusMap) {
|
||||
request('bikeshare-status');
|
||||
const runtime = state._cityRuntime.get(cityId);
|
||||
if (!runtime) return;
|
||||
for (const key of runtime.stationKeys) {
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record) continue;
|
||||
const status = statusMap.get(record.stationId) || null;
|
||||
// Resolve from the published capacity, not last poll's derived value.
|
||||
record.capacity = resolveCapacity(
|
||||
parts.model,
|
||||
record.publishedCapacity,
|
||||
status,
|
||||
);
|
||||
record.bikesAvailable = parts.model.toNonNegativeInteger(
|
||||
status?.bikesAvailable,
|
||||
);
|
||||
record.docksAvailable = parts.model.toNonNegativeInteger(
|
||||
status?.docksAvailable,
|
||||
);
|
||||
record.isInstalled = parts.model.normalizeGbfsBool(
|
||||
status?.isInstalled,
|
||||
true,
|
||||
);
|
||||
record.isRenting = parts.model.normalizeGbfsBool(
|
||||
status?.isRenting,
|
||||
true,
|
||||
);
|
||||
record.isReturning = parts.model.normalizeGbfsBool(
|
||||
status?.isReturning,
|
||||
true,
|
||||
);
|
||||
record.point.pixelSize = capacityToPixelSize(record.capacity);
|
||||
record.point.color = statusToColor(
|
||||
parts.model,
|
||||
status,
|
||||
record.capacity,
|
||||
);
|
||||
syncPoint(record);
|
||||
}
|
||||
normalSet.commit();
|
||||
selection.refreshSelectedCard();
|
||||
},
|
||||
};
|
||||
afterRemove: resetNormalSet,
|
||||
update: syncPoint,
|
||||
afterUpdate: () => normalSet.commit(),
|
||||
});
|
||||
|
||||
const selection = {
|
||||
buildSelectionLabel(record) {
|
||||
return buildBikeshareSelectionLabel(record);
|
||||
},
|
||||
createBikeshareSelectedOverlayEntry,
|
||||
refreshSelectedCard() {
|
||||
const key = state._selectedKey;
|
||||
const record = state._stationRenderMap.get(key);
|
||||
@@ -278,10 +166,6 @@ export function createBikeshareNavaraRenderer(engine, context) {
|
||||
}
|
||||
request('bikeshare-selection');
|
||||
},
|
||||
_installClickHandler() {},
|
||||
_onKeyDown(event) {
|
||||
if (event.key === 'Escape' && state._selectedKey) this._clearSelection();
|
||||
},
|
||||
};
|
||||
|
||||
const viewport = createViewport({
|
||||
@@ -291,12 +175,9 @@ export function createBikeshareNavaraRenderer(engine, context) {
|
||||
getCameraCenterLatLon() {
|
||||
const rect = engine.camera.viewRectangle();
|
||||
if (rect) {
|
||||
let east = rect.east;
|
||||
if (east < rect.west) east += Math.PI * 2;
|
||||
let longitude = (rect.west + east) / 2;
|
||||
if (longitude > Math.PI) longitude -= Math.PI * 2;
|
||||
const { latitude, longitude } = viewRectangleCenter(rect);
|
||||
return {
|
||||
lat: geo.math.toDegrees((rect.south + rect.north) / 2),
|
||||
lat: geo.math.toDegrees(latitude),
|
||||
lon: geo.math.toDegrees(longitude),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
} from './policy.js';
|
||||
|
||||
export function buildBikeshareSelectionLabel(record) {
|
||||
function buildBikeshareSelectionLabel(record) {
|
||||
const stationName = String(record?.stationName || '').trim();
|
||||
const stationLabel =
|
||||
stationName ||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { MAX_TOTAL_POINTS } from './policy.js';
|
||||
import {
|
||||
capacityToPixelSize,
|
||||
resolveCapacity,
|
||||
statusToColor,
|
||||
} from './presentation.js';
|
||||
|
||||
/**
|
||||
* The station records behind the rendered points, per city, on either
|
||||
* engine. `points` draws them:
|
||||
* - `position(station)`: the station's world position, or null;
|
||||
* - `create(record, { position, pixelSize })`: the record's point;
|
||||
* - `remove(record)`, `update(record)`: one point removed or restyled;
|
||||
* - `afterAdd()`, `afterRemove()`, `afterUpdate()`: a batch is done.
|
||||
* Every member but `position` and `create` is optional.
|
||||
*/
|
||||
export function createStationPoints({ state, services, parts }, points) {
|
||||
/**
|
||||
* Get or create the runtime tracking object for a city.
|
||||
* @param {string} cityId - City identifier.
|
||||
* @returns {{ stationKeys: Set<string> }} City runtime object.
|
||||
*/
|
||||
function ensureCityRuntime(cityId) {
|
||||
if (state._cityRuntime.has(cityId)) return state._cityRuntime.get(cityId);
|
||||
const runtime = { stationKeys: new Set() };
|
||||
state._cityRuntime.set(cityId, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure points exist for all stations in a city.
|
||||
* Creates new points for stations not yet rendered; skips existing ones.
|
||||
* Respects the MAX_TOTAL_POINTS global cap to prevent GPU overload.
|
||||
* @param {string} cityId - City identifier.
|
||||
* @param {Map<string, Object>} stationMap - Parsed station info map for the city.
|
||||
*/
|
||||
function ensureCityPoints(cityId, stationMap) {
|
||||
// Deferred debounce/fetch completions change points after the camera
|
||||
// settled: each commit needs one frame in idle mode.
|
||||
services.render.governorRequestRender('bikeshare-points');
|
||||
const runtime = ensureCityRuntime(cityId);
|
||||
|
||||
for (const station of stationMap.values()) {
|
||||
const key = parts.model.stationKey(cityId, station.stationId);
|
||||
if (state._stationRenderMap.has(key)) {
|
||||
runtime.stationKeys.add(key);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Enforce global point cap
|
||||
if (state._stationRenderMap.size >= MAX_TOTAL_POINTS) {
|
||||
if (!state._limitWarned) {
|
||||
state._limitWarned = true;
|
||||
console.warn(
|
||||
`[Data:Bikeshare] Point cap reached (${MAX_TOTAL_POINTS}).`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const position = points.position(station);
|
||||
if (!position) continue;
|
||||
|
||||
const record = {
|
||||
key,
|
||||
cityId,
|
||||
stationId: station.stationId,
|
||||
stationName: station.name,
|
||||
point: null,
|
||||
capacity: parts.model.toNonNegativeInteger(station.capacity),
|
||||
publishedCapacity: parts.model.toNonNegativeInteger(station.capacity),
|
||||
bikesAvailable: null,
|
||||
docksAvailable: null,
|
||||
isInstalled: station.isInstalled,
|
||||
isRenting: station.isRenting,
|
||||
isReturning: station.isReturning,
|
||||
};
|
||||
record.point = points.create(record, {
|
||||
position,
|
||||
pixelSize: capacityToPixelSize(station.capacity),
|
||||
});
|
||||
state._stationRenderMap.set(key, record);
|
||||
runtime.stationKeys.add(key);
|
||||
}
|
||||
|
||||
points.afterAdd?.();
|
||||
state._count = state._stationRenderMap.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all rendered points for a city and clean up runtime state.
|
||||
* Also clears any active selection if it belongs to this city.
|
||||
* @param {string} cityId - City identifier to remove.
|
||||
*/
|
||||
function removeCityPoints(cityId) {
|
||||
const runtime = state._cityRuntime.get(cityId);
|
||||
if (!runtime) return;
|
||||
|
||||
// Clear selection if it belongs to the city being removed
|
||||
if (state._selectedKey && runtime.stationKeys.has(state._selectedKey))
|
||||
parts.selection._clearSelection();
|
||||
|
||||
for (const key of runtime.stationKeys) {
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record) continue;
|
||||
points.remove?.(record);
|
||||
state._stationRenderMap.delete(key);
|
||||
}
|
||||
|
||||
state._cityRuntime.delete(cityId);
|
||||
points.afterRemove?.();
|
||||
state._count = state._stationRenderMap.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply real-time status data to rendered station points for a city.
|
||||
* Updates each point's color (availability ratio) and pixel size (capacity),
|
||||
* and refreshes the render record's cached availability fields.
|
||||
* @param {string} cityId - City identifier.
|
||||
* @param {Map<string, Object>} statusMap - Parsed station status map.
|
||||
*/
|
||||
function applyStatusToPoints(cityId, statusMap) {
|
||||
services.render.governorRequestRender('bikeshare-status');
|
||||
const runtime = state._cityRuntime.get(cityId);
|
||||
if (!runtime) return;
|
||||
|
||||
for (const key of runtime.stationKeys) {
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record) continue;
|
||||
|
||||
const status = statusMap.get(record.stationId) || null;
|
||||
// Resolve from the published capacity, not last poll's derived value.
|
||||
const capacity = resolveCapacity(
|
||||
parts.model,
|
||||
record.publishedCapacity,
|
||||
status,
|
||||
);
|
||||
record.capacity = capacity;
|
||||
|
||||
record.bikesAvailable = parts.model.toNonNegativeInteger(
|
||||
status?.bikesAvailable,
|
||||
);
|
||||
record.docksAvailable = parts.model.toNonNegativeInteger(
|
||||
status?.docksAvailable,
|
||||
);
|
||||
record.isInstalled = parts.model.normalizeGbfsBool(
|
||||
status?.isInstalled,
|
||||
true,
|
||||
);
|
||||
record.isRenting = parts.model.normalizeGbfsBool(status?.isRenting, true);
|
||||
record.isReturning = parts.model.normalizeGbfsBool(
|
||||
status?.isReturning,
|
||||
true,
|
||||
);
|
||||
|
||||
// Update visual properties based on current status
|
||||
record.point.pixelSize = capacityToPixelSize(capacity);
|
||||
record.point.color = statusToColor(parts.model, status, capacity);
|
||||
points.update?.(record);
|
||||
}
|
||||
points.afterUpdate?.();
|
||||
parts.selection.refreshSelectedCard();
|
||||
}
|
||||
|
||||
return { ensureCityPoints, removeCityPoints, applyStatusToPoints };
|
||||
}
|
||||
@@ -126,7 +126,7 @@ export function createLifecycle({
|
||||
layerState._lastAppliedRegime = null;
|
||||
}
|
||||
function bindScene(viewer, options) {
|
||||
// Task 5: track the surface regime the initial geometry was computed for
|
||||
// Track the surface regime the initial geometry was computed for
|
||||
// and listen for map-stack changes (main.js re-dispatches
|
||||
// MapStackController.onChange as this CustomEvent). The handler compares
|
||||
// regimes itself, so 'switching'/'error' emissions and same-regime stack
|
||||
@@ -140,7 +140,7 @@ export function createLifecycle({
|
||||
);
|
||||
}
|
||||
|
||||
// Field-test fix (2026-07-06): horizon-cull on camera settle (pairs with
|
||||
// Horizon-cull on camera settle (pairs with
|
||||
// the billboards' always-on-top depth setting) + one initial pass so the
|
||||
// first paint is already culled.
|
||||
if (!layerState._horizonCullListener) {
|
||||
@@ -187,7 +187,7 @@ export function createLifecycle({
|
||||
// remain eligible for true empty-space deselection.
|
||||
const pickedId = resolvePickId(picked);
|
||||
if (pickedId !== null) return;
|
||||
// Item A (owner round 2): the scene pick found no camera — try the
|
||||
// The scene pick found no camera — try the
|
||||
// painted ambient cards. The cards canvas is pointer-events:none (this
|
||||
// handler owns the events), so a click landing on a card's rect selects
|
||||
// its camera exactly like a click on the icon. Cesium click positions
|
||||
@@ -309,7 +309,7 @@ export function createLifecycle({
|
||||
parts.model.ensureCameraPose(camera);
|
||||
}
|
||||
|
||||
// Task 5 (height-datum fix): batch ALL camera coords through the Re:Earth
|
||||
// Batch ALL camera coords through the Re:Earth
|
||||
// ellipsoidal ground-prior resolver (network-cached — NOT a scene query;
|
||||
// the catalog's orthometric groundElevationM feeds the geoid fallback
|
||||
// chain). Bounded wait: a warm proxy cache resolves in milliseconds, so
|
||||
@@ -352,7 +352,7 @@ export function createLifecycle({
|
||||
billboard,
|
||||
coverageEntities: [],
|
||||
projection: null,
|
||||
// Task 5 (height-datum fix): regime-aware ground resolution state.
|
||||
// Regime-aware ground resolution state.
|
||||
// groundPrior — { ellipsoid, source } from the Re:Earth batch
|
||||
// (null until a late batch lands). The prior applies in EVERY
|
||||
// regime and is the terrain-globe resolution outright.
|
||||
@@ -397,7 +397,7 @@ export function createLifecycle({
|
||||
layerState._activeCameraId = layerState._records[0].camera.id;
|
||||
}
|
||||
|
||||
// Task 5: if the prior batch lost init's bounded race, apply it post-hoc
|
||||
// If the prior batch lost init's bounded race, apply it post-hoc
|
||||
// when it lands (pure recomputes — applyLateGroundPriors guards against
|
||||
// a torn-down/re-inited catalog).
|
||||
if (!priors) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import { createZonesCesiumRenderer } from '../shared/render/cesiumZones.js';
|
||||
@@ -12,11 +11,6 @@ export { normalizeDroneAirspaceSnapshot } from './records.js';
|
||||
export { createDroneAirspaceSource } from './source.js';
|
||||
export * from './cards.js';
|
||||
|
||||
/** Fill/line color for a zone by TYPE_CODE. */
|
||||
export function droneAirspaceColor(typeCode) {
|
||||
return Cesium.Color.fromCssColorString(droneAirspaceAccent(typeCode));
|
||||
}
|
||||
|
||||
/** The zones on a Cesium globe (the default renderer). */
|
||||
export function createDroneAirspaceCesiumRenderer({
|
||||
viewer,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Native earthquake entities, moved from the layer without changing its
|
||||
// static CLAMP_TO_GROUND ellipses, properties or analyst snapshot semantics.
|
||||
// Native earthquake entities: static CLAMP_TO_GROUND ellipses with the
|
||||
// layer's properties and analyst snapshot semantics.
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export function createEarthquakesCesiumRenderer(_engine, { viewer }) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Classify the real visible terrain/Google-tiles surface in a public
|
||||
// Navara post-effect. Native ground colour blends in display space; doing
|
||||
// it explicitly preserves translucent colours and overlap order.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Uniform } from 'three';
|
||||
import {
|
||||
createGroundTexture as texture,
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
DISC_EDGES,
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
} from './navaraGeometry.js';
|
||||
import { createDiscGrid, GRID_COLS, GRID_ROWS } from './navaraGrid.js';
|
||||
const KEY = 'gevEarthquakeGround';
|
||||
const registeredViews = new WeakSet();
|
||||
const fragmentShader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth;
|
||||
uniform sampler2D tSurfaceDepth;
|
||||
@@ -196,81 +195,61 @@ function buildState(discs) {
|
||||
return state;
|
||||
}
|
||||
|
||||
function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
return class GroundEffectDesc extends EffectDesc {
|
||||
static key = KEY;
|
||||
static insertAfter = [
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'toneMapping',
|
||||
const groundEffect = defineGroundEffect({
|
||||
key: KEY,
|
||||
name: 'GevEarthquakeGround',
|
||||
fragmentShader,
|
||||
insertAfter: [
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'toneMapping',
|
||||
],
|
||||
insertBefore: [
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['tEdges', new Uniform(null)],
|
||||
['tFrames', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uEdgeSize', new Uniform([1, 1])],
|
||||
['uFrameSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
],
|
||||
update() {
|
||||
const state = this.owner.state,
|
||||
camera = this.view.camera.raw,
|
||||
mrt = this.find('mrt');
|
||||
if (!this.effect || !camera || !state) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, mrt);
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tEdges').value = state.edges.texture;
|
||||
u.get('uEdgeSize').value = [state.edges.width, state.edges.height];
|
||||
u.get('tFrames').value = state.packed.texture;
|
||||
u.get('uFrameSize').value = [state.packed.width, state.packed.height];
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('tCandidates').value = state.candidates.texture;
|
||||
u.get('uCandidateSize').value = [
|
||||
state.candidates.width,
|
||||
state.candidates.height,
|
||||
];
|
||||
static insertBefore = [
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, ctx, config) {
|
||||
super(view, ctx, config);
|
||||
this.owner = config[KEY].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevEarthquakeGround', fragmentShader, {
|
||||
// Keep a separate pass: inputColor is the already tone-mapped frame.
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['tEdges', new Uniform(null)],
|
||||
['tFrames', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uEdgeSize', new Uniform([1, 1])],
|
||||
['uFrameSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
const state = this.owner.state,
|
||||
camera = this.view.camera.raw,
|
||||
mrt = this.find('mrt');
|
||||
if (!this.effect || !camera || !state) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, mrt);
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tEdges').value = state.edges.texture;
|
||||
u.get('uEdgeSize').value = [state.edges.width, state.edges.height];
|
||||
u.get('tFrames').value = state.packed.texture;
|
||||
u.get('uFrameSize').value = [state.packed.width, state.packed.height];
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('tCandidates').value = state.candidates.texture;
|
||||
u.get('uCandidateSize').value = [
|
||||
state.candidates.width,
|
||||
state.candidates.height,
|
||||
];
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export function createEarthquakesNavaraRenderer(
|
||||
engine,
|
||||
{ view, EffectDesc, NavaraEffect } = {},
|
||||
) {
|
||||
if (!view?.camera || !engine?.render || !EffectDesc || !NavaraEffect)
|
||||
throw new TypeError('Earthquakes require a Navara view');
|
||||
if (!registeredViews.has(view)) {
|
||||
view.registerEffect(KEY, groundEffectClass(EffectDesc, NavaraEffect));
|
||||
registeredViews.add(view);
|
||||
}
|
||||
groundEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
let destroyed = false,
|
||||
visible = false,
|
||||
rows = [],
|
||||
|
||||
@@ -9,8 +9,6 @@ export function createFirmsNavaraRenderer(
|
||||
engine,
|
||||
{ view: nativeView, EffectDesc, NavaraEffect, id = 'local-firms' } = {},
|
||||
) {
|
||||
if (!engine?.movers || !nativeView?.camera || !EffectDesc || !NavaraEffect)
|
||||
throw new TypeError('FIRMS requires a Navara view');
|
||||
const display = createGroundCellDisplay(
|
||||
engine,
|
||||
{ view: nativeView, EffectDesc, NavaraEffect },
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// visible terrain and 3D tiles by one non-pickable classification pass. Only
|
||||
// surface pixels take it, so the fire markers above stay untouched. The
|
||||
// adapter has heatImagery.js's interface, so the layer drives both alike.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import {
|
||||
DataTexture,
|
||||
LinearFilter,
|
||||
@@ -18,9 +17,9 @@ import {
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
|
||||
const KEY = 'gevFirmsHeat';
|
||||
const registeredViews = new WeakSet();
|
||||
|
||||
// Row 0 of the raster is the north edge and column 0 is 180°W; the texture
|
||||
// keeps that order (no flip), so v = 0 is north.
|
||||
@@ -63,59 +62,45 @@ void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
}
|
||||
`;
|
||||
|
||||
function heatEffectClass(EffectDesc, NavaraEffect) {
|
||||
return class FirmsHeatEffectDesc extends EffectDesc {
|
||||
static key = KEY;
|
||||
// Under the heat cells' and markers' place in the chain: after the other
|
||||
// surface drapes, before sharpening, anti-aliasing and overlays.
|
||||
static insertAfter = [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'toneMapping',
|
||||
];
|
||||
static insertBefore = [
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[KEY].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevFirmsHeat', fragmentShader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['tHeat', new Uniform(null)],
|
||||
['uOpacity', new Uniform(1)],
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
const owner = this.owner,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !owner.texture || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tHeat').value = owner.texture;
|
||||
u.get('uOpacity').value = owner.opacity;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
const heatEffect = defineGroundEffect({
|
||||
key: KEY,
|
||||
name: 'GevFirmsHeat',
|
||||
fragmentShader,
|
||||
// Under the heat cells' and markers' place in the chain: after the other
|
||||
// surface drapes, before sharpening, anti-aliasing and overlays.
|
||||
insertAfter: [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'toneMapping',
|
||||
],
|
||||
insertBefore: [
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['tHeat', new Uniform(null)],
|
||||
['uOpacity', new Uniform(1)],
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
],
|
||||
update() {
|
||||
const owner = this.owner,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !owner.texture || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tHeat').value = owner.texture;
|
||||
u.get('uOpacity').value = owner.opacity;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The raster as a texture: linear between pixels, wrapping across 180°. Its
|
||||
@@ -148,10 +133,7 @@ export function createFirmsHeatDrape(
|
||||
engine,
|
||||
{ view, EffectDesc, NavaraEffect },
|
||||
) {
|
||||
if (!registeredViews.has(view)) {
|
||||
view.registerEffect(KEY, heatEffectClass(EffectDesc, NavaraEffect));
|
||||
registeredViews.add(view);
|
||||
}
|
||||
heatEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
const owner = { texture: null, opacity: 1 };
|
||||
let raster = null,
|
||||
show = true,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// The real FIRMS PNGs in one engine mover atlas.
|
||||
import { packImageAtlas } from '../../shared/render/imageAtlas.js';
|
||||
|
||||
const WHITE = Object.freeze([1, 1, 1, 1]);
|
||||
const CELL = 60,
|
||||
PAD = 2,
|
||||
@@ -61,33 +63,22 @@ export function createFirmsSpriteBank(
|
||||
}
|
||||
};
|
||||
function buildAtlas() {
|
||||
const entries = [...loaded],
|
||||
side = Math.ceil(Math.sqrt(entries.length));
|
||||
const canvas = createCanvas();
|
||||
canvas.width = side * CELL;
|
||||
canvas.height = Math.ceil(entries.length / side) * CELL;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('FIRMS atlas requires a canvas');
|
||||
const cells = {},
|
||||
lookup = new Map();
|
||||
entries.forEach(([url, image], index) => {
|
||||
const lookup = new Map();
|
||||
const entries = [...loaded].map(([url, image], index) => {
|
||||
const width = image.naturalWidth ?? image.width,
|
||||
height = image.naturalHeight ?? image.height;
|
||||
if (!(width > 0 && width <= BASE_SIZE && height === width))
|
||||
throw new Error('FIRMS sprite dimensions are invalid');
|
||||
const x = (index % side) * CELL + PAD,
|
||||
y = Math.floor(index / side) * CELL + PAD;
|
||||
context.drawImage(image, x, y);
|
||||
const key = String(index);
|
||||
cells[key] = [
|
||||
x / canvas.width,
|
||||
y / canvas.height,
|
||||
(x + width) / canvas.width,
|
||||
(y + height) / canvas.height,
|
||||
];
|
||||
lookup.set(url, { key, scale: width / BASE_SIZE });
|
||||
return { key, image, width, height };
|
||||
});
|
||||
return { canvas, cells, lookup };
|
||||
const atlas = packImageAtlas(entries, {
|
||||
canvas: createCanvas(),
|
||||
cell: CELL,
|
||||
pad: PAD,
|
||||
});
|
||||
return { ...atlas, lookup };
|
||||
}
|
||||
async function flush() {
|
||||
if (destroyed) return;
|
||||
|
||||
@@ -115,7 +115,7 @@ export function createLifecycle({
|
||||
const renderer = flightState._renderer;
|
||||
flightState.enabled = true;
|
||||
renderer?.fleet.setVisible(true);
|
||||
if (renderer) holdContinuousRender('flights'); // per-frame animator (perf wave 2)
|
||||
if (renderer) holdContinuousRender('flights'); // per-frame animator
|
||||
renderer?.models.setVisible(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
globalThis.document?.body.classList.contains('cockpit-mode') === true,
|
||||
|
||||
@@ -1,22 +1,11 @@
|
||||
// The civil flights layer's renderer on the Navara engine: the shared
|
||||
// aircraft renderer (src/layers/aircraft/render/navara.js) with the flights'
|
||||
// sprite slot (drawn over the other contact layers, as data/spriteOrder
|
||||
// orders them on Cesium) and airplane.glb's nose offset. Registered for
|
||||
// 'navara' by the Navara mode after its import() (src/app/navaraMode.js).
|
||||
// aircraft renderer with airplane.glb's nose offset. Registered for 'navara'
|
||||
// by the Navara mode after its import() (src/app/navaraMode.js).
|
||||
|
||||
import { createAircraftNavaraRenderer } from '../../aircraft/render/navara.js';
|
||||
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
|
||||
import { aircraftLayerNavaraRenderer } from '../../aircraft/render/navara.js';
|
||||
import { MODEL_HEADING_OFFSET_DEG } from '../policy.js';
|
||||
|
||||
/**
|
||||
* Registry factory (src/app/layers/renderers.js): `(engine, options)`.
|
||||
* @param {import('../../../globe/contract.js').GlobeEngine} engine
|
||||
*/
|
||||
export function createFlightsNavaraRenderer(engine) {
|
||||
return createAircraftNavaraRenderer({
|
||||
engine,
|
||||
layerId: 'flights',
|
||||
order: SPRITE_LAYER_ORDER.indexOf('flights'),
|
||||
headingOffsetDeg: MODEL_HEADING_OFFSET_DEG,
|
||||
});
|
||||
}
|
||||
export const createFlightsNavaraRenderer = aircraftLayerNavaraRenderer(
|
||||
'flights',
|
||||
MODEL_HEADING_OFFSET_DEG,
|
||||
);
|
||||
@@ -1,8 +1,7 @@
|
||||
// The flights logic draws only through its renderer (phase 3 Task 10a): with
|
||||
// a renderer that is plain data (no Cesium), the layer builds its fleet,
|
||||
// selects a contact on a click through the engine's selection dispatcher,
|
||||
// tracks and follows it, and releases it on an empty click. This is the seam
|
||||
// the Navara renderer (Task 10b) plugs into.
|
||||
// The flights logic draws only through its renderer: with a renderer that
|
||||
// is plain data (no Cesium), the layer builds its fleet, selects a contact
|
||||
// on a click through the engine's selection dispatcher, tracks and follows
|
||||
// it, and releases it on an empty click.
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -12,7 +11,6 @@ import { createApplicationFlights } from '../../app/layers/flights.js';
|
||||
import { defaultSurface } from '../../data/surfaceServices.js';
|
||||
import * as militaryRegistry from '../../data/militaryRegistry.js';
|
||||
import { openSkySnapshot } from '../../sources/live/aircraft.js';
|
||||
import { missingAircraftRendererMembers } from '../aircraft/render/contract.js';
|
||||
import { Rgba } from '../shared/color.js';
|
||||
import { recordingAircraftRenderer as recordingRenderer } from '../../testSupport/aircraftRecordingRenderer.mjs';
|
||||
|
||||
@@ -78,7 +76,6 @@ test('the flights logic draws, selects and follows only through its renderer', a
|
||||
},
|
||||
});
|
||||
layer.init(null, { engine });
|
||||
assert.deepEqual(missingAircraftRendererMembers(renderer), []);
|
||||
layer.enable();
|
||||
try {
|
||||
await layer.update(null);
|
||||
|
||||
@@ -32,7 +32,7 @@ export function createFlightSnapshotRenderer({
|
||||
// Reclassify if the category resolved/changed (first extended poll);
|
||||
// a ground flip (landing/takeoff) re-scales the SAME billboard in
|
||||
// place — the transition is a restyle, never a removal.
|
||||
// Round 5: depth policy is uniform (always depth-test-free, see
|
||||
// The depth policy is uniform (always depth-test-free, see
|
||||
// _groundDepthDistance) — nothing to flip on landing/takeoff.
|
||||
// Position AND rotation are owned by the fleet pass (_fleetTick);
|
||||
// course changes land on the next rotation pass (forced below).
|
||||
|
||||
@@ -399,7 +399,7 @@ export function createTracking({
|
||||
// 12 Hz icon instead of lagging ~1 s behind it.
|
||||
if (!flightState._trailHeadEntity && flightState._renderer) {
|
||||
flightState._trailHeadEntity = flightState._renderer.trails.createHead({
|
||||
// 'gev-trail' namespace (round 6): claimed by trailRenderer's pick
|
||||
// 'gev-trail' namespace: claimed by trailRenderer's pick
|
||||
// owner so a click on the head segment never reads as empty space.
|
||||
id: `gev-trail:fl-head-${++flightState._trailHeadSeq}`,
|
||||
show: !flightState._cockpitContactMode,
|
||||
@@ -441,9 +441,9 @@ export function createTracking({
|
||||
return [from, geo.cartesian3.clone(head)];
|
||||
},
|
||||
width: 2.5,
|
||||
// Round 4: the head must never vanish into the mesh either (dimmed
|
||||
// when occluded so depth still reads); round 8: geodesic, consistent
|
||||
// with the trail body (no chords).
|
||||
// The head must never vanish into the mesh either (dimmed when
|
||||
// occluded so depth still reads); geodesic, consistent with the
|
||||
// trail body (no chords).
|
||||
color: TRAIL_COLOR,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { GNSS_LEVEL_COLORS } from '../records.js';
|
||||
import { rgbaFromCss } from '../../shared/color.js';
|
||||
import { viewRectangleCenter } from '../../shared/viewRectangle.js';
|
||||
import { createGroundCellDisplay } from '../../shared/render/navaraGroundCells.js';
|
||||
|
||||
export function createGnssNavaraRenderer(engine, options) {
|
||||
@@ -13,15 +14,7 @@ export function createGnssNavaraRenderer(engine, options) {
|
||||
let position = centre && geo.cartographic.fromCartesian(centre);
|
||||
if (!position) {
|
||||
const rect = camera.viewRectangle();
|
||||
if (rect) {
|
||||
const east =
|
||||
rect.east < rect.west ? rect.east + 2 * Math.PI : rect.east;
|
||||
const longitude = (rect.west + east) / 2;
|
||||
position = {
|
||||
latitude: (rect.south + rect.north) / 2,
|
||||
longitude: longitude > Math.PI ? longitude - 2 * Math.PI : longitude,
|
||||
};
|
||||
} else position = camera.pose().cartographic;
|
||||
position = rect ? viewRectangleCenter(rect) : camera.pose().cartographic;
|
||||
}
|
||||
return {
|
||||
latitude: geo.math.toDegrees(position.latitude),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { t } from '../../../i18n/index.js';
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
|
||||
import { createInfrastructureOverlayEntry } from '../../../data/infrastructureOverlayEntry.js';
|
||||
@@ -14,8 +13,8 @@ import {
|
||||
createInstallationOutlineDrapedMesh,
|
||||
} from './navaraGeometry.js';
|
||||
import { batchInstallationOutlines } from './navaraOutlineBatch.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
|
||||
const registeredViews = new WeakSet();
|
||||
const KEY = 'gevInstallationsDrape';
|
||||
const BLACK = [0, 0, 0, 0.8];
|
||||
const IDLE_SHADER = /* glsl */ `
|
||||
@@ -24,46 +23,30 @@ void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
}
|
||||
`;
|
||||
|
||||
function createDrapeEffectClass(EffectDesc, NavaraEffect) {
|
||||
return class InstallationDrapeDesc extends EffectDesc {
|
||||
static key = KEY;
|
||||
static insertAfter = ['mrt'];
|
||||
|
||||
constructor(view, ctx, config) {
|
||||
super(view, ctx, config);
|
||||
this.owner = config[KEY].owner;
|
||||
const drapeEffect = defineGroundEffect({
|
||||
key: KEY,
|
||||
name: 'GevInstallationDrape',
|
||||
fragmentShader: IDLE_SHADER,
|
||||
insertAfter: ['mrt'],
|
||||
update() {
|
||||
const mrt = this.find('mrt');
|
||||
this.owner.globeNormal.value = mrt?.globeNormalBuffer ?? null;
|
||||
this.owner.globeDepth.value = mrt?.globeDepthBuffer ?? null;
|
||||
const scene = this.ctx.scenes.draped;
|
||||
this.owner.scene = scene;
|
||||
for (const mesh of this.owner.meshes)
|
||||
if (mesh.parent !== scene) scene.add(mesh);
|
||||
},
|
||||
destroy() {
|
||||
for (const mesh of this.owner.meshes) {
|
||||
if (mesh.parent) mesh.parent.remove(mesh);
|
||||
mesh.geometry.dispose();
|
||||
mesh.material.dispose();
|
||||
}
|
||||
|
||||
createPass() {
|
||||
this.effect = new Effect('GevInstallationDrape', IDLE_SHADER, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
|
||||
updateFrame() {
|
||||
const mrt = this.find('mrt');
|
||||
this.owner.globeNormal.value = mrt?.globeNormalBuffer ?? null;
|
||||
this.owner.globeDepth.value = mrt?.globeDepthBuffer ?? null;
|
||||
const scene = this.ctx.scenes.draped;
|
||||
this.owner.scene = scene;
|
||||
for (const mesh of this.owner.meshes)
|
||||
if (mesh.parent !== scene) scene.add(mesh);
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
for (const mesh of this.owner.meshes) {
|
||||
if (mesh.parent) mesh.parent.remove(mesh);
|
||||
mesh.geometry.dispose();
|
||||
mesh.material.dispose();
|
||||
}
|
||||
this.owner.meshes.clear();
|
||||
this.owner.scene = null;
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
this.owner.meshes.clear();
|
||||
this.owner.scene = null;
|
||||
},
|
||||
});
|
||||
|
||||
function createPointSet(engine, { id, sizePx, capacity, order }) {
|
||||
return engine.movers.createSet({
|
||||
@@ -92,19 +75,7 @@ export function createInstallationsNavaraRenderer(
|
||||
setupMaterialForDrape,
|
||||
},
|
||||
) {
|
||||
if (
|
||||
!engine?.movers ||
|
||||
!view?.registerEffect ||
|
||||
!EffectDesc ||
|
||||
!NavaraEffect ||
|
||||
!DrapedMesh ||
|
||||
!setupMaterialForDrape
|
||||
)
|
||||
throw new TypeError('Installations require a Navara view');
|
||||
if (!registeredViews.has(view)) {
|
||||
view.registerEffect(KEY, createDrapeEffectClass(EffectDesc, NavaraEffect));
|
||||
registeredViews.add(view);
|
||||
}
|
||||
drapeEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
|
||||
const layerState = state;
|
||||
const owner = {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Mission points, paths and the pad zone on Navara.
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createMoverBank } from '../../aircraft/render/navara.js';
|
||||
import { createMoverBank } from '../../shared/render/navaraMoverBank.js';
|
||||
import { createEngineLayerView } from '../../shared/render/engineView.js';
|
||||
import { registerViewerEngine } from '../../../globe/cesium/engineFromViewer.js';
|
||||
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
|
||||
|
||||
@@ -5,24 +5,21 @@
|
||||
// the zone's radius of the pad, with Cesium's fill, rim and emission. Nothing
|
||||
// is drawn at a height, so the zone neither floats over nor sinks under the
|
||||
// ground, and no height is sampled.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Matrix3, Uniform, Vector3 } from 'three';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
import { rgbaFromCss } from '../../shared/color.js';
|
||||
import { LAUNCH_PAD_ZONE_RADIUS_M, LAUNCH_PAD_ZONE_STYLE } from '../policy.js';
|
||||
|
||||
export const PAD_GROUND_KEY = 'gevLaunchPadGround';
|
||||
// The surface above or below the pad that the zone still classifies, as
|
||||
// Cesium's classification volume spans the terrain heights there.
|
||||
export const PAD_GROUND_BAND_M = 9000;
|
||||
const registered = new WeakSet();
|
||||
const PAD_GROUND_BAND_M = 9000;
|
||||
const glslFloat = (value) => Number(value).toFixed(4);
|
||||
/** A #rrggbb colour as display (sRGB) values, as Cesium's material reads it. */
|
||||
const displayRgb = (hex) =>
|
||||
[1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16) / 255);
|
||||
|
||||
export const padGroundShader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth;
|
||||
@@ -66,7 +63,7 @@ void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
`;
|
||||
|
||||
/** The pad's ECEF position and its east, north and up axes. */
|
||||
export function padFrame(launch) {
|
||||
function padFrame(launch) {
|
||||
const m = geo.transforms.eastNorthUpToFixedFrame(
|
||||
geo.cartesian3.fromDegrees(launch.lon, launch.lat, 0),
|
||||
geo.ellipsoid.WGS84,
|
||||
@@ -79,72 +76,59 @@ export function padFrame(launch) {
|
||||
};
|
||||
}
|
||||
|
||||
function padGroundClass(EffectDesc, NavaraEffect) {
|
||||
return class LaunchPadGroundDesc extends EffectDesc {
|
||||
static key = PAD_GROUND_KEY;
|
||||
static insertAfter = [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'gevFirmsGround',
|
||||
'toneMapping',
|
||||
];
|
||||
static insertBefore = [
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[PAD_GROUND_KEY].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevLaunchPadGround', padGroundShader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['uViewToWorld', new Uniform(new Matrix3())],
|
||||
['uPadOffset', new Uniform(new Vector3())],
|
||||
['uEast', new Uniform(new Vector3())],
|
||||
['uNorth', new Uniform(new Vector3())],
|
||||
['uUp', new Uniform(new Vector3())],
|
||||
[
|
||||
'uPadColor',
|
||||
new Uniform(
|
||||
new Vector3(...displayRgb(LAUNCH_PAD_ZONE_STYLE.color)),
|
||||
),
|
||||
],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
const frame = this.owner.frame,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !frame || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
const u = this.effect.uniforms;
|
||||
u.get('uViewToWorld').value.setFromMatrix4(camera.matrixWorld);
|
||||
const e = camera.matrixWorld.elements;
|
||||
u.get('uPadOffset').value.set(
|
||||
frame.origin[0] - e[12],
|
||||
frame.origin[1] - e[13],
|
||||
frame.origin[2] - e[14],
|
||||
);
|
||||
u.get('uEast').value.fromArray(frame.east);
|
||||
u.get('uNorth').value.fromArray(frame.north);
|
||||
u.get('uUp').value.fromArray(frame.up);
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
const padGroundEffect = defineGroundEffect({
|
||||
key: PAD_GROUND_KEY,
|
||||
name: 'GevLaunchPadGround',
|
||||
fragmentShader: padGroundShader,
|
||||
insertAfter: [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'gevFirmsGround',
|
||||
'toneMapping',
|
||||
],
|
||||
insertBefore: [
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['uViewToWorld', new Uniform(new Matrix3())],
|
||||
['uPadOffset', new Uniform(new Vector3())],
|
||||
['uEast', new Uniform(new Vector3())],
|
||||
['uNorth', new Uniform(new Vector3())],
|
||||
['uUp', new Uniform(new Vector3())],
|
||||
[
|
||||
'uPadColor',
|
||||
// Display (sRGB) values, as Cesium's material reads the colour.
|
||||
new Uniform(
|
||||
new Vector3(...rgbaFromCss(LAUNCH_PAD_ZONE_STYLE.color).rgba()),
|
||||
),
|
||||
],
|
||||
],
|
||||
update() {
|
||||
const frame = this.owner.frame,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !frame || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
const u = this.effect.uniforms;
|
||||
u.get('uViewToWorld').value.setFromMatrix4(camera.matrixWorld);
|
||||
const e = camera.matrixWorld.elements;
|
||||
u.get('uPadOffset').value.set(
|
||||
frame.origin[0] - e[12],
|
||||
frame.origin[1] - e[13],
|
||||
frame.origin[2] - e[14],
|
||||
);
|
||||
u.get('uEast').value.fromArray(frame.east);
|
||||
u.get('uNorth').value.fromArray(frame.north);
|
||||
u.get('uUp').value.fromArray(frame.up);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Show one pad zone on a Navara view; `show` toggles it, `destroy` removes it.
|
||||
@@ -153,13 +137,7 @@ function padGroundClass(EffectDesc, NavaraEffect) {
|
||||
* @param {{ lon: number, lat: number }} launch
|
||||
*/
|
||||
export function createPadGround(view, { EffectDesc, NavaraEffect }, launch) {
|
||||
if (!registered.has(view)) {
|
||||
view.registerEffect(
|
||||
PAD_GROUND_KEY,
|
||||
padGroundClass(EffectDesc, NavaraEffect),
|
||||
);
|
||||
registered.add(view);
|
||||
}
|
||||
padGroundEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
const owner = { frame: padFrame(launch) };
|
||||
let handle = view.addEffect({
|
||||
[PAD_GROUND_KEY]: { owner },
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// The Local ADS-B layer's renderer on Cesium (phase 3 Task 12a): the Cesium
|
||||
// objects the layer used to build itself, moved here one for one — its
|
||||
// The Local ADS-B layer's renderer on Cesium: its
|
||||
// CustomDataSource of marker entities (billboard with per-frame position,
|
||||
// rotation and visibility callbacks, a 2,000 km display distance, the 978 MHz
|
||||
// UAT ring as a point graphic), its model PrimitiveCollection (models load,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// The Local ADS-B layer's renderer on the Navara engine (phase 3 Task 12b),
|
||||
// The Local ADS-B layer's renderer on the Navara engine,
|
||||
// with render/cesium.js's interface: the shared aircraft renderer
|
||||
// (src/layers/aircraft/render/navara.js) draws the magenta markers (its
|
||||
// fleet glyphs), the Flights models and the trail; the markers' per-frame
|
||||
@@ -9,10 +9,8 @@
|
||||
// (src/app/navaraMode.js). The camera never follows a local aircraft.
|
||||
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
createAircraftNavaraRenderer,
|
||||
createMoverBank,
|
||||
} from '../../aircraft/render/navara.js';
|
||||
import { createAircraftNavaraRenderer } from '../../aircraft/render/navara.js';
|
||||
import { createMoverBank } from '../../shared/render/navaraMoverBank.js';
|
||||
import { MODEL_HEADING_OFFSET_DEG } from '../../flights/policy.js';
|
||||
import { nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
import {
|
||||
@@ -37,7 +35,7 @@ const RING_TOTAL_PX = RING_PIXEL_SIZE + 2 * RING_OUTLINE_PX;
|
||||
const MARKER_ORDER = -1;
|
||||
|
||||
/** The ring's atlas: a white ring on a 64 px canvas (tinted per instance). */
|
||||
export function drawUatRingAtlas(size = 64) {
|
||||
function drawUatRingAtlas(size = 64) {
|
||||
const canvas = globalThis.document.createElement('canvas');
|
||||
canvas.width = size;
|
||||
canvas.height = size;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// The Local ADS-B logic on its Navara renderer (phase 3 Task 12b) over a
|
||||
// The Local ADS-B logic on its Navara renderer over a
|
||||
// fake engine: magenta markers in the shared aircraft renderer's glyph sets,
|
||||
// the UAT ring as its own set, a click through the engine's selection
|
||||
// dispatcher selects (the camera never follows), empty map releases, and the
|
||||
|
||||
@@ -98,7 +98,7 @@ export function createLifecycle({
|
||||
const renderer = flightState._renderer;
|
||||
flightState.enabled = true;
|
||||
renderer?.fleet.setVisible(true);
|
||||
if (renderer) holdContinuousRender('military'); // per-frame animator (perf wave 2)
|
||||
if (renderer) holdContinuousRender('military'); // per-frame animator
|
||||
renderer?.models.setVisible(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
globalThis.document?.body.classList.contains('cockpit-mode') === true,
|
||||
|
||||
@@ -1,22 +1,11 @@
|
||||
// The military flights layer's renderer on the Navara engine: the shared
|
||||
// aircraft renderer (src/layers/aircraft/render/navara.js) with the
|
||||
// military's sprite slot (data/spriteOrder's order on Cesium) and jet.glb's
|
||||
// nose offset. Registered for 'navara' by the Navara mode after its
|
||||
// import() (src/app/navaraMode.js).
|
||||
// aircraft renderer with jet.glb's nose offset. Registered for 'navara' by
|
||||
// the Navara mode after its import() (src/app/navaraMode.js).
|
||||
|
||||
import { createAircraftNavaraRenderer } from '../../aircraft/render/navara.js';
|
||||
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
|
||||
import { aircraftLayerNavaraRenderer } from '../../aircraft/render/navara.js';
|
||||
import { MODEL_HEADING_OFFSET_DEG } from '../policy.js';
|
||||
|
||||
/**
|
||||
* Registry factory (src/app/layers/renderers.js): `(engine, options)`.
|
||||
* @param {import('../../../globe/contract.js').GlobeEngine} engine
|
||||
*/
|
||||
export function createMilitaryNavaraRenderer(engine) {
|
||||
return createAircraftNavaraRenderer({
|
||||
engine,
|
||||
layerId: 'military',
|
||||
order: SPRITE_LAYER_ORDER.indexOf('military'),
|
||||
headingOffsetDeg: MODEL_HEADING_OFFSET_DEG,
|
||||
});
|
||||
}
|
||||
export const createMilitaryNavaraRenderer = aircraftLayerNavaraRenderer(
|
||||
'military',
|
||||
MODEL_HEADING_OFFSET_DEG,
|
||||
);
|
||||
@@ -1,8 +1,7 @@
|
||||
// The military logic draws only through its renderer (phase 3 Task 11a): with
|
||||
// a renderer that is plain data (no Cesium), the layer builds its amber
|
||||
// fleet, selects a contact on a click through the engine's selection
|
||||
// dispatcher, tracks and follows it, and releases it on an empty click or
|
||||
// Escape. This is the seam the Navara renderer (Task 11b) plugs into.
|
||||
// The military logic draws only through its renderer: with a renderer that
|
||||
// is plain data (no Cesium), the layer builds its amber fleet, selects a
|
||||
// contact on a click through the engine's selection dispatcher, tracks and
|
||||
// follows it, and releases it on an empty click or Escape.
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -10,7 +9,6 @@ import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
|
||||
import { createApplicationMilitary } from '../../app/layers/militaryFlights.js';
|
||||
import { defaultSurface } from '../../data/surfaceServices.js';
|
||||
import * as militaryRegistry from '../../data/militaryRegistry.js';
|
||||
import { missingAircraftRendererMembers } from '../aircraft/render/contract.js';
|
||||
import { Rgba } from '../shared/color.js';
|
||||
import { MIL_ICON_COLOR, TRACKED_ICON_COLOR } from './policy.js';
|
||||
import { recordingAircraftRenderer } from '../../testSupport/aircraftRecordingRenderer.mjs';
|
||||
@@ -82,7 +80,6 @@ test('the military logic draws, selects and follows only through its renderer',
|
||||
},
|
||||
});
|
||||
layer.init(null, { engine });
|
||||
assert.deepEqual(missingAircraftRendererMembers(renderer), []);
|
||||
layer.enable();
|
||||
try {
|
||||
await layer.update(null);
|
||||
|
||||
@@ -55,7 +55,7 @@ export function createMilitarySnapshotRenderer({
|
||||
// resync the live model, any in-flight load, and the tracked
|
||||
// standalone (mirror of flights.js).
|
||||
if (prevMeta?.klass !== meta.klass) rendering._syncModelToClass(icao24);
|
||||
// Round 5: depth policy is uniform (always depth-test-free, see
|
||||
// The depth policy is uniform (always depth-test-free, see
|
||||
// _groundDepthDistance) — nothing to flip on landing/takeoff.
|
||||
} else {
|
||||
// Start where the fleet pass will draw it: the fleet renders behind
|
||||
|
||||
@@ -523,7 +523,7 @@ export function createTracking({
|
||||
// to the 12 Hz icon instead of lagging ~1 s behind it.
|
||||
if (!flightState._trailHeadEntity && flightState._renderer) {
|
||||
flightState._trailHeadEntity = flightState._renderer.trails.createHead({
|
||||
// 'gev-trail' namespace (round 6): claimed by trailRenderer's pick
|
||||
// 'gev-trail' namespace: claimed by trailRenderer's pick
|
||||
// owner so a click on the head segment never reads as empty space.
|
||||
id: `gev-trail:mil-head-${++flightState._trailHeadSeq}`,
|
||||
show: !flightState._cockpitContactMode,
|
||||
@@ -547,7 +547,7 @@ export function createTracking({
|
||||
// backward/reversing segment.
|
||||
const start =
|
||||
flightState._trailPositions[flightState._trailPositions.length - 2];
|
||||
// Floor the head too (round 2): a grounded tracked contact's DR
|
||||
// Floor the head too: a grounded tracked contact's DR
|
||||
// display height is the pre-datum default — without this the last
|
||||
// segment dives underground while taxiing.
|
||||
const end = _trailFloorPosition(geo.cartesian3.clone(head));
|
||||
@@ -569,9 +569,9 @@ export function createTracking({
|
||||
return [from, end];
|
||||
},
|
||||
width: 2.5,
|
||||
// Round 4: the head must never vanish into the mesh either (dimmed
|
||||
// when occluded so depth still reads); round 8: geodesic, consistent
|
||||
// with the trail body (no chords).
|
||||
// The head must never vanish into the mesh either (dimmed when
|
||||
// occluded so depth still reads); geodesic, consistent with the
|
||||
// trail body (no chords).
|
||||
color: TRAIL_COLOR,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,8 +18,6 @@ const RESAMPLE_TRIES = 20;
|
||||
* that found no surface under a place yet.
|
||||
*/
|
||||
export function createOsmPlacesNavaraRenderer(engine) {
|
||||
if (!engine?.movers)
|
||||
throw new TypeError('OSM Places requires a globe engine');
|
||||
const color = rgbaFromCss(OSM_PLACE_COLOR).rgba();
|
||||
let set = null,
|
||||
capacity = 0,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Uniform, Matrix4, DataTexture } from 'three';
|
||||
import {
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
|
||||
const KEY = 'gevRecentImagery',
|
||||
registered = new WeakMap();
|
||||
effects = new Map();
|
||||
const shader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth,tSurfaceDepth,tA,tB;
|
||||
uniform mat4 uInverseProjection,uWorld;
|
||||
@@ -57,91 +57,75 @@ void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
const boxVector = (b) =>
|
||||
b ? [b.west, b.south, b.east, b.north] : [0, 0, 0, 0];
|
||||
|
||||
// Another key (the Nepal event imagery) draws over the recent imagery.
|
||||
const imageryEffect = (key) =>
|
||||
defineGroundEffect({
|
||||
key,
|
||||
name: 'GevRecentImagery',
|
||||
fragmentShader: shader,
|
||||
insertAfter:
|
||||
key === KEY ? ['toneMapping'] : ['gevRecentImagery', 'toneMapping'],
|
||||
insertBefore: [
|
||||
'gevNepalEvent',
|
||||
'gevObservedWeather',
|
||||
'gevEarthquakeGround',
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['uGeographicA', new Uniform(false)],
|
||||
['uGeographicB', new Uniform(false)],
|
||||
['uWorld', new Uniform(new Matrix4())],
|
||||
['uSplit', new Uniform(0.5)],
|
||||
['uPixelRatio', new Uniform(1)],
|
||||
['uPreview', new Uniform([0, 0, 0, 0])],
|
||||
['uPreviewVisible', new Uniform(false)],
|
||||
...['A', 'B'].flatMap((id) => [
|
||||
[`t${id}`, new Uniform(null)],
|
||||
[`uBounds${id}`, new Uniform([0, 0, 1, 1])],
|
||||
[`uBox${id}`, new Uniform([0, 0, 0, 0])],
|
||||
[`uLook${id}`, new Uniform([0, 0])],
|
||||
]),
|
||||
],
|
||||
update() {
|
||||
if (!this.effect) return;
|
||||
const camera = this.view.camera.raw,
|
||||
u = this.effect.uniforms,
|
||||
o = this.owner;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
u.get('uWorld').value.copy(camera.matrixWorld);
|
||||
u.get('uSplit').value = o.split;
|
||||
u.get('uPixelRatio').value = o.pixelRatio();
|
||||
u.get('uPreview').value = boxVector(o.preview);
|
||||
u.get('uPreviewVisible').value = Boolean(o.preview);
|
||||
for (const id of ['A', 'B']) {
|
||||
const r = o.slots[id.toLowerCase()];
|
||||
u.get(`uGeographic${id}`).value = r?.atlas?.plan.geographic === true;
|
||||
u.get(`t${id}`).value = r?.atlas?.texture || o.empty;
|
||||
u.get(`uBounds${id}`).value = r?.atlas?.plan.bounds || [0, 0, 1, 1];
|
||||
u.get(`uBox${id}`).value = boxVector(r?.box);
|
||||
u.get(`uLook${id}`).value = [
|
||||
r?.atlas ? r.alpha : 0,
|
||||
r?.split === 'left' ? -1 : r?.split === 'right' ? 1 : 0,
|
||||
];
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export function createImageryGround(
|
||||
engine,
|
||||
{ view, EffectDesc, NavaraEffect },
|
||||
owner,
|
||||
key = KEY,
|
||||
) {
|
||||
if (!view || !EffectDesc || !NavaraEffect)
|
||||
throw new TypeError('Imagery requires Navara ground effects');
|
||||
if (!registered.has(view)) registered.set(view, new Set());
|
||||
if (!registered.get(view).has(key)) {
|
||||
class ImageryEffect extends EffectDesc {
|
||||
static key = key;
|
||||
static insertAfter = ['toneMapping'];
|
||||
static insertBefore = [
|
||||
'gevNepalEvent',
|
||||
'gevObservedWeather',
|
||||
'gevEarthquakeGround',
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[key].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevRecentImagery', shader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['uGeographicA', new Uniform(false)],
|
||||
['uGeographicB', new Uniform(false)],
|
||||
['uWorld', new Uniform(new Matrix4())],
|
||||
['uSplit', new Uniform(0.5)],
|
||||
['uPixelRatio', new Uniform(1)],
|
||||
['uPreview', new Uniform([0, 0, 0, 0])],
|
||||
['uPreviewVisible', new Uniform(false)],
|
||||
...['A', 'B'].flatMap((id) => [
|
||||
[`t${id}`, new Uniform(null)],
|
||||
[`uBounds${id}`, new Uniform([0, 0, 1, 1])],
|
||||
[`uBox${id}`, new Uniform([0, 0, 0, 0])],
|
||||
[`uLook${id}`, new Uniform([0, 0])],
|
||||
]),
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
if (!this.effect) return;
|
||||
const camera = this.view.camera.raw,
|
||||
u = this.effect.uniforms,
|
||||
o = this.owner;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
u.get('uWorld').value.copy(camera.matrixWorld);
|
||||
u.get('uSplit').value = o.split;
|
||||
u.get('uPixelRatio').value = o.pixelRatio();
|
||||
u.get('uPreview').value = boxVector(o.preview);
|
||||
u.get('uPreviewVisible').value = Boolean(o.preview);
|
||||
for (const id of ['A', 'B']) {
|
||||
const r = o.slots[id.toLowerCase()];
|
||||
u.get(`uGeographic${id}`).value = r?.atlas?.plan.geographic === true;
|
||||
u.get(`t${id}`).value = r?.atlas?.texture || o.empty;
|
||||
u.get(`uBounds${id}`).value = r?.atlas?.plan.bounds || [0, 0, 1, 1];
|
||||
u.get(`uBox${id}`).value = boxVector(r?.box);
|
||||
u.get(`uLook${id}`).value = [
|
||||
r?.atlas ? r.alpha : 0,
|
||||
r?.split === 'left' ? -1 : r?.split === 'right' ? 1 : 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
}
|
||||
class NepalEffect extends ImageryEffect {
|
||||
static insertAfter = ['gevRecentImagery', 'toneMapping'];
|
||||
}
|
||||
view.registerEffect(key, key === KEY ? ImageryEffect : NepalEffect);
|
||||
registered.get(view).add(key);
|
||||
}
|
||||
if (!effects.has(key)) effects.set(key, imageryEffect(key));
|
||||
effects.get(key).register(view, { EffectDesc, NavaraEffect });
|
||||
owner.empty = new DataTexture(new Uint8Array(4), 1, 1);
|
||||
owner.empty.needsUpdate = true;
|
||||
owner.pixelRatio = () =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const LIMIT = 85.05112878;
|
||||
export const TILE_SIZE = 256;
|
||||
export const MAX_TILE_SIDE = 8;
|
||||
const MAX_TILE_SIDE = 8;
|
||||
export const mercatorX = (lon) => (lon + 180) / 360;
|
||||
export const mercatorY = (lat) => {
|
||||
const r = (Math.max(-LIMIT, Math.min(LIMIT, lat)) * Math.PI) / 180;
|
||||
|
||||
@@ -95,9 +95,9 @@ export const TRACK_VIEW_FROM_HIGH_SCALE = 4;
|
||||
* attribute, so classification costs nothing per frame.
|
||||
*/
|
||||
|
||||
export const POINT_OUTLINE = WHITE.withAlpha(0.3);
|
||||
const POINT_OUTLINE = WHITE.withAlpha(0.3);
|
||||
|
||||
export const _classColor = (group) => rgbaFromCss(satelliteClassColor(group));
|
||||
const _classColor = (group) => rgbaFromCss(satelliteClassColor(group));
|
||||
|
||||
export const POINT_STYLES = {
|
||||
// The ISS keeps its own long-standing red hero styling rather than the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Satellite points, rigid orbit rings and follow through the globe contract.
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createMoverBank } from '../../aircraft/render/navara.js';
|
||||
import { createMoverBank } from '../../shared/render/navaraMoverBank.js';
|
||||
import { createEngineLayerView } from '../../shared/render/engineView.js';
|
||||
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
|
||||
import { WHITE, constantRgba } from '../../shared/color.js';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Engine-neutral layer colours (phase 3): the colour constants the layers
|
||||
// used to build as Cesium.Color, without Cesium.
|
||||
// Engine-neutral layer colours: the layers' colour constants, with
|
||||
// Cesium.Color's values but without Cesium.
|
||||
//
|
||||
// An Rgba has Cesium.Color's fields and the methods the layers call on their
|
||||
// colours (`withAlpha`, `clone`, `equals`), so it is accepted wherever a
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Sprite atlases for the engine's mover sets: images packed into a grid of
|
||||
// square cells, each `pad` px into its cell, with the [u0, v0, u1, v1]
|
||||
// rectangle of every image.
|
||||
|
||||
/**
|
||||
* The atlas layout (pure). Each entry is `{ key, width, height }`, the
|
||||
* drawn size of its image.
|
||||
* @param {{ key: string, width: number, height: number }[]} entries
|
||||
* @param {{ cell: number, pad?: number, columns?: number }} options
|
||||
* @returns {{ width: number, height: number,
|
||||
* rects: { key: string, x: number, y: number, width: number, height: number }[],
|
||||
* cells: Record<string, number[]> }}
|
||||
*/
|
||||
export function imageAtlasLayout(
|
||||
entries,
|
||||
{ cell, pad = 2, columns = Math.ceil(Math.sqrt(entries.length)) },
|
||||
) {
|
||||
const width = columns * cell;
|
||||
const height = Math.ceil(entries.length / columns) * cell;
|
||||
const cells = {};
|
||||
const rects = entries.map((entry, index) => {
|
||||
const x = (index % columns) * cell + pad;
|
||||
const y = Math.floor(index / columns) * cell + pad;
|
||||
cells[entry.key] = [
|
||||
x / width,
|
||||
y / height,
|
||||
(x + entry.width) / width,
|
||||
(y + entry.height) / height,
|
||||
];
|
||||
return { key: entry.key, x, y, width: entry.width, height: entry.height };
|
||||
});
|
||||
return { width, height, rects, cells };
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws `{ key, image, width, height }` entries into one canvas at
|
||||
* imageAtlasLayout's cells: at the image's own size, or scaled to
|
||||
* width × height with `resize`.
|
||||
* @returns {{ canvas: object, cells: Record<string, number[]> }}
|
||||
*/
|
||||
export function packImageAtlas(
|
||||
entries,
|
||||
{ canvas = document.createElement('canvas'), resize = false, ...options },
|
||||
) {
|
||||
const layout = imageAtlasLayout(entries, options);
|
||||
canvas.width = layout.width;
|
||||
canvas.height = layout.height;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('Sprite atlas requires a canvas');
|
||||
entries.forEach(({ image }, index) => {
|
||||
const { x, y, width, height } = layout.rects[index];
|
||||
if (resize) context.drawImage(image, x, y, width, height);
|
||||
else context.drawImage(image, x, y);
|
||||
});
|
||||
return { canvas, cells: layout.cells };
|
||||
}
|
||||
|
||||
/** Decodes image URLs (browser). */
|
||||
export const decodeImages = (urls) =>
|
||||
Promise.all(
|
||||
urls.map(async (url) => {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
return image;
|
||||
}),
|
||||
);
|
||||
@@ -4,7 +4,7 @@ const ellipsoid = geo.ellipsoid.WGS84;
|
||||
const A = ellipsoid.radii.x,
|
||||
B = ellipsoid.radii.z;
|
||||
const E2 = 1 - (B * B) / (A * A);
|
||||
export function latitudeBoundary(degrees) {
|
||||
function latitudeBoundary(degrees) {
|
||||
const angle = geo.math.toRadians(degrees),
|
||||
sin = Math.sin(angle),
|
||||
cos = Math.cos(angle);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Classify visible terrain and 3D tiles. Multiple cell layers share one non-pickable pass.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Matrix4, Uniform } from 'three';
|
||||
import { rectangleFrame } from './navaraCellGeometry.js';
|
||||
import { defineGroundEffect } from './navaraGroundEffect.js';
|
||||
import { viewFrame, groundClipBounds } from './navaraGroundGeometry.js';
|
||||
import { createGroundGrid, GRID_COLS, GRID_ROWS } from './navaraGroundGrid.js';
|
||||
import {
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
updateGroundSurface,
|
||||
} from './navaraGroundSurface.js';
|
||||
const KEY = 'gevFirmsGround';
|
||||
const registeredViews = new WeakSet();
|
||||
const fragmentShader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth;
|
||||
uniform sampler2D tSurfaceDepth;
|
||||
@@ -200,65 +199,51 @@ function buildState(cells) {
|
||||
},
|
||||
};
|
||||
}
|
||||
function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
return class FirmsGroundEffectDesc extends EffectDesc {
|
||||
static key = KEY;
|
||||
static insertAfter = [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'toneMapping',
|
||||
];
|
||||
static insertBefore = [
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[KEY].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevFirmsGround', fragmentShader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['tCells', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uCellSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
const state = this.owner.state,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !state || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tCells').value = state.packed.texture;
|
||||
u.get('uCellSize').value[0] = state.packed.width;
|
||||
u.get('uCellSize').value[1] = state.packed.height;
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('tCandidates').value = state.candidates.texture;
|
||||
u.get('uCandidateSize').value[0] = state.candidates.width;
|
||||
u.get('uCandidateSize').value[1] = state.candidates.height;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
const groundEffect = defineGroundEffect({
|
||||
key: KEY,
|
||||
name: 'GevFirmsGround',
|
||||
fragmentShader,
|
||||
insertAfter: [
|
||||
'gevEarthquakeGround',
|
||||
'gevObservedWeather',
|
||||
'gevNepalEvent',
|
||||
'gevRecentImagery',
|
||||
'toneMapping',
|
||||
],
|
||||
insertBefore: [
|
||||
'gevPreSharpenOverlay',
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['tCells', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uCellSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
],
|
||||
update() {
|
||||
const state = this.owner.state,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !state || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tCells').value = state.packed.texture;
|
||||
u.get('uCellSize').value[0] = state.packed.width;
|
||||
u.get('uCellSize').value[1] = state.packed.height;
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('tCandidates').value = state.candidates.texture;
|
||||
u.get('uCandidateSize').value[0] = state.candidates.width;
|
||||
u.get('uCandidateSize').value[1] = state.candidates.height;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
},
|
||||
});
|
||||
// The SDK allows one active effect per key. Compose enabled datasets in
|
||||
// catalog order so both can be drawn without replacing one another.
|
||||
const views = new WeakMap();
|
||||
@@ -267,10 +252,7 @@ export function createGroundCellDisplay(
|
||||
{ view, EffectDesc, NavaraEffect },
|
||||
order,
|
||||
) {
|
||||
if (!registeredViews.has(view)) {
|
||||
view.registerEffect(KEY, groundEffectClass(EffectDesc, NavaraEffect));
|
||||
registeredViews.add(view);
|
||||
}
|
||||
groundEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
let pass = views.get(view);
|
||||
if (!pass) {
|
||||
pass = {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
|
||||
/**
|
||||
* A screen-space pass on a Navara view, registered once per view under `key`.
|
||||
* `insertAfter` and `insertBefore` place it in the view's effect chain.
|
||||
* `uniforms()` lists the pass's [name, Uniform] entries; `update` and
|
||||
* `destroy` run as the descriptor's updateFrame and onDestroy, with the
|
||||
* descriptor as `this` (its `effect`, `owner`, `view`, `ctx` and `find`).
|
||||
* The owner is the `owner` of the config added with `view.addEffect`.
|
||||
*/
|
||||
export function defineGroundEffect({
|
||||
key,
|
||||
name,
|
||||
fragmentShader,
|
||||
uniforms,
|
||||
insertAfter,
|
||||
insertBefore,
|
||||
update,
|
||||
destroy,
|
||||
}) {
|
||||
const registered = new WeakSet();
|
||||
const descriptor = (EffectDesc, NavaraEffect) =>
|
||||
class GroundEffectDesc extends EffectDesc {
|
||||
static key = key;
|
||||
static insertAfter = insertAfter;
|
||||
static insertBefore = insertBefore;
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[key].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect(name, fragmentShader, {
|
||||
// Keep a separate pass: inputColor is the already tone-mapped frame.
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: uniforms && new Map(uniforms()),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
update.call(this);
|
||||
}
|
||||
onDestroy() {
|
||||
destroy?.call(this);
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
return {
|
||||
key,
|
||||
/** Register the pass on `view` the first time it is used there. */
|
||||
register(view, { EffectDesc, NavaraEffect }) {
|
||||
if (registered.has(view)) return;
|
||||
view.registerEffect(key, descriptor(EffectDesc, NavaraEffect));
|
||||
registered.add(view);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,36 +1,62 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import { createImageryGround } from '../../recentImagery/render/navaraGround.js';
|
||||
import { createEarthquakesNavaraRenderer } from '../../earthquakes/render/navara.js';
|
||||
import { createGroundCellDisplay } from './navaraGroundCells.js';
|
||||
|
||||
// EffectDesc gives insertAfter priority, then tries insertBefore. Check the
|
||||
// actual renderer declarations under every activation order, including the
|
||||
// minimal look, whose pipeline has no toneMapping anchor.
|
||||
const declarations = [
|
||||
['gevRecentImagery', '../../recentImagery/render/navaraGround.js'],
|
||||
['gevNepalEvent', '../../recentImagery/render/navaraGround.js'],
|
||||
['gevObservedWeather', '../../weather/render/navaraSurface.js'],
|
||||
['gevEarthquakeGround', '../../earthquakes/render/navara.js'],
|
||||
['gevFirmsGround', './navaraGroundCells.js'],
|
||||
['gevPreSharpenOverlay', '../../../globe/navara/overlay.js'],
|
||||
'gevRecentImagery',
|
||||
'gevNepalEvent',
|
||||
'gevObservedWeather',
|
||||
'gevEarthquakeGround',
|
||||
'gevFirmsGround',
|
||||
'gevPreSharpenOverlay',
|
||||
];
|
||||
// The descriptor a renderer registers; its setup stops there.
|
||||
const stop = new Error('registered');
|
||||
function registered(create) {
|
||||
let spec;
|
||||
const view = {
|
||||
camera: {},
|
||||
registerEffect(key, Desc) {
|
||||
spec = { key, after: Desc.insertAfter, before: Desc.insertBefore };
|
||||
throw stop;
|
||||
},
|
||||
};
|
||||
try {
|
||||
create({ view, EffectDesc: class {}, NavaraEffect: class {} });
|
||||
} catch (error) {
|
||||
if (error !== stop) throw error;
|
||||
}
|
||||
return spec;
|
||||
}
|
||||
async function declared(key, path, className) {
|
||||
let source = await fs.readFile(new URL(path, import.meta.url), 'utf8');
|
||||
if (className) source = source.split(`class ${className}`)[1];
|
||||
const anchors = (name) =>
|
||||
[
|
||||
...source
|
||||
.match(new RegExp(`static ${name} = \\[([^\\]]*)\\]`))[1]
|
||||
.matchAll(/'([^']+)'/g),
|
||||
].map((m) => m[1]);
|
||||
return { key, after: anchors('insertAfter'), before: anchors('insertBefore') };
|
||||
}
|
||||
const specs = [
|
||||
registered((sdk) => createImageryGround({}, sdk, {})),
|
||||
registered((sdk) => createImageryGround({}, sdk, {}, 'gevNepalEvent')),
|
||||
await declared('gevObservedWeather', '../../weather/render/navaraSurface.js'),
|
||||
registered((sdk) => createEarthquakesNavaraRenderer({ render: {} }, sdk)),
|
||||
registered((sdk) => createGroundCellDisplay({}, sdk, 0)),
|
||||
await declared(
|
||||
'gevPreSharpenOverlay',
|
||||
'../../../globe/navara/overlay.js',
|
||||
'GevPreSharpenOverlayEffectDesc',
|
||||
),
|
||||
];
|
||||
const specs = await Promise.all(
|
||||
declarations.map(async ([key, path]) => {
|
||||
let source = await fs.readFile(new URL(path, import.meta.url), 'utf8');
|
||||
if (key === 'gevPreSharpenOverlay')
|
||||
source = source.split('class GevPreSharpenOverlayEffectDesc')[1];
|
||||
const anchors = (name) =>
|
||||
[
|
||||
...(key === 'gevNepalEvent' && name === 'insertAfter' ? source.split('class NepalEffect')[1] : source)
|
||||
.match(new RegExp(`static ${name} = \\[([^\\]]*)\\]`))[1]
|
||||
.matchAll(/'([^']+)'/g),
|
||||
].map((m) => m[1]);
|
||||
return {
|
||||
key,
|
||||
after: anchors('insertAfter'),
|
||||
before: anchors('insertBefore'),
|
||||
};
|
||||
}),
|
||||
);
|
||||
const permutations = (items) =>
|
||||
items.length
|
||||
? items.flatMap((item, i) =>
|
||||
@@ -64,7 +90,7 @@ test('all ground/glyph activation orders preserve imagery, classification and ma
|
||||
}
|
||||
assert.deepEqual(
|
||||
order.filter((key) => specs.some((s) => s.key === key)),
|
||||
declarations.map(([key]) => key),
|
||||
declarations,
|
||||
`${toneMapping}: ${activation.map((s) => s.key)}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// A growing bank of engine.movers sprites or models that Navara renderers
|
||||
// share: handles hold their index into one mover set, which is rebuilt at
|
||||
// double the capacity when it fills.
|
||||
|
||||
const FIRST_CAPACITY = 1024;
|
||||
|
||||
// Reused set() arguments (set() copies them; no object per write).
|
||||
const fieldsNoPick = {
|
||||
position: undefined,
|
||||
orientation: undefined,
|
||||
color: undefined,
|
||||
rotation: undefined,
|
||||
scale: undefined,
|
||||
cell: undefined,
|
||||
show: undefined,
|
||||
};
|
||||
/** Writes `fields` of the mover at `index` (set() copies them). */
|
||||
export function writeFields(set, index, fields) {
|
||||
const scratch = fieldsNoPick;
|
||||
for (const key in fields) scratch[key] = fields[key];
|
||||
set.set(index, scratch);
|
||||
for (const key in fields) scratch[key] = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A growing bank of one kind of mover: handles hold an index; removal moves
|
||||
* the last handle into the hole. `options(capacity, generation)` gives the
|
||||
* createSet options; `write(handle, set, index)` writes a handle whole.
|
||||
*/
|
||||
export function createMoverBank(engine, { options, write, onCommit }) {
|
||||
const handles = [];
|
||||
let set = null;
|
||||
let generation = 0;
|
||||
let capacity = 0;
|
||||
let visible = true;
|
||||
let dirty = false;
|
||||
const build = (wanted) => {
|
||||
const next = engine.movers.createSet(options(wanted, ++generation));
|
||||
set?.destroy();
|
||||
set = next;
|
||||
capacity = wanted;
|
||||
handles.forEach((handle, index) => write(handle, set, index));
|
||||
set.setCount(visible ? handles.length : 0);
|
||||
};
|
||||
const bank = {
|
||||
handles,
|
||||
get set() {
|
||||
return set;
|
||||
},
|
||||
ready: () => Boolean(set?.ready()),
|
||||
add(handle) {
|
||||
if (handle.gevBank === bank) return;
|
||||
handle.gevBank?.remove(handle);
|
||||
handle.gevBank = bank;
|
||||
handle.gevIndex = handles.length;
|
||||
handles.push(handle);
|
||||
if (!set || handles.length > capacity)
|
||||
build(Math.max(FIRST_CAPACITY, capacity * 2, handles.length));
|
||||
else {
|
||||
write(handle, set, handle.gevIndex);
|
||||
if (visible) set.setCount(handles.length);
|
||||
}
|
||||
bank.touch();
|
||||
},
|
||||
remove(handle) {
|
||||
if (handle.gevBank !== bank) return;
|
||||
const index = handle.gevIndex;
|
||||
const last = handles.pop();
|
||||
if (last !== handle) {
|
||||
handles[index] = last;
|
||||
last.gevIndex = index;
|
||||
write(last, set, index);
|
||||
}
|
||||
handle.gevBank = null;
|
||||
handle.gevIndex = -1;
|
||||
set?.setCount(visible ? handles.length : 0);
|
||||
bank.touch();
|
||||
},
|
||||
/** Writes `fields` of one handle (when it is in this bank). */
|
||||
update(handle, fields) {
|
||||
if (handle.gevBank !== bank || !set) return;
|
||||
writeFields(set, handle.gevIndex, fields);
|
||||
bank.touch();
|
||||
},
|
||||
setVisible(next) {
|
||||
visible = next;
|
||||
set?.setCount(visible ? handles.length : 0);
|
||||
bank.touch();
|
||||
},
|
||||
visible: () => visible,
|
||||
touch() {
|
||||
if (!dirty) {
|
||||
dirty = true;
|
||||
onCommit(bank);
|
||||
}
|
||||
},
|
||||
commit() {
|
||||
if (!dirty) return;
|
||||
dirty = false;
|
||||
set?.commit();
|
||||
},
|
||||
destroy() {
|
||||
for (const handle of handles) {
|
||||
handle.gevBank = null;
|
||||
handle.gevIndex = -1;
|
||||
}
|
||||
handles.length = 0;
|
||||
set?.destroy();
|
||||
set = null;
|
||||
},
|
||||
};
|
||||
return bank;
|
||||
}
|
||||
|
||||
/** Plain colour copy (the stored value a handle's colour getter returns). */
|
||||
export class StoredColor {
|
||||
constructor(color) {
|
||||
this.red = color?.red ?? 1;
|
||||
this.green = color?.green ?? 1;
|
||||
this.blue = color?.blue ?? 1;
|
||||
this.alpha = color?.alpha ?? 1;
|
||||
}
|
||||
|
||||
withAlpha(alpha) {
|
||||
return new StoredColor({ ...this, alpha });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import * as geo from '../../geo/index.js';
|
||||
|
||||
/**
|
||||
* The centre of a view rectangle (radians), across the antimeridian when
|
||||
* its east edge is west of its west edge.
|
||||
* @param {{ west: number, south: number, east: number, north: number }} rect
|
||||
* @returns {{ latitude: number, longitude: number }}
|
||||
*/
|
||||
export function viewRectangleCenter(rect) {
|
||||
const east = rect.east < rect.west ? rect.east + Math.PI * 2 : rect.east;
|
||||
return {
|
||||
latitude: (rect.south + rect.north) / 2,
|
||||
longitude: geo.math.negativePiToPi((rect.west + east) / 2),
|
||||
};
|
||||
}
|
||||
@@ -41,7 +41,7 @@ export function featureReference(feature) {
|
||||
* Split a [lon, lat] path where a segment crosses the antimeridian, so no
|
||||
* drawn segment runs the long way across the whole map.
|
||||
*/
|
||||
export function splitAtAntimeridian(path) {
|
||||
function splitAtAntimeridian(path) {
|
||||
const parts = [];
|
||||
let current = [];
|
||||
for (let index = 0; index < path.length; index++) {
|
||||
|
||||
@@ -19,7 +19,7 @@ import { nextTask } from '../../sources/vectorTiles.js';
|
||||
* local ground estimate (a local tangent-plane approximation, metres apart at
|
||||
* the traffic layer's kilometre range). Null without a camera.
|
||||
*/
|
||||
export function groundDistanceFrom(camera, groundHeight = 0) {
|
||||
function groundDistanceFrom(camera, groundHeight = 0) {
|
||||
const view = camera && Cesium.Cartographic.fromCartesian(camera);
|
||||
if (!view) return null;
|
||||
const clearance = view.height - (groundHeight || 0) - DOT_HEIGHT_OFFSET;
|
||||
|
||||
@@ -258,8 +258,8 @@ export function createLifecycle({
|
||||
// Enabling is explicit intent, not a camera gesture that needs settling.
|
||||
parts.viewport.onCameraChanged({ immediate: true });
|
||||
|
||||
// Boot-order guard (field-test round 1: layer sat empty until the user
|
||||
// moved): when the persisted layer state re-enables traffic during the
|
||||
// Boot-order guard (otherwise the layer sits empty until the user
|
||||
// moves): when the persisted layer state re-enables traffic during the
|
||||
// intro flyTo, the initial check bails at high altitude — and a camera
|
||||
// that then parks never re-fires camera.changed. Retry cheaply until the
|
||||
// first load commits, then self-clear. Also acts as a safety kick if a
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { Rgba } from '../../shared/color.js';
|
||||
import { createMoverBank } from '../../aircraft/render/navara.js';
|
||||
import { createMoverBank } from '../../shared/render/navaraMoverBank.js';
|
||||
import {
|
||||
decodeImages,
|
||||
packImageAtlas,
|
||||
} from '../../shared/render/imageAtlas.js';
|
||||
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
|
||||
import { TRANSIT_ICON_KINDS, transitIcon } from '../../../data/transitIcons.js';
|
||||
|
||||
/** The same bounded mode/selection/style rasters used by native billboards. */
|
||||
export async function drawTransitAtlas() {
|
||||
async function drawTransitAtlas() {
|
||||
const urls = [
|
||||
...new Set(
|
||||
TRANSIT_ICON_KINDS.flatMap((mode) =>
|
||||
@@ -15,34 +19,17 @@ export async function drawTransitAtlas() {
|
||||
),
|
||||
),
|
||||
];
|
||||
const images = await Promise.all(
|
||||
urls.map(async (url) => {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
return image;
|
||||
}),
|
||||
);
|
||||
const images = await decodeImages(urls);
|
||||
const cell = Math.max(...images.map((image) => image.naturalWidth)) + 4;
|
||||
const columns = Math.ceil(Math.sqrt(images.length));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = columns * cell;
|
||||
canvas.height = Math.ceil(images.length / columns) * cell;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('Transit atlas requires a canvas');
|
||||
const cells = {};
|
||||
images.forEach((image, i) => {
|
||||
const x = (i % columns) * cell + 2,
|
||||
y = Math.floor(i / columns) * cell + 2;
|
||||
context.drawImage(image, x, y);
|
||||
cells[urls[i]] = [
|
||||
x / canvas.width,
|
||||
y / canvas.height,
|
||||
(x + image.naturalWidth) / canvas.width,
|
||||
(y + image.naturalHeight) / canvas.height,
|
||||
];
|
||||
});
|
||||
return { canvas, cells };
|
||||
return packImageAtlas(
|
||||
images.map((image, i) => ({
|
||||
key: urls[i],
|
||||
image,
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight,
|
||||
})),
|
||||
{ cell, pad: 2 },
|
||||
);
|
||||
}
|
||||
|
||||
/** Two independently dirty banks: moving contacts never upload the static fleet. */
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Uniform } from 'three';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { rgbaFromCss } from '../../shared/color.js';
|
||||
@@ -17,9 +16,9 @@ import {
|
||||
viewFrame,
|
||||
groundClipBounds,
|
||||
} from '../../shared/render/navaraGroundGeometry.js';
|
||||
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
|
||||
|
||||
const KEY = 'gevTransitGround',
|
||||
registered = new WeakSet();
|
||||
const KEY = 'gevTransitGround';
|
||||
const shader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth,tSurfaceDepth,tSegments,tGrid,tCandidates;
|
||||
uniform vec2 uSegmentSize,uCandidateSize;
|
||||
@@ -198,82 +197,63 @@ function storage(segments) {
|
||||
};
|
||||
}
|
||||
|
||||
function descriptor(EffectDesc, NavaraEffect) {
|
||||
return class TransitGroundEffect extends EffectDesc {
|
||||
static key = KEY;
|
||||
static insertAfter = ['toneMapping'];
|
||||
static insertBefore = [
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[KEY].owner;
|
||||
const groundEffect = defineGroundEffect({
|
||||
key: KEY,
|
||||
name: 'GevTransitGround',
|
||||
fragmentShader: shader,
|
||||
insertAfter: ['toneMapping'],
|
||||
insertBefore: [
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
],
|
||||
uniforms: () => [
|
||||
...groundSurfaceUniforms(),
|
||||
['tSegments', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uSegmentSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
['uDisplayT', new Uniform(0)],
|
||||
['uActive', new Uniform(-1)],
|
||||
['uColor', new Uniform([1, 1, 1])],
|
||||
['uPixelRatio', new Uniform(1)],
|
||||
],
|
||||
update() {
|
||||
if (!this.effect) return;
|
||||
const { state, displayT, active, color, pixelRatio } = this.owner;
|
||||
const camera = this.view.camera.raw;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
for (const [name, data] of [
|
||||
['Segments', state.packed],
|
||||
['Candidates', state.candidates],
|
||||
]) {
|
||||
u.get(`t${name}`).value = data.texture;
|
||||
const size = u.get(
|
||||
name === 'Segments' ? 'uSegmentSize' : 'uCandidateSize',
|
||||
).value;
|
||||
size[0] = data.width;
|
||||
size[1] = data.height;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevTransitGround', shader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['tSegments', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uSegmentSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
['uDisplayT', new Uniform(0)],
|
||||
['uActive', new Uniform(-1)],
|
||||
['uColor', new Uniform([1, 1, 1])],
|
||||
['uPixelRatio', new Uniform(1)],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
updateFrame() {
|
||||
if (!this.effect) return;
|
||||
const { state, displayT, active, color, pixelRatio } = this.owner;
|
||||
const camera = this.view.camera.raw;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
for (const [name, data] of [
|
||||
['Segments', state.packed],
|
||||
['Candidates', state.candidates],
|
||||
]) {
|
||||
u.get(`t${name}`).value = data.texture;
|
||||
const size = u.get(
|
||||
name === 'Segments' ? 'uSegmentSize' : 'uCandidateSize',
|
||||
).value;
|
||||
size[0] = data.width;
|
||||
size[1] = data.height;
|
||||
}
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('uDisplayT').value = displayT - state.epoch;
|
||||
u.get('uActive').value = active;
|
||||
u.get('uColor').value = color;
|
||||
u.get('uPixelRatio').value = pixelRatio();
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('uDisplayT').value = displayT - state.epoch;
|
||||
u.get('uActive').value = active;
|
||||
u.get('uColor').value = color;
|
||||
u.get('uPixelRatio').value = pixelRatio();
|
||||
},
|
||||
});
|
||||
|
||||
/** A static corridor texture; playback only updates time and active uniforms. */
|
||||
export function createTransitNavaraTrail(
|
||||
engine,
|
||||
{ view, EffectDesc, NavaraEffect },
|
||||
) {
|
||||
if (!view || !EffectDesc || !NavaraEffect)
|
||||
throw new TypeError('Transit trails require the Navara ground effect API');
|
||||
if (!registered.has(view)) {
|
||||
view.registerEffect(KEY, descriptor(EffectDesc, NavaraEffect));
|
||||
registered.add(view);
|
||||
}
|
||||
groundEffect.register(view, { EffectDesc, NavaraEffect });
|
||||
let segments = [],
|
||||
revision = -1,
|
||||
rebuilds = 0,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
inflateViewBounds,
|
||||
} from './policy.js';
|
||||
import { transitFeedsInRange } from '../../data/transitFeeds.js';
|
||||
import { viewRectangleCenter } from '../shared/viewRectangle.js';
|
||||
|
||||
/**
|
||||
* Camera-driven feed activation: only the feeds whose coverage circle contains
|
||||
@@ -25,11 +26,7 @@ export function createViewport({ state, services, parts }) {
|
||||
function getCameraCenterLatLon() {
|
||||
const rect = parts.renderer?.viewRectangle();
|
||||
if (rect) {
|
||||
const east = rect.east < rect.west ? rect.east + Math.PI * 2 : rect.east;
|
||||
const center = {
|
||||
latitude: (rect.south + rect.north) / 2,
|
||||
longitude: geo.math.negativePiToPi((rect.west + east) / 2),
|
||||
};
|
||||
const center = viewRectangleCenter(rect);
|
||||
return {
|
||||
lat: geo.math.toDegrees(center.latitude),
|
||||
lon: geo.math.toDegrees(center.longitude),
|
||||
|
||||
@@ -4,123 +4,11 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
|
||||
import * as selection from '../../data/selectionDispatcher.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { createVesselLayer } from './index.js';
|
||||
import { recordingRenderer, services } from './testFixtures.mjs';
|
||||
|
||||
const noop = () => {};
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
function recordingRenderer(engine) {
|
||||
const sprites = new Set();
|
||||
const moveEnd = new Set();
|
||||
const camera = {
|
||||
positionWC: { x: 0, y: 0, z: 6_500_000 },
|
||||
// 60 km up: the layer asks for a 60 km area around the camera.
|
||||
positionCartographic: {
|
||||
latitude: 40.6 * RAD,
|
||||
longitude: -73.9 * RAD,
|
||||
height: 60_000,
|
||||
},
|
||||
rightWC: { x: 1, y: 0, z: 0 },
|
||||
upWC: { x: 0, y: 1, z: 0 },
|
||||
heading: 0,
|
||||
pitch: 0,
|
||||
roll: 0,
|
||||
};
|
||||
let attached = false;
|
||||
return {
|
||||
sprites,
|
||||
camera,
|
||||
moveTo(lat, lon) {
|
||||
camera.positionCartographic = {
|
||||
latitude: lat * RAD,
|
||||
longitude: lon * RAD,
|
||||
height: 60_000,
|
||||
};
|
||||
for (const listener of moveEnd) listener();
|
||||
},
|
||||
renderer: {
|
||||
kind: 'plain',
|
||||
engine,
|
||||
view: {
|
||||
camera,
|
||||
scene: { canvas: { clientWidth: 0, clientHeight: 0 } },
|
||||
horizon: () => ({ isPointVisible: () => true }),
|
||||
worldToWindow: () => undefined,
|
||||
canvasSize: () => ({ width: 1280, height: 800 }),
|
||||
requestRender: noop,
|
||||
on(event, listener) {
|
||||
if (event !== 'moveEnd') return noop;
|
||||
moveEnd.add(listener);
|
||||
return () => moveEnd.delete(listener);
|
||||
},
|
||||
},
|
||||
fleet: {
|
||||
collection: null,
|
||||
attached: () => attached,
|
||||
attach() {
|
||||
attached = true;
|
||||
},
|
||||
setVisible: noop,
|
||||
add(spec) {
|
||||
const sprite = { ...spec };
|
||||
sprites.add(sprite);
|
||||
return sprite;
|
||||
},
|
||||
remove: (sprite) => sprites.delete(sprite),
|
||||
detach() {
|
||||
attached = false;
|
||||
},
|
||||
},
|
||||
pickedRecord: (picked) =>
|
||||
picked?.id && typeof picked.id === 'object' ? picked.id : null,
|
||||
follow: { onChanged: () => noop, active: () => false },
|
||||
trails: { create: () => null },
|
||||
destroy: noop,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function services(renderer) {
|
||||
return {
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer: noop,
|
||||
registerEntityContext: () => null,
|
||||
selectEntityContext: noop,
|
||||
},
|
||||
trails: { createTrail: null },
|
||||
labels: {},
|
||||
picking,
|
||||
overlay: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
hitTestWorldOverlay: () => null,
|
||||
},
|
||||
geoid: { ensureGeoidReady: () => new Promise(noop), geoidHeight: () => 0 },
|
||||
sprites: {
|
||||
registerSpriteCollection: noop,
|
||||
restoreSpriteOrder: noop,
|
||||
restoreSpriteOrderOnEnable: noop,
|
||||
},
|
||||
focus: {
|
||||
focusNowMs: (now) => now,
|
||||
getFocusTarget: () => null,
|
||||
focusPassIsNeeded: () => false,
|
||||
forgetSpriteFocus: noop,
|
||||
},
|
||||
worldFocus: { requestWorldFocus: noop },
|
||||
render: {
|
||||
holdContinuousRender: noop,
|
||||
releaseContinuousRender: noop,
|
||||
governorRequestRender: noop,
|
||||
},
|
||||
selection,
|
||||
renderer: { create: () => renderer },
|
||||
};
|
||||
}
|
||||
|
||||
const row = (mmsi, latitude, longitude, observedAtMs) => ({
|
||||
id: mmsi,
|
||||
reference: mmsi,
|
||||
@@ -136,7 +24,15 @@ const row = (mmsi, latitude, longitude, observedAtMs) => ({
|
||||
|
||||
test('edge:ais-live-vessels: a vessel crossing into the next cell during an AIS gap keeps one request and its card by MMSI', async (t) => {
|
||||
const engine = createFakeEngine();
|
||||
const recorder = recordingRenderer(engine);
|
||||
// 60 km up: the layer asks for a 60 km area around the camera.
|
||||
const recorder = recordingRenderer(engine, {
|
||||
positionWC: { x: 0, y: 0, z: 6_500_000 },
|
||||
positionCartographic: {
|
||||
latitude: 40.6 * RAD,
|
||||
longitude: -73.9 * RAD,
|
||||
height: 60_000,
|
||||
},
|
||||
});
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
getElementById: () => null,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// The vessels layer's renderer on Cesium (phase 3 Task 13a): the Cesium
|
||||
// objects the layer used to build itself, moved here one for one — its
|
||||
// The vessels layer's renderer on Cesium: its
|
||||
// BillboardCollection of ship chevrons (translucent blend, screen-aligned
|
||||
// rotation, centred, never depth-tested), the camera reads (horizon
|
||||
// occluder, window projection, canvas size), the "another layer took the
|
||||
@@ -9,8 +8,8 @@
|
||||
//
|
||||
// The trail stays an entity polyline (createTrail) rather than engine.lines:
|
||||
// Cesium's engine.lines is a Primitive with a depth-fail appearance, the
|
||||
// path that did not draw segments below the photoreal mesh in round 6
|
||||
// (plan, the T13/T15 blocker; flights keeps the same entity path in 10a).
|
||||
// path that does not draw segments below the photoreal mesh (flights keeps
|
||||
// the same entity path).
|
||||
//
|
||||
// Interface (shared with render/navara.js): ./contract.js.
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// The vessel renderer: what the vessels layer's logic asks of an engine to
|
||||
// draw its ship chevrons and the selected vessel's trail, and to read the
|
||||
// camera. render/cesium.js implements it over Cesium (the objects the layer
|
||||
// used to build itself, one for one); render/navara.js on the Navara engine
|
||||
// camera. render/cesium.js implements it over Cesium; render/navara.js on the Navara engine
|
||||
// over engine.movers / engine.lines / engine.projector. Nothing here imports
|
||||
// an engine.
|
||||
//
|
||||
@@ -54,39 +53,3 @@
|
||||
* @property {{ create(options: { color: string, width: number }): object|null }} trails
|
||||
* @property {() => void} destroy
|
||||
*/
|
||||
|
||||
/** The members every vessel renderer has (both engines). */
|
||||
export const VESSEL_RENDERER_SHAPE = Object.freeze({
|
||||
top: ['kind', 'view', 'fleet', 'pickedRecord', 'follow', 'trails', 'destroy'],
|
||||
view: [
|
||||
'camera',
|
||||
'scene',
|
||||
'horizon',
|
||||
'worldToWindow',
|
||||
'canvasSize',
|
||||
'requestRender',
|
||||
'on',
|
||||
],
|
||||
fleet: [
|
||||
'collection',
|
||||
'attached',
|
||||
'attach',
|
||||
'setVisible',
|
||||
'add',
|
||||
'remove',
|
||||
'detach',
|
||||
],
|
||||
follow: ['onChanged', 'active'],
|
||||
trails: ['create'],
|
||||
});
|
||||
|
||||
/** The members of VESSEL_RENDERER_SHAPE a renderer lacks ([] when whole). */
|
||||
export function missingVesselRendererMembers(renderer) {
|
||||
const missing = [];
|
||||
for (const name of VESSEL_RENDERER_SHAPE.top)
|
||||
if (!(name in (renderer ?? {}))) missing.push(name);
|
||||
for (const part of ['view', 'fleet', 'follow', 'trails'])
|
||||
for (const name of VESSEL_RENDERER_SHAPE[part])
|
||||
if (!(name in (renderer?.[part] ?? {}))) missing.push(`${part}.${name}`);
|
||||
return missing;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// The vessels layer's renderer on the Navara engine (phase 3 Task 13b),
|
||||
// The vessels layer's renderer on the Navara engine,
|
||||
// with render/cesium.js's interface (./contract.js), built only on the
|
||||
// engine contract: the chevrons are one engine.movers sprite bank (always on
|
||||
// top, as Cesium's depth-test-free billboards) whose atlas holds every
|
||||
@@ -14,8 +14,17 @@
|
||||
// frame).
|
||||
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createMoverBank } from '../../aircraft/render/navara.js';
|
||||
import {
|
||||
createMoverBank,
|
||||
StoredColor,
|
||||
} from '../../shared/render/navaraMoverBank.js';
|
||||
import { createEngineLayerView } from '../../shared/render/engineView.js';
|
||||
import { rgbaFromCss } from '../../shared/color.js';
|
||||
import {
|
||||
decodeImages,
|
||||
imageAtlasLayout,
|
||||
packImageAtlas,
|
||||
} from '../../shared/render/imageAtlas.js';
|
||||
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
|
||||
import { allVesselChevronIcons, VESSEL_ICON_PX } from '../icons.js';
|
||||
|
||||
@@ -25,62 +34,34 @@ const TRAIL_OCCLUDED_ALPHA = 0.4;
|
||||
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
|
||||
const ATLAS_PAD = 2;
|
||||
|
||||
const iconEntry = (key, image) => ({
|
||||
key,
|
||||
image,
|
||||
width: VESSEL_ICON_PX,
|
||||
height: VESSEL_ICON_PX,
|
||||
});
|
||||
const atlasOptions = (icons) => ({
|
||||
cell: VESSEL_ICON_PX + 2 * ATLAS_PAD,
|
||||
pad: ATLAS_PAD,
|
||||
columns: icons.length,
|
||||
});
|
||||
|
||||
/** The chevron atlas layout (pure): one 32 px cell per icon, in a row. */
|
||||
export function vesselAtlasLayout(icons = allVesselChevronIcons()) {
|
||||
const cell = VESSEL_ICON_PX + 2 * ATLAS_PAD;
|
||||
const width = icons.length * cell;
|
||||
const height = cell;
|
||||
const rects = new Map();
|
||||
const cells = {};
|
||||
icons.forEach((icon, column) => {
|
||||
const x = column * cell + ATLAS_PAD;
|
||||
const y = ATLAS_PAD;
|
||||
rects.set(icon, { x, y, size: VESSEL_ICON_PX });
|
||||
cells[icon] = [
|
||||
x / width,
|
||||
y / height,
|
||||
(x + VESSEL_ICON_PX) / width,
|
||||
(y + VESSEL_ICON_PX) / height,
|
||||
];
|
||||
});
|
||||
return { width, height, rects, cells };
|
||||
return imageAtlasLayout(
|
||||
icons.map((icon) => iconEntry(icon)),
|
||||
atlasOptions(icons),
|
||||
);
|
||||
}
|
||||
|
||||
/** Draws the atlas (browser): a canvas and its cells, once the SVGs decode. */
|
||||
export async function drawVesselAtlas() {
|
||||
const layout = vesselAtlasLayout();
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = layout.width;
|
||||
canvas.height = layout.height;
|
||||
const context = canvas.getContext('2d');
|
||||
await Promise.all(
|
||||
[...layout.rects].map(async ([uri, { x, y, size }]) => {
|
||||
const image = new Image();
|
||||
image.src = uri;
|
||||
await image.decode();
|
||||
context.drawImage(image, x, y, size, size);
|
||||
}),
|
||||
async function drawVesselAtlas() {
|
||||
const icons = allVesselChevronIcons();
|
||||
const images = await decodeImages(icons);
|
||||
return packImageAtlas(
|
||||
icons.map((icon, i) => iconEntry(icon, images[i])),
|
||||
{ ...atlasOptions(icons), resize: true },
|
||||
);
|
||||
return { canvas, cells: layout.cells };
|
||||
}
|
||||
|
||||
const cssToRgb = (css) => {
|
||||
const hex = String(css).replace('#', '');
|
||||
return [0, 2, 4].map((at) => parseInt(hex.slice(at, at + 2), 16) / 255);
|
||||
};
|
||||
|
||||
/** Plain colour copy (what a handle's colour getter returns). */
|
||||
class StoredColor {
|
||||
constructor(color) {
|
||||
this.red = color?.red ?? 1;
|
||||
this.green = color?.green ?? 1;
|
||||
this.blue = color?.blue ?? 1;
|
||||
this.alpha = color?.alpha ?? 1;
|
||||
}
|
||||
|
||||
withAlpha(alpha) {
|
||||
return new StoredColor({ ...this, alpha });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -338,7 +319,7 @@ export function createVesselsNavaraRenderer(
|
||||
let lineSeq = 0;
|
||||
const trails = {
|
||||
create({ color, width = 2.5 }) {
|
||||
const [r, g, b] = cssToRgb(color);
|
||||
const [r, g, b] = rgbaFromCss(color).rgba();
|
||||
const id = `gev-trail:${LAYER_ID}-${++lineSeq}`;
|
||||
let line = null;
|
||||
const ensure = () =>
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
|
||||
import * as selection from '../../data/selectionDispatcher.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { createVesselLayer } from './index.js';
|
||||
import { recordingRenderer, services } from './testFixtures.mjs';
|
||||
import { createVesselsCesiumRenderer } from './render/cesium.js';
|
||||
import { missingVesselRendererMembers } from './render/contract.js';
|
||||
import { allVesselChevronIcons, vesselChevronIcon } from './icons.js';
|
||||
import {
|
||||
VESSEL_TYPE_CSS_COLORS,
|
||||
@@ -14,109 +12,6 @@ import {
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
/** A renderer of plain records over the engine: what the logic asks for. */
|
||||
function recordingRenderer(engine) {
|
||||
const sprites = new Set();
|
||||
const followListeners = new Set();
|
||||
let following = false;
|
||||
let attached = false;
|
||||
return {
|
||||
sprites,
|
||||
raiseFollow(active) {
|
||||
following = active;
|
||||
for (const listener of followListeners) listener();
|
||||
},
|
||||
renderer: {
|
||||
kind: 'plain',
|
||||
engine,
|
||||
view: {
|
||||
camera: {
|
||||
positionWC: { x: 0, y: 0, z: 20_000_000 },
|
||||
positionCartographic: { latitude: 0, longitude: 0, height: 1e7 },
|
||||
rightWC: { x: 1, y: 0, z: 0 },
|
||||
upWC: { x: 0, y: 1, z: 0 },
|
||||
heading: 0,
|
||||
pitch: 0,
|
||||
roll: 0,
|
||||
},
|
||||
scene: { canvas: { clientWidth: 0, clientHeight: 0 } },
|
||||
horizon: () => ({ isPointVisible: () => true }),
|
||||
worldToWindow: () => undefined,
|
||||
canvasSize: () => ({ width: 1280, height: 800 }),
|
||||
requestRender: noop,
|
||||
on: () => noop,
|
||||
},
|
||||
fleet: {
|
||||
collection: null,
|
||||
attached: () => attached,
|
||||
attach() {
|
||||
attached = true;
|
||||
},
|
||||
setVisible: noop,
|
||||
add(spec) {
|
||||
const sprite = { ...spec };
|
||||
sprites.add(sprite);
|
||||
return sprite;
|
||||
},
|
||||
remove: (sprite) => sprites.delete(sprite),
|
||||
detach() {
|
||||
attached = false;
|
||||
},
|
||||
},
|
||||
pickedRecord: (picked) =>
|
||||
picked?.id && typeof picked.id === 'object' ? picked.id : null,
|
||||
follow: {
|
||||
onChanged(listener) {
|
||||
followListeners.add(listener);
|
||||
return () => followListeners.delete(listener);
|
||||
},
|
||||
active: () => following,
|
||||
},
|
||||
trails: { create: () => null },
|
||||
destroy: noop,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function services(renderer) {
|
||||
return {
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer: noop,
|
||||
registerEntityContext: () => null,
|
||||
selectEntityContext: noop,
|
||||
},
|
||||
trails: { createTrail: null },
|
||||
labels: {},
|
||||
picking,
|
||||
overlay: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
hitTestWorldOverlay: () => null,
|
||||
},
|
||||
geoid: { ensureGeoidReady: () => new Promise(noop), geoidHeight: () => 0 },
|
||||
sprites: {
|
||||
registerSpriteCollection: noop,
|
||||
restoreSpriteOrder: noop,
|
||||
restoreSpriteOrderOnEnable: noop,
|
||||
},
|
||||
focus: {
|
||||
focusNowMs: (now) => now,
|
||||
getFocusTarget: () => null,
|
||||
focusPassIsNeeded: () => false,
|
||||
forgetSpriteFocus: noop,
|
||||
},
|
||||
worldFocus: { requestWorldFocus: noop },
|
||||
render: {
|
||||
holdContinuousRender: noop,
|
||||
releaseContinuousRender: noop,
|
||||
governorRequestRender: noop,
|
||||
},
|
||||
selection,
|
||||
renderer: { create: () => renderer },
|
||||
};
|
||||
}
|
||||
|
||||
const row = (mmsi, latitude, longitude) => ({
|
||||
id: mmsi,
|
||||
reference: mmsi,
|
||||
@@ -130,11 +25,10 @@ const row = (mmsi, latitude, longitude) => ({
|
||||
courseDeg: 90,
|
||||
});
|
||||
|
||||
test('the vessels Cesium renderer has every member of the contract', () => {
|
||||
test('the vessels Cesium renderer picks the record a billboard is of', () => {
|
||||
const renderer = createVesselsCesiumRenderer(null, {
|
||||
viewer: { scene: {}, camera: {} },
|
||||
});
|
||||
assert.deepEqual(missingVesselRendererMembers(renderer), []);
|
||||
assert.equal(renderer.kind, 'cesium');
|
||||
// The record a pick is of: Cesium's billboard id is the record.
|
||||
const record = { mmsi: '111' };
|
||||
@@ -221,7 +115,6 @@ test('vessels on the Navara renderer: one always-on-top chevron bank, MMSI picks
|
||||
const renderer = createVesselsNavaraRenderer(engine, {
|
||||
drawAtlas: async () => ({ canvas: { kind: 'atlas' }, cells: layout.cells }),
|
||||
});
|
||||
assert.deepEqual(missingVesselRendererMembers(renderer), []);
|
||||
const layer = createVesselLayer({
|
||||
source: {
|
||||
label: 'Fixture vessels',
|
||||
@@ -367,7 +260,8 @@ test('a pending AIS poll and selected trail survive replacement of the planet',
|
||||
});
|
||||
|
||||
test('a vessel bank commits rows arriving after its empty visibility commit and after growth', async () => {
|
||||
const { createMoverBank } = await import('../aircraft/render/navara.js');
|
||||
const { createMoverBank } =
|
||||
await import('../shared/render/navaraMoverBank.js');
|
||||
let commits = 0;
|
||||
let pending = null;
|
||||
const bank = createMoverBank(
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Test doubles shared by the vessel layer's tests: a renderer that records
|
||||
// what the logic asks for, and the application services the layer reads.
|
||||
import * as selection from '../../data/selectionDispatcher.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
|
||||
const noop = () => {};
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
/**
|
||||
* A renderer of plain records over the engine: what the logic asks for.
|
||||
* `camera` places the view (default: 10,000 km over 0°, 0°); `moveTo` moves
|
||||
* it 60 km over a point and raises moveEnd; `raiseFollow` raises a follow
|
||||
* change.
|
||||
*/
|
||||
export function recordingRenderer(
|
||||
engine,
|
||||
{
|
||||
positionWC = { x: 0, y: 0, z: 20_000_000 },
|
||||
positionCartographic = { latitude: 0, longitude: 0, height: 1e7 },
|
||||
} = {},
|
||||
) {
|
||||
const sprites = new Set();
|
||||
const moveEnd = new Set();
|
||||
const followListeners = new Set();
|
||||
const camera = {
|
||||
positionWC,
|
||||
positionCartographic,
|
||||
rightWC: { x: 1, y: 0, z: 0 },
|
||||
upWC: { x: 0, y: 1, z: 0 },
|
||||
heading: 0,
|
||||
pitch: 0,
|
||||
roll: 0,
|
||||
};
|
||||
let following = false;
|
||||
let attached = false;
|
||||
return {
|
||||
sprites,
|
||||
camera,
|
||||
moveTo(lat, lon) {
|
||||
camera.positionCartographic = {
|
||||
latitude: lat * RAD,
|
||||
longitude: lon * RAD,
|
||||
height: 60_000,
|
||||
};
|
||||
for (const listener of moveEnd) listener();
|
||||
},
|
||||
raiseFollow(active) {
|
||||
following = active;
|
||||
for (const listener of followListeners) listener();
|
||||
},
|
||||
renderer: {
|
||||
kind: 'plain',
|
||||
engine,
|
||||
view: {
|
||||
camera,
|
||||
scene: { canvas: { clientWidth: 0, clientHeight: 0 } },
|
||||
horizon: () => ({ isPointVisible: () => true }),
|
||||
worldToWindow: () => undefined,
|
||||
canvasSize: () => ({ width: 1280, height: 800 }),
|
||||
requestRender: noop,
|
||||
on(event, listener) {
|
||||
if (event !== 'moveEnd') return noop;
|
||||
moveEnd.add(listener);
|
||||
return () => moveEnd.delete(listener);
|
||||
},
|
||||
},
|
||||
fleet: {
|
||||
collection: null,
|
||||
attached: () => attached,
|
||||
attach() {
|
||||
attached = true;
|
||||
},
|
||||
setVisible: noop,
|
||||
add(spec) {
|
||||
const sprite = { ...spec };
|
||||
sprites.add(sprite);
|
||||
return sprite;
|
||||
},
|
||||
remove: (sprite) => sprites.delete(sprite),
|
||||
detach() {
|
||||
attached = false;
|
||||
},
|
||||
},
|
||||
pickedRecord: (picked) =>
|
||||
picked?.id && typeof picked.id === 'object' ? picked.id : null,
|
||||
follow: {
|
||||
onChanged(listener) {
|
||||
followListeners.add(listener);
|
||||
return () => followListeners.delete(listener);
|
||||
},
|
||||
active: () => following,
|
||||
},
|
||||
trails: { create: () => null },
|
||||
destroy: noop,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The application services the layer reads, creating `renderer`. */
|
||||
export function services(renderer) {
|
||||
return {
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer: noop,
|
||||
registerEntityContext: () => null,
|
||||
selectEntityContext: noop,
|
||||
},
|
||||
trails: { createTrail: null },
|
||||
labels: {},
|
||||
picking,
|
||||
overlay: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
hitTestWorldOverlay: () => null,
|
||||
},
|
||||
geoid: { ensureGeoidReady: () => new Promise(noop), geoidHeight: () => 0 },
|
||||
sprites: {
|
||||
registerSpriteCollection: noop,
|
||||
restoreSpriteOrder: noop,
|
||||
restoreSpriteOrderOnEnable: noop,
|
||||
},
|
||||
focus: {
|
||||
focusNowMs: (now) => now,
|
||||
getFocusTarget: () => null,
|
||||
focusPassIsNeeded: () => false,
|
||||
forgetSpriteFocus: noop,
|
||||
},
|
||||
worldFocus: { requestWorldFocus: noop },
|
||||
render: {
|
||||
holdContinuousRender: noop,
|
||||
releaseContinuousRender: noop,
|
||||
governorRequestRender: noop,
|
||||
},
|
||||
selection,
|
||||
renderer: { create: () => renderer },
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user