mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 10:12:18 +00:00
Draw vessels, satellites, Space Missions, ALPR, bikeshare and OSM Places through one display each
Each layer now has one render/display.js on the globe contract, the same factory on both engines; its render/cesium* and render/navara* files go. Cesium's behaviour is the reference, and the logic that was written twice is written once: - AIS vessels: atlas chevrons and engine.lines trails. The display registers the gev-trail pick claim itself and its trailing visibility pass now also runs on Navara. - Satellites: point banks per look, orbit rings as lines turned by their model matrix, and selection and follow through engine.camera.follow. The emulated _viewer is gone, and the tracked readout republishes card text on Navara too. - Space Missions: dots, reticle, trajectories and tactical orbits as movers and lines. The layer keeps its own records instead of Entities and DataSources, and camera work goes through engine.camera. Clicks go through the selection dispatcher, and hover keeps Cesium's throttle. The pad zone is its rim only: the contract has no surface fill yet. - ALPR, bikeshare and OSM Places: one display and, for bikeshare, one style module each; clicks through engine.input, no ScreenSpaceEventHandler or EntityCluster. ALPR keeps Navara's horizon cull, and OSM Places points sample the surface where Cesium clamped them. Coupling: layer renderer lines fall from 4546/11106 to 2638/8735 (Cesium/Navara), `viewer` lines from 2209 to 2014, ScreenSpaceEventHandler files from 20 to 15.
This commit is contained in:
1 parent
3e261d1baf
commit
f06b93fbc9
120 files changed
+6626
-6998
No files matched your search
@@ -1,14 +0,0 @@
|
||||
import { createLifecycle } from './cesium/lifecycle.js';
|
||||
import { createRendering } from './cesium/rendering.js';
|
||||
import { createSelection } from './cesium/selection.js';
|
||||
import { createViewport } from './cesium/viewport.js';
|
||||
|
||||
/** Compose the existing Cesium-owned bikeshare render modules. */
|
||||
export function createBikeshareCesiumRenderer(context) {
|
||||
return {
|
||||
rendering: createRendering(context),
|
||||
selection: createSelection(context),
|
||||
viewport: createViewport(context),
|
||||
lifecycle: createLifecycle(context),
|
||||
};
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { GBFS_CITY_REGISTRY } from '../../registry.js';
|
||||
import { BIKESHARE_SELECTED_OVERLAY_SOURCE_ID } from '../../policy.js';
|
||||
import {
|
||||
claimCameraSensitivity,
|
||||
releaseCameraSensitivity,
|
||||
} from '../../../../data/cameraSensitivity.js';
|
||||
|
||||
export function createLifecycle({
|
||||
state: layerState,
|
||||
services,
|
||||
parts,
|
||||
source,
|
||||
engine,
|
||||
}) {
|
||||
const {
|
||||
registerSpriteCollection,
|
||||
unregisterSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
} = services.sprites;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
const methods = {
|
||||
/**
|
||||
* Initialize the bikeshare layer. Creates the point primitive collection,
|
||||
* resets all internal state, and installs the click handler.
|
||||
* Called once during app bootstrap.
|
||||
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
|
||||
*/
|
||||
init(viewer) {
|
||||
layerState._viewer = viewer;
|
||||
layerState._pointCollection = new Cesium.PointPrimitiveCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
});
|
||||
viewer.scene.primitives.add(layerState._pointCollection);
|
||||
registerSpriteCollection('bikeshare', layerState._pointCollection);
|
||||
layerState._pointCollection.show = false;
|
||||
|
||||
layerState._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
|
||||
parts.selection._installClickHandler(viewer);
|
||||
|
||||
restoreSpriteOrder(viewer);
|
||||
|
||||
console.log(
|
||||
`[Data:Bikeshare] Initialized with ${GBFS_CITY_REGISTRY.length} cities`,
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Enable the bikeshare layer. Shows points, attaches the camera listener,
|
||||
* and triggers an initial proximity check.
|
||||
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (layerState._enabled) return;
|
||||
layerState._enabled = true;
|
||||
layerState._failedCityIds.clear();
|
||||
this.show(viewer);
|
||||
},
|
||||
show(viewer) {
|
||||
viewer = layerState._viewer;
|
||||
layerState._pointCollection.show = true;
|
||||
layerState._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
true,
|
||||
);
|
||||
parts.selection._installClickHandler(viewer);
|
||||
// Pick-ownership (H2): station point ids are string render-map keys.
|
||||
registerPickOwner('bikeshare', (pickedId) =>
|
||||
layerState._stationRenderMap.has(pickedId),
|
||||
);
|
||||
|
||||
if (!layerState._cameraChangedAttached) {
|
||||
viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged);
|
||||
// Through the shared ledger: this is a single number every layer's
|
||||
// camera.changed listener shares, and a layer leaving must not hand
|
||||
// back a coarse default while this one is still driving off it.
|
||||
claimCameraSensitivity(engine ?? viewer.camera, 'bikeshare', 0.05);
|
||||
layerState._cameraChangedAttached = true;
|
||||
}
|
||||
|
||||
void parts.viewport.runProximityCheck();
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
* Disable the bikeshare layer. Hides points, removes event listeners,
|
||||
* aborts all pending fetches, and tears down all city data.
|
||||
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
|
||||
*/
|
||||
disable(viewer) {
|
||||
viewer = layerState._viewer;
|
||||
if (!viewer) return;
|
||||
layerState._enabled = false;
|
||||
layerState._proximityGeneration++;
|
||||
layerState._altitudeGateEnabled = false;
|
||||
clearTimeout(layerState._cameraDebounceTimer);
|
||||
layerState._cameraDebounceTimer = null;
|
||||
parts.selection._clearSelection();
|
||||
layerState._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
|
||||
if (layerState._clickHandler) {
|
||||
layerState._clickHandler.destroy();
|
||||
layerState._clickHandler = null;
|
||||
}
|
||||
document.removeEventListener('keydown', parts.selection._onKeyDown);
|
||||
unregisterPickOwner('bikeshare');
|
||||
|
||||
if (layerState._cameraChangedAttached) {
|
||||
viewer.camera.changed.removeEventListener(
|
||||
parts.viewport.onCameraChanged,
|
||||
);
|
||||
releaseCameraSensitivity(engine ?? viewer.camera, 'bikeshare');
|
||||
layerState._cameraChangedAttached = false;
|
||||
}
|
||||
|
||||
parts.ingestion.abortAllInFlight();
|
||||
parts.viewport.deactivateAllCities();
|
||||
layerState._cityRuntime.clear();
|
||||
layerState._pointCollection.show = false;
|
||||
layerState._count = 0;
|
||||
layerState._loading = false;
|
||||
layerState._loadingOps = 0;
|
||||
},
|
||||
|
||||
detach() {
|
||||
const viewer = layerState._viewer;
|
||||
parts.selection._clearSelection();
|
||||
layerState._clickHandler?.destroy();
|
||||
layerState._clickHandler = null;
|
||||
document.removeEventListener('keydown', parts.selection._onKeyDown);
|
||||
unregisterPickOwner('bikeshare');
|
||||
if (layerState._cameraChangedAttached) {
|
||||
viewer.camera.changed.removeEventListener(
|
||||
parts.viewport.onCameraChanged,
|
||||
);
|
||||
releaseCameraSensitivity(engine ?? viewer.camera, 'bikeshare');
|
||||
layerState._cameraChangedAttached = false;
|
||||
}
|
||||
unregisterSpriteCollection?.('bikeshare', layerState._pointCollection);
|
||||
viewer.scene.primitives.remove(layerState._pointCollection);
|
||||
layerState._pointCollection = null;
|
||||
},
|
||||
|
||||
/** Permanently release primitives, handlers, and the selected host source. */
|
||||
destroy(viewer) {
|
||||
viewer = layerState._viewer;
|
||||
if (!viewer) return;
|
||||
clearTimeout(layerState._cameraDebounceTimer);
|
||||
layerState._cameraDebounceTimer = null;
|
||||
if (layerState._enabled) this.disable(viewer);
|
||||
else {
|
||||
parts.selection._clearSelection();
|
||||
layerState._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
if (layerState._clickHandler) {
|
||||
layerState._clickHandler.destroy();
|
||||
layerState._clickHandler = null;
|
||||
}
|
||||
document.removeEventListener('keydown', parts.selection._onKeyDown);
|
||||
unregisterPickOwner('bikeshare');
|
||||
}
|
||||
if (layerState._cameraChangedAttached) {
|
||||
viewer.camera.changed.removeEventListener(
|
||||
parts.viewport.onCameraChanged,
|
||||
);
|
||||
releaseCameraSensitivity(engine ?? viewer.camera, 'bikeshare');
|
||||
layerState._cameraChangedAttached = false;
|
||||
}
|
||||
parts.ingestion.abortAllInFlight();
|
||||
if (layerState._pointCollection) {
|
||||
unregisterSpriteCollection?.('bikeshare', layerState._pointCollection);
|
||||
viewer.scene.primitives.remove(layerState._pointCollection);
|
||||
layerState._pointCollection = null;
|
||||
}
|
||||
layerState._viewer = null;
|
||||
layerState._stationInfoCache.clear();
|
||||
layerState._statusCache.clear();
|
||||
},
|
||||
};
|
||||
|
||||
return { methods };
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createState } from '../../state.js';
|
||||
|
||||
test('destroy releases the original viewer and registered collection even when passed another viewer', (t) => {
|
||||
const previous = globalThis.document;
|
||||
globalThis.document = { removeEventListener() {} };
|
||||
t.after(() => {
|
||||
globalThis.document = previous;
|
||||
});
|
||||
const noop = () => {};
|
||||
const calls = [];
|
||||
const services = {
|
||||
overlays: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteCollection: noop,
|
||||
unregisterSpriteCollection: (...args) => calls.push(args),
|
||||
restoreSpriteOrder: noop,
|
||||
},
|
||||
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
|
||||
};
|
||||
const state = createState({ services });
|
||||
const viewer = { scene: { primitives: new Cesium.PrimitiveCollection() } };
|
||||
const other = { scene: { primitives: new Cesium.PrimitiveCollection() } };
|
||||
const lifecycle = createLifecycle({
|
||||
state,
|
||||
services,
|
||||
parts: {
|
||||
selection: {
|
||||
_installClickHandler: noop,
|
||||
_clearSelection: noop,
|
||||
_onKeyDown: noop,
|
||||
},
|
||||
ingestion: { abortAllInFlight: noop },
|
||||
},
|
||||
}).methods;
|
||||
lifecycle.init(viewer);
|
||||
const collection = state._pointCollection;
|
||||
state._stationInfoCache.set('city', new Map());
|
||||
state._statusCache.set('city', {});
|
||||
lifecycle.destroy(other);
|
||||
lifecycle.destroy(other);
|
||||
assert.equal(viewer.scene.primitives.length, 0);
|
||||
assert.equal(other.scene.primitives.length, 0);
|
||||
assert.equal(collection.isDestroyed(), true);
|
||||
assert.deepEqual(calls, [['bikeshare', collection]]);
|
||||
assert.equal(state._stationInfoCache.size, 0);
|
||||
assert.equal(state._statusCache.size, 0);
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
COLOR_NEUTRAL,
|
||||
POINT_HEIGHT_OFFSET_M,
|
||||
COLOR_OUTLINE,
|
||||
} from '../../policy.js';
|
||||
import { createStationPoints } from '../../stationPoints.js';
|
||||
|
||||
export function createRendering(context) {
|
||||
const { state: layerState } = context;
|
||||
|
||||
/**
|
||||
* Create a Cartesian3 position for a station, terrain-clamped when possible.
|
||||
* Falls back to a fixed small height offset if terrain sampling is unsupported.
|
||||
* @param {Object} station - Station info object with lat/lon.
|
||||
* @returns {Cesium.Cartesian3|null} World position, or null if coordinates are invalid.
|
||||
*/
|
||||
|
||||
function createStationPosition(station) {
|
||||
const lon = Number(station?.lon);
|
||||
const lat = Number(station?.lat);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
||||
|
||||
let height = POINT_HEIGHT_OFFSET_M;
|
||||
// Sample terrain height so points sit on ground rather than at ellipsoid level
|
||||
if (layerState._viewer?.scene?.sampleHeightSupported) {
|
||||
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
|
||||
const sampled = layerState._viewer.scene.sampleHeight(carto);
|
||||
if (Number.isFinite(sampled)) {
|
||||
height = sampled + POINT_HEIGHT_OFFSET_M;
|
||||
}
|
||||
}
|
||||
|
||||
return Cesium.Cartesian3.fromDegrees(lon, lat, height);
|
||||
}
|
||||
|
||||
return createStationPoints(context, {
|
||||
position: createStationPosition,
|
||||
// A point primitive with distance-based scale and translucency falloff
|
||||
create: (record, { position, pixelSize }) =>
|
||||
layerState._pointCollection.add({
|
||||
position,
|
||||
pixelSize,
|
||||
color: COLOR_NEUTRAL,
|
||||
outlineColor: COLOR_OUTLINE,
|
||||
outlineWidth: 1,
|
||||
scaleByDistance: new Cesium.NearFarScalar(200, 1.35, 130000, 0.4),
|
||||
translucencyByDistance: new Cesium.NearFarScalar(
|
||||
200,
|
||||
1.0,
|
||||
180000,
|
||||
0.15,
|
||||
),
|
||||
disableDepthTestDistance: 2500,
|
||||
id: record.key,
|
||||
}),
|
||||
remove: (record) => layerState._pointCollection.remove(record.point),
|
||||
});
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from '../../../../data/inputOwnership.js';
|
||||
import { createBikeshareSelectedOverlayEntry } from '../../selectionModel.js';
|
||||
import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
} from '../../policy.js';
|
||||
|
||||
export function createSelection({
|
||||
state: layerState,
|
||||
services,
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
/**
|
||||
* Clear the current station selection.
|
||||
* Re-shows the hidden point primitive and removes the highlight entity.
|
||||
*/
|
||||
|
||||
function _clearSelection() {
|
||||
if (layerState._selectedKey) {
|
||||
const record = layerState._stationRenderMap.get(layerState._selectedKey);
|
||||
if (record?.point) {
|
||||
record.point.show = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (layerState._selectedEntity && layerState._viewer) {
|
||||
layerState._viewer.entities.remove(layerState._selectedEntity);
|
||||
}
|
||||
|
||||
layerState._selectedKey = null;
|
||||
layerState._selectedEntity = null;
|
||||
layerState._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a station by key: hides the original point primitive and adds a
|
||||
* highlighted cyan entity plus a protected shared-host availability card.
|
||||
* @param {string} key - Composite "cityId:stationId" key.
|
||||
*/
|
||||
|
||||
function _selectStation(key) {
|
||||
_clearSelection();
|
||||
|
||||
const record = layerState._stationRenderMap.get(key);
|
||||
if (!record || !record.point?.position || !layerState._viewer) return;
|
||||
|
||||
layerState._selectedKey = key;
|
||||
// Hide the base point so the highlight entity replaces it visually
|
||||
record.point.show = false;
|
||||
|
||||
layerState._selectedEntity = layerState._viewer.entities.add({
|
||||
position: record.point.position,
|
||||
point: {
|
||||
pixelSize: 14,
|
||||
color: Cesium.Color.CYAN,
|
||||
outlineColor: Cesium.Color.BLACK,
|
||||
outlineWidth: 2,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
});
|
||||
refreshSelectedCard();
|
||||
}
|
||||
|
||||
function refreshSelectedCard() {
|
||||
const key = layerState._selectedKey;
|
||||
const record = layerState._stationRenderMap.get(key);
|
||||
if (!record) return;
|
||||
const entry = createBikeshareSelectedOverlayEntry(key, record);
|
||||
if (entry) {
|
||||
layerState._overlayHost.setEntries(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
[entry],
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a screen-space click handler for station selection/deselection.
|
||||
* Also registers a global keydown listener for Escape-to-deselect.
|
||||
* Idempotent — does nothing if a handler is already installed.
|
||||
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
|
||||
*/
|
||||
|
||||
function _installClickHandler(viewer) {
|
||||
if (layerState._clickHandler) return;
|
||||
|
||||
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
|
||||
viewer.scene.canvas,
|
||||
);
|
||||
layerState._clickHandler.setInputAction((click) => {
|
||||
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
|
||||
if (!isPointerFree()) return;
|
||||
const picked = viewer.scene.pick(click.position);
|
||||
|
||||
if (picked) {
|
||||
// Clicking selected entity itself — ignore (don't deselect).
|
||||
if (picked.id === layerState._selectedEntity) return;
|
||||
|
||||
// Check if the picked primitive or entity id matches a station key
|
||||
const primitive = picked.primitive;
|
||||
if (
|
||||
primitive &&
|
||||
typeof primitive.id === 'string' &&
|
||||
layerState._stationRenderMap.has(primitive.id)
|
||||
) {
|
||||
_selectStation(primitive.id);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof picked.id === 'string' &&
|
||||
layerState._stationRenderMap.has(picked.id)
|
||||
) {
|
||||
_selectStation(picked.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Clicked empty space — deselect.
|
||||
if (layerState._selectedKey) _clearSelection();
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
|
||||
document.addEventListener('keydown', _onKeyDown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Global keydown handler — deselects the current station on Escape.
|
||||
* @param {KeyboardEvent} e - Keyboard event.
|
||||
*/
|
||||
|
||||
function _onKeyDown(e) {
|
||||
if (e.key === 'Escape' && layerState._selectedKey) {
|
||||
_clearSelection();
|
||||
}
|
||||
}
|
||||
return {
|
||||
refreshSelectedCard,
|
||||
_clearSelection,
|
||||
_selectStation,
|
||||
_installClickHandler,
|
||||
_onKeyDown,
|
||||
};
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../../geo/index.js';
|
||||
import { createViewport as createSharedViewport } from '../../viewport.js';
|
||||
|
||||
export function createViewport(context) {
|
||||
/**
|
||||
* Get the camera's current altitude in meters above the ellipsoid.
|
||||
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
|
||||
* @returns {number} Altitude in meters, or Infinity if unavailable.
|
||||
*/
|
||||
|
||||
function getCameraAltitude(viewer) {
|
||||
const carto = viewer?.camera?.positionCartographic;
|
||||
return carto && Number.isFinite(carto.height) ? carto.height : Infinity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the lat/lon the camera is currently looking at.
|
||||
* Prefers the center of the computed view rectangle; falls back to the
|
||||
* camera's own cartographic position when the rectangle is unavailable.
|
||||
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
|
||||
* @returns {{ lat: number, lon: number }|null} Center coordinates in degrees, or null.
|
||||
*/
|
||||
|
||||
function getCameraCenterLatLon(viewer) {
|
||||
// Try view rectangle center first (more accurate for tilted views)
|
||||
const rect = viewer?.camera?.computeViewRectangle?.(
|
||||
viewer.scene.globe?.ellipsoid,
|
||||
);
|
||||
if (rect) {
|
||||
const center = Cesium.Rectangle.center(rect);
|
||||
return {
|
||||
lat: geo.math.toDegrees(center.latitude),
|
||||
lon: geo.math.toDegrees(center.longitude),
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback: use the camera's own position
|
||||
const carto = viewer?.camera?.positionCartographic;
|
||||
if (carto) {
|
||||
return {
|
||||
lat: geo.math.toDegrees(carto.latitude),
|
||||
lon: geo.math.toDegrees(carto.longitude),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return createSharedViewport({
|
||||
...context,
|
||||
camera: { getCameraAltitude, getCameraCenterLatLon },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
// The bikeshare stations on the globe contract (engine.movers, engine.input,
|
||||
// engine.camera, engine.surface), the same on every engine:
|
||||
// - rendering: one point per station in one point set, sized by capacity
|
||||
// and coloured by availability, scaled and faded with distance, on top
|
||||
// only within 2.5 km of the camera;
|
||||
// - selection: a click on a station hides its point under a 14 px cyan
|
||||
// highlight (a one-point set drawn over everything) and publishes its
|
||||
// card; a click elsewhere or Escape clears it;
|
||||
// - viewport: the camera's altitude and view centre for the city range
|
||||
// check, rerun after camera changes;
|
||||
// - lifecycle: what init, enable, show, disable, detach and destroy own.
|
||||
// The layer (index.js) merges these into its parts.
|
||||
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { isPointerFree } from '../../../data/inputOwnership.js';
|
||||
import {
|
||||
claimCameraSensitivity,
|
||||
releaseCameraSensitivity,
|
||||
} from '../../../data/cameraSensitivity.js';
|
||||
import { SPRITE_LAYER_ORDER } from '../../../data/spriteOrder.js';
|
||||
import { viewRectangleCenter } from '../../shared/viewRectangle.js';
|
||||
import { GBFS_CITY_REGISTRY } from '../registry.js';
|
||||
import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
COLOR_NEUTRAL,
|
||||
MAX_TOTAL_POINTS,
|
||||
POINT_HEIGHT_OFFSET_M,
|
||||
} from '../policy.js';
|
||||
import { createBikeshareSelectedOverlayEntry } from '../selectionModel.js';
|
||||
import { createStationPoints } from '../stationPoints.js';
|
||||
import { createViewport } from '../viewport.js';
|
||||
import {
|
||||
SELECTED_COLOR,
|
||||
SELECTED_POINT,
|
||||
SELECTED_SET_ID,
|
||||
STATION_DEPTH_TEST,
|
||||
STATION_POINT,
|
||||
STATION_SET_ID,
|
||||
} from './style.js';
|
||||
|
||||
const LAYER_ID = 'bikeshare';
|
||||
// The station points take the layer's place among the contact sprites; the
|
||||
// highlight draws over the layer's own points.
|
||||
const STATION_ORDER = SPRITE_LAYER_ORDER.indexOf(LAYER_ID);
|
||||
const SELECTED_ORDER = STATION_ORDER + 0.5;
|
||||
|
||||
/**
|
||||
* @param {import('../../../globe/contract.js').GlobeEngine} engine
|
||||
* @param {{ state: object, services: object, parts: object, source: object }} context
|
||||
* @returns {{ rendering: object, selection: object, viewport: object, lifecycle: { methods: object } }}
|
||||
*/
|
||||
export function createBikeshareDisplay(engine, context) {
|
||||
if (!engine)
|
||||
throw new TypeError('The bikeshare display needs a globe engine');
|
||||
const { state, services, parts } = context;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking ?? {};
|
||||
let stations = null;
|
||||
let highlight = null;
|
||||
let visible = false;
|
||||
let destroyed = false;
|
||||
let removeClick = null;
|
||||
let removeCamera = null;
|
||||
|
||||
// Both sets, made with the first station or selection.
|
||||
function ensureSets() {
|
||||
if (stations || destroyed) return Boolean(stations);
|
||||
stations = engine.movers.createSet({
|
||||
id: STATION_SET_ID,
|
||||
kind: 'point',
|
||||
capacity: MAX_TOTAL_POINTS,
|
||||
order: STATION_ORDER,
|
||||
pickable: true,
|
||||
sharpen: true,
|
||||
depthTest: STATION_DEPTH_TEST,
|
||||
point: STATION_POINT,
|
||||
});
|
||||
highlight = engine.movers.createSet({
|
||||
id: SELECTED_SET_ID,
|
||||
kind: 'point',
|
||||
capacity: 1,
|
||||
order: SELECTED_ORDER,
|
||||
pickable: true,
|
||||
sharpen: true,
|
||||
depthTest: 'always',
|
||||
point: SELECTED_POINT,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
function destroySets() {
|
||||
stations?.destroy();
|
||||
highlight?.destroy();
|
||||
stations = highlight = null;
|
||||
}
|
||||
|
||||
// A station's point as stationPoints keeps it: position, pixelSize,
|
||||
// colour and show.
|
||||
function writePoint(record) {
|
||||
if (!stations) return;
|
||||
stations.set(record.index, {
|
||||
position: record.point.position,
|
||||
color: record.point.color.rgba(),
|
||||
scale: record.point.pixelSize / STATION_POINT.sizePx,
|
||||
show: record.point.show,
|
||||
pickId: record.key,
|
||||
});
|
||||
}
|
||||
function reindex() {
|
||||
let index = 0;
|
||||
for (const record of state._stationRenderMap.values()) {
|
||||
record.index = index++;
|
||||
writePoint(record);
|
||||
}
|
||||
}
|
||||
function commitStations() {
|
||||
if (!stations) return;
|
||||
stations.setCount(visible ? state._stationRenderMap.size : 0);
|
||||
stations.commit();
|
||||
}
|
||||
function commitHighlight() {
|
||||
if (!highlight) return;
|
||||
const key = state._selectedKey;
|
||||
const record = key ? state._stationRenderMap.get(key) : null;
|
||||
const shown = Boolean(record?.point?.position);
|
||||
if (shown)
|
||||
highlight.set(0, {
|
||||
position: record.point.position,
|
||||
color: SELECTED_COLOR.rgba(),
|
||||
scale: 1,
|
||||
show: true,
|
||||
pickId: key,
|
||||
});
|
||||
highlight.setCount(shown ? 1 : 0);
|
||||
highlight.commit();
|
||||
}
|
||||
// The stations show and hide together; the highlight goes with the
|
||||
// selection.
|
||||
function setVisible(next) {
|
||||
if (visible === next) return;
|
||||
visible = next;
|
||||
commitStations();
|
||||
}
|
||||
|
||||
const rendering = createStationPoints(context, {
|
||||
// On the rendered surface where it answers, a small height otherwise.
|
||||
position(station) {
|
||||
const lon = Number(station?.lon);
|
||||
const lat = Number(station?.lat);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
|
||||
ensureSets();
|
||||
const sampled = engine.surface.supported
|
||||
? engine.surface.sampleHeight(
|
||||
geo.cartographic.fromDegrees(lon, lat),
|
||||
[stations, highlight].filter(Boolean),
|
||||
)
|
||||
: undefined;
|
||||
const height =
|
||||
(Number.isFinite(sampled) ? sampled : 0) + POINT_HEIGHT_OFFSET_M;
|
||||
return geo.cartesian3.fromDegrees(lon, lat, height);
|
||||
},
|
||||
create(record, { position, pixelSize }) {
|
||||
ensureSets();
|
||||
record.index = state._stationRenderMap.size;
|
||||
record.point = {
|
||||
position,
|
||||
pixelSize,
|
||||
color: COLOR_NEUTRAL,
|
||||
show: true,
|
||||
};
|
||||
writePoint(record);
|
||||
return record.point;
|
||||
},
|
||||
afterAdd: commitStations,
|
||||
afterRemove() {
|
||||
reindex();
|
||||
commitStations();
|
||||
},
|
||||
update: writePoint,
|
||||
afterUpdate: commitStations,
|
||||
});
|
||||
|
||||
const selection = {
|
||||
/** Clears the selection: the station's point returns, the card goes. */
|
||||
_clearSelection() {
|
||||
const record = state._selectedKey
|
||||
? state._stationRenderMap.get(state._selectedKey)
|
||||
: null;
|
||||
if (record?.point) {
|
||||
record.point.show = true;
|
||||
writePoint(record);
|
||||
commitStations();
|
||||
}
|
||||
state._selectedKey = null;
|
||||
commitHighlight();
|
||||
state._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID);
|
||||
},
|
||||
/** Selects a station: its point hides under the highlight and its card. */
|
||||
_selectStation(key) {
|
||||
selection._clearSelection();
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record || !record.point?.position || !ensureSets()) return;
|
||||
state._selectedKey = key;
|
||||
record.point.show = false;
|
||||
writePoint(record);
|
||||
commitStations();
|
||||
commitHighlight();
|
||||
selection.refreshSelectedCard();
|
||||
},
|
||||
refreshSelectedCard() {
|
||||
const key = state._selectedKey;
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record) return;
|
||||
const entry = createBikeshareSelectedOverlayEntry(key, record);
|
||||
if (entry)
|
||||
state._overlayHost.setEntries(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
[entry],
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
},
|
||||
/**
|
||||
* A click on a station selects it, one on the highlight changes nothing
|
||||
* and any other clears the selection; Escape clears it too. Once.
|
||||
*/
|
||||
_installClickHandler() {
|
||||
if (removeClick) return;
|
||||
const remove = engine.input.on('click', selection._onClick, {
|
||||
pick: true,
|
||||
});
|
||||
globalThis.document?.addEventListener?.('keydown', selection._onKeyDown);
|
||||
removeClick = () => {
|
||||
remove();
|
||||
globalThis.document?.removeEventListener?.(
|
||||
'keydown',
|
||||
selection._onKeyDown,
|
||||
);
|
||||
};
|
||||
},
|
||||
_uninstallClickHandler() {
|
||||
removeClick?.();
|
||||
removeClick = null;
|
||||
},
|
||||
_onClick(event) {
|
||||
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
|
||||
if (!isPointerFree()) return;
|
||||
const picked = event.picked;
|
||||
if (picked) {
|
||||
if (picked.owner === SELECTED_SET_ID) return;
|
||||
if (
|
||||
typeof picked.id === 'string' &&
|
||||
state._stationRenderMap.has(picked.id)
|
||||
) {
|
||||
selection._selectStation(picked.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (state._selectedKey) selection._clearSelection();
|
||||
},
|
||||
_onKeyDown(event) {
|
||||
if (event.key === 'Escape' && state._selectedKey)
|
||||
selection._clearSelection();
|
||||
},
|
||||
};
|
||||
|
||||
const viewport = createViewport({
|
||||
...context,
|
||||
camera: {
|
||||
getCameraAltitude: () => engine.camera.height(),
|
||||
// The view rectangle's centre, else the point under the camera.
|
||||
getCameraCenterLatLon() {
|
||||
const rect = engine.camera.viewRectangle();
|
||||
if (rect) {
|
||||
const { latitude, longitude } = viewRectangleCenter(rect);
|
||||
return {
|
||||
lat: geo.math.toDegrees(latitude),
|
||||
lon: geo.math.toDegrees(longitude),
|
||||
};
|
||||
}
|
||||
const cartographic = engine.camera.pose()?.cartographic;
|
||||
return cartographic
|
||||
? {
|
||||
lat: geo.math.toDegrees(cartographic.latitude),
|
||||
lon: geo.math.toDegrees(cartographic.longitude),
|
||||
}
|
||||
: null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// camera.changed through the shared sensitivity ledger: every layer's
|
||||
// listener shares the one number (src/data/cameraSensitivity.js).
|
||||
function attachCamera() {
|
||||
if (state._cameraChangedAttached) return;
|
||||
removeCamera = engine.camera.changed.addEventListener(
|
||||
parts.viewport.onCameraChanged,
|
||||
);
|
||||
claimCameraSensitivity(engine, LAYER_ID, 0.05);
|
||||
state._cameraChangedAttached = true;
|
||||
}
|
||||
function detachCamera() {
|
||||
if (!state._cameraChangedAttached) return;
|
||||
removeCamera?.();
|
||||
removeCamera = null;
|
||||
releaseCameraSensitivity(engine, LAYER_ID);
|
||||
state._cameraChangedAttached = false;
|
||||
}
|
||||
function releaseInput() {
|
||||
parts.selection._uninstallClickHandler();
|
||||
unregisterPickOwner?.(LAYER_ID);
|
||||
}
|
||||
|
||||
const methods = {
|
||||
/** Builds the sets, hidden until show(). */
|
||||
init() {
|
||||
if (destroyed) throw new Error('Bikeshare renderer is destroyed');
|
||||
state._engine = engine;
|
||||
ensureSets();
|
||||
setVisible(false);
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
console.log(
|
||||
`[Data:Bikeshare] Initialized with ${GBFS_CITY_REGISTRY.length} cities`,
|
||||
);
|
||||
},
|
||||
enable() {
|
||||
if (destroyed || state._enabled) return;
|
||||
state._enabled = true;
|
||||
state._failedCityIds.clear();
|
||||
methods.show();
|
||||
},
|
||||
/** Shows the points and card, takes clicks and follows the camera. */
|
||||
show() {
|
||||
setVisible(true);
|
||||
state._overlayHost.setVisible(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID, true);
|
||||
parts.selection._installClickHandler();
|
||||
// Pick ownership: station point ids are render-map keys.
|
||||
registerPickOwner?.(LAYER_ID, (pickedId) =>
|
||||
state._stationRenderMap.has(pickedId),
|
||||
);
|
||||
attachCamera();
|
||||
void parts.viewport.runProximityCheck();
|
||||
},
|
||||
/** Hides everything, stops every request and drops the cities. */
|
||||
disable() {
|
||||
if (destroyed) return;
|
||||
state._enabled = false;
|
||||
state._proximityGeneration++;
|
||||
state._altitudeGateEnabled = false;
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = null;
|
||||
parts.selection._clearSelection();
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
releaseInput();
|
||||
detachCamera();
|
||||
parts.ingestion.abortAllInFlight();
|
||||
parts.viewport.deactivateAllCities();
|
||||
state._cityRuntime.clear();
|
||||
setVisible(false);
|
||||
state._count = 0;
|
||||
state._loading = false;
|
||||
state._loadingOps = 0;
|
||||
},
|
||||
/** Leaves this globe; the caches stay for the next one. */
|
||||
detach() {
|
||||
parts.selection._clearSelection();
|
||||
releaseInput();
|
||||
detachCamera();
|
||||
destroySets();
|
||||
destroyed = true;
|
||||
},
|
||||
/** Releases the sets, listeners and caches for good. */
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = null;
|
||||
if (state._enabled) methods.disable();
|
||||
else {
|
||||
parts.selection._clearSelection();
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
releaseInput();
|
||||
}
|
||||
detachCamera();
|
||||
parts.ingestion.abortAllInFlight();
|
||||
destroySets();
|
||||
destroyed = true;
|
||||
state._engine = null;
|
||||
state._stationInfoCache.clear();
|
||||
state._statusCache.clear();
|
||||
},
|
||||
};
|
||||
|
||||
return { rendering, selection, viewport, lifecycle: { methods } };
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
// The bikeshare stations on the engine contract, on the fake engine and on
|
||||
// the Cesium engine (real Cesium point collections over a stub scene: they
|
||||
// draw nothing but hold what the engine writes): the station discs and the
|
||||
// selected highlight as the layer styles them, their height on the sampled
|
||||
// surface, the click and Escape rules, the camera's change listener and
|
||||
// sensitivity claim, and what enable/disable cycles and teardown leave.
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
|
||||
import { createFakeEventHandlers } from '../../../globe/cesium/testing/fakeViewer.mjs';
|
||||
import { createCesiumMoversEngine } from '../../../testSupport/cesiumMoversEngine.mjs';
|
||||
import { createBikeshareLayer } from '../index.js';
|
||||
import { capacityToPixelSize } from '../presentation.js';
|
||||
import { COLOR_GREEN, COLOR_OUTLINE, COLOR_RED } from '../policy.js';
|
||||
import { createBikeshareDisplay } from './display.js';
|
||||
|
||||
const city = 'austin-capmetro';
|
||||
const key = `${city}:central`;
|
||||
const information = {
|
||||
data: {
|
||||
stations: [
|
||||
{
|
||||
station_id: 'central',
|
||||
name: '中央 / Central',
|
||||
lat: 30.2672,
|
||||
lon: -97.7431,
|
||||
capacity: 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const status = (bikes = 7) => ({
|
||||
data: {
|
||||
stations: [
|
||||
{
|
||||
station_id: 'central',
|
||||
num_bikes_available: bikes,
|
||||
num_docks_available: 10 - bikes,
|
||||
is_installed: true,
|
||||
is_renting: true,
|
||||
is_returning: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
const near = (actual, expected, label, tolerance = 1e-6) =>
|
||||
assert.ok(
|
||||
Math.abs(actual - expected) < tolerance,
|
||||
`${label}: ${actual} vs ${expected}`,
|
||||
);
|
||||
|
||||
function fakeHarness() {
|
||||
const engine = createFakeEngine();
|
||||
return {
|
||||
name: 'the fake engine',
|
||||
engine,
|
||||
/** A click whose pick is `picked` (undefined: the map). */
|
||||
click(picked) {
|
||||
engine.fake.script('pick', picked);
|
||||
engine.fake.input('click', { position: { x: 100, y: 100 } });
|
||||
},
|
||||
surface(height) {
|
||||
engine.fake.script('sampleHeight', height);
|
||||
},
|
||||
point: (id, index) => {
|
||||
const { store } = engine.fake.moverSet(id);
|
||||
return {
|
||||
shown: index < store.count && store.shows[index] === 1,
|
||||
pixelSize:
|
||||
engine.fake.moverSet(id).options.point.sizePx * store.scales[index],
|
||||
color: [...store.colors.slice(index * 4, index * 4 + 4)],
|
||||
id: store.pickIds[index],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function cesiumHarness() {
|
||||
const handlers = createFakeEventHandlers();
|
||||
const { engine, viewer, primitive } = createCesiumMoversEngine({
|
||||
engineOptions: {
|
||||
createEventHandler: handlers.create,
|
||||
scheduleFrame: (run) => run(),
|
||||
},
|
||||
});
|
||||
const count = (id) => engine.movers.list().find((set) => set.id === id).count;
|
||||
// A Cesium pick of `picked`'s set and instance: its point primitive.
|
||||
let native;
|
||||
viewer.scene.pick = () => native;
|
||||
viewer.scene.drillPick = () => (native ? [native] : []);
|
||||
return {
|
||||
name: 'the Cesium engine',
|
||||
cesium: true,
|
||||
engine,
|
||||
primitive,
|
||||
click(picked) {
|
||||
native = undefined;
|
||||
if (picked?.owner?.startsWith('bikeshare'))
|
||||
native = { primitive: primitive(picked.owner).get(picked.instance) };
|
||||
else if (picked) native = { id: picked.id, primitive: {} };
|
||||
for (const handler of handlers.handlers)
|
||||
handler.fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, {
|
||||
position: new Cesium.Cartesian2(100, 100),
|
||||
});
|
||||
},
|
||||
surface(height) {
|
||||
viewer.scene.sampleHeightSupported = true;
|
||||
viewer.scene.sampleHeight = () => height;
|
||||
},
|
||||
point: (id, index) => {
|
||||
const point = primitive(id).get(index);
|
||||
return {
|
||||
shown: index < count(id) && point.show,
|
||||
pixelSize: point.pixelSize,
|
||||
color: [
|
||||
point.color.red,
|
||||
point.color.green,
|
||||
point.color.blue,
|
||||
point.color.alpha,
|
||||
],
|
||||
id: point.id,
|
||||
native: point,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const HARNESSES = [fakeHarness, cesiumHarness];
|
||||
|
||||
function fixture(makeHarness, getStations) {
|
||||
const h = makeHarness();
|
||||
h.engine.camera.setView({
|
||||
destination: geo.cartesian3.fromDegrees(-97.7431, 30.2672, 10000),
|
||||
});
|
||||
const entries = new Map();
|
||||
const owners = new Map();
|
||||
let context, display;
|
||||
let bikes = 7;
|
||||
const source = {
|
||||
getStations:
|
||||
getStations ??
|
||||
(async (url) =>
|
||||
url.includes('station_information') ? information : status(bikes)),
|
||||
};
|
||||
const layer = createBikeshareLayer({
|
||||
source,
|
||||
services: {
|
||||
render: { governorRequestRender() {} },
|
||||
overlays: {
|
||||
setOverlayEntries: (id, value) => entries.set(id, value),
|
||||
setOverlaySourceVisible() {},
|
||||
clearOverlaySource: (id) => entries.delete(id),
|
||||
},
|
||||
picking: {
|
||||
registerPickOwner: (id, owns) => owners.set(id, owns),
|
||||
unregisterPickOwner: (id) => owners.delete(id),
|
||||
},
|
||||
},
|
||||
rendererFactory(value) {
|
||||
context = value;
|
||||
display = createBikeshareDisplay(h.engine, value);
|
||||
return display;
|
||||
},
|
||||
});
|
||||
layer.init(null, { engine: h.engine });
|
||||
return {
|
||||
...h,
|
||||
h,
|
||||
layer,
|
||||
entries,
|
||||
owners,
|
||||
get context() {
|
||||
return context;
|
||||
},
|
||||
get display() {
|
||||
return display;
|
||||
},
|
||||
setBikes: (value) => {
|
||||
bikes = value;
|
||||
},
|
||||
count: (id) => h.engine.movers.list().find((set) => set.id === id)?.count,
|
||||
};
|
||||
}
|
||||
|
||||
test('the display needs a globe engine', () => {
|
||||
assert.throws(() => createBikeshareDisplay(null, {}), TypeError);
|
||||
});
|
||||
|
||||
for (const makeHarness of HARNESSES) {
|
||||
const { name } = makeHarness();
|
||||
|
||||
test(`stations draw as capacity-sized discs that fade with distance (${name})`, async () => {
|
||||
const f = fixture(makeHarness);
|
||||
try {
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
assert.equal(f.layer.getStats().count, 1);
|
||||
assert.equal(f.count('bikeshare'), 1);
|
||||
const station = f.point('bikeshare', 0);
|
||||
assert.equal(station.shown, true);
|
||||
assert.equal(station.id, key, 'a pick returns the station key');
|
||||
near(station.pixelSize, capacityToPixelSize(10), 'pixel size');
|
||||
// 7 of 10 bikes: plenty.
|
||||
COLOR_GREEN.rgba().forEach((value, i) =>
|
||||
near(station.color[i], value, `colour ${i}`),
|
||||
);
|
||||
if (f.cesium) {
|
||||
const collection = f.primitive('bikeshare');
|
||||
assert.ok(collection instanceof Cesium.PointPrimitiveCollection);
|
||||
const point = station.native;
|
||||
assert.equal(point.outlineWidth, 1);
|
||||
assert.ok(
|
||||
point.outlineColor.equalsEpsilon(
|
||||
new Cesium.Color(...COLOR_OUTLINE.rgba()),
|
||||
1e-6,
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.NearFarScalar.equals(
|
||||
point.scaleByDistance,
|
||||
new Cesium.NearFarScalar(200, 1.35, 130000, 0.4),
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.NearFarScalar.equals(
|
||||
point.translucencyByDistance,
|
||||
new Cesium.NearFarScalar(200, 1, 180000, 0.15),
|
||||
),
|
||||
);
|
||||
assert.equal(point.disableDepthTestDistance, 2500);
|
||||
} else {
|
||||
const { options } = f.engine.fake.moverSet('bikeshare');
|
||||
assert.equal(options.pickable, true);
|
||||
assert.equal(options.sharpen, true);
|
||||
assert.equal(options.order, 3, 'its data/spriteOrder slot');
|
||||
assert.deepEqual(options.depthTest, { disableWithinM: 2500 });
|
||||
assert.equal(options.point.outlinePx, 1);
|
||||
assert.deepEqual(options.point.outlineColor, COLOR_OUTLINE.rgba());
|
||||
assert.deepEqual(
|
||||
options.point.scaleByDistance,
|
||||
[200, 1.35, 130000, 0.4],
|
||||
);
|
||||
assert.deepEqual(
|
||||
options.point.translucencyByDistance,
|
||||
[200, 1, 180000, 0.15],
|
||||
);
|
||||
}
|
||||
f.setBikes(1);
|
||||
await f.layer.update();
|
||||
COLOR_RED.rgba().forEach((value, i) =>
|
||||
near(f.point('bikeshare', 0).color[i], value, `refreshed colour ${i}`),
|
||||
);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test(`a selected station hides under a cyan highlight and keeps its card fresh (${name})`, async () => {
|
||||
const f = fixture(makeHarness);
|
||||
try {
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
f.click({ id: key, owner: 'bikeshare', instance: 0 });
|
||||
assert.equal(f.count('bikeshare-selected'), 1);
|
||||
assert.equal(f.point('bikeshare', 0).shown, false);
|
||||
const highlight = f.point('bikeshare-selected', 0);
|
||||
assert.equal(highlight.shown, true);
|
||||
near(highlight.pixelSize, 14, 'highlight size');
|
||||
assert.deepEqual(highlight.color, [0, 1, 1, 1]);
|
||||
if (f.cesium) {
|
||||
const point = highlight.native;
|
||||
assert.equal(point.outlineWidth, 2);
|
||||
assert.ok(point.outlineColor.equals(Cesium.Color.BLACK));
|
||||
assert.equal(point.disableDepthTestDistance, Number.POSITIVE_INFINITY);
|
||||
assert.equal(point.scaleByDistance, undefined);
|
||||
} else {
|
||||
const { options } = f.engine.fake.moverSet('bikeshare-selected');
|
||||
assert.equal(options.depthTest, 'always');
|
||||
assert.equal(options.point.scaleByDistance, null);
|
||||
assert.deepEqual(options.point.outlineColor, [0, 0, 0, 1]);
|
||||
assert.ok(
|
||||
options.order > f.engine.fake.moverSet('bikeshare').options.order,
|
||||
'over the layer’s own points',
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
f.entries.get('bikeshare-selected')[0].title,
|
||||
'中央 / Central',
|
||||
);
|
||||
f.click({ id: key, owner: 'bikeshare-selected', instance: 0 });
|
||||
assert.equal(
|
||||
f.count('bikeshare-selected'),
|
||||
1,
|
||||
'a click on the highlight keeps the selection',
|
||||
);
|
||||
f.setBikes(2);
|
||||
await f.layer.update();
|
||||
assert.match(
|
||||
f.entries.get('bikeshare-selected')[0].details[0],
|
||||
/2 avail/,
|
||||
);
|
||||
assert.equal(f.layer.getAnalystRecords()[0].bikesAvailable, 2);
|
||||
f.click(undefined);
|
||||
assert.equal(f.count('bikeshare-selected'), 0);
|
||||
assert.equal(f.point('bikeshare', 0).shown, true);
|
||||
assert.equal(f.entries.size, 0);
|
||||
f.click({ id: key, owner: 'bikeshare', instance: 0 });
|
||||
f.click({ id: 'flight:abc', owner: 'flights-sprites-0', instance: 0 });
|
||||
assert.equal(
|
||||
f.count('bikeshare-selected'),
|
||||
0,
|
||||
"another layer's object clears the selection too",
|
||||
);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test(`camera changes rerun the range check and ten cycles leave nothing behind (${name})`, async () => {
|
||||
const f = fixture(makeHarness);
|
||||
try {
|
||||
const base = f.engine.camera.percentageChanged;
|
||||
for (let cycle = 0; cycle < 10; cycle++) {
|
||||
f.layer.enable();
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
assert.equal(f.layer.getStats().count, 1);
|
||||
assert.equal(f.engine.camera.percentageChanged, 0.05);
|
||||
assert.equal(f.owners.get('bikeshare')(key), true);
|
||||
f.engine.camera.changed.raiseEvent(0.1);
|
||||
assert.ok(f.context.state._cameraDebounceTimer);
|
||||
f.layer.disable();
|
||||
assert.equal(f.context.state._cameraDebounceTimer, null);
|
||||
assert.equal(f.context.state._cameraChangedAttached, false);
|
||||
assert.equal(f.engine.camera.percentageChanged, base);
|
||||
assert.equal(f.owners.has('bikeshare'), false);
|
||||
assert.equal(f.layer.getStats().count, 0);
|
||||
assert.deepEqual(f.layer.getDetectableObjects(), []);
|
||||
assert.equal(f.count('bikeshare'), 0);
|
||||
f.engine.camera.changed.raiseEvent(0.1);
|
||||
assert.equal(f.context.state._cameraDebounceTimer, null);
|
||||
}
|
||||
const gate = f.display.viewport.shouldActivateAtAltitude;
|
||||
assert.equal(gate(49000), false);
|
||||
assert.equal(gate(48000), true);
|
||||
assert.equal(gate(51000), true);
|
||||
assert.equal(gate(52000), false);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
f.layer.destroy();
|
||||
}
|
||||
assert.deepEqual(f.engine.movers.list(), []);
|
||||
});
|
||||
|
||||
test(`station positions sample the surface with the layer's own sets hidden (${name})`, async () => {
|
||||
const f = fixture(makeHarness);
|
||||
try {
|
||||
f.surface(175);
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
const point = f.layer.getDetectableObjects()[0].position;
|
||||
near(geo.cartographic.fromCartesian(point).height, 177, 'height');
|
||||
if (!f.cesium) {
|
||||
const call = f.engine.fake.callsOf('surface.sampleHeight')[0];
|
||||
assert.deepEqual(
|
||||
call.args[1].map((set) => set.id),
|
||||
['bikeshare', 'bikeshare-selected'],
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('Escape clears the selection while the layer shows', async (t) => {
|
||||
const previous = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete globalThis.document;
|
||||
else globalThis.document = previous;
|
||||
});
|
||||
const f = fixture(fakeHarness);
|
||||
try {
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
f.click({ id: key, owner: 'bikeshare', instance: 0 });
|
||||
assert.equal(f.count('bikeshare-selected'), 1);
|
||||
const escape = new Event('keydown');
|
||||
escape.key = 'Escape';
|
||||
globalThis.document.dispatchEvent(escape);
|
||||
assert.equal(f.count('bikeshare-selected'), 0);
|
||||
f.click({ id: key, owner: 'bikeshare', instance: 0 });
|
||||
f.layer.disable();
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
f.click({ id: key, owner: 'bikeshare', instance: 0 });
|
||||
f.layer.disable();
|
||||
globalThis.document.dispatchEvent(escape);
|
||||
assert.equal(f.count('bikeshare-selected'), 0);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('an aborted response cannot repopulate caches or clear a newer request loading state', async () => {
|
||||
const pending = [];
|
||||
const f = fixture(
|
||||
fakeHarness,
|
||||
(url, { signal }) =>
|
||||
new Promise((resolve) => pending.push({ url, signal, resolve })),
|
||||
);
|
||||
f.layer.enable();
|
||||
assert.equal(pending.length, 1);
|
||||
f.layer.disable();
|
||||
assert.equal(pending[0].signal.aborted, true);
|
||||
f.layer.enable();
|
||||
assert.equal(pending.length, 2);
|
||||
pending[0].resolve(information);
|
||||
await settle();
|
||||
assert.equal(f.context.state._stationInfoCache.size, 0);
|
||||
assert.equal(f.layer.getStats().loading, true);
|
||||
f.layer.destroy();
|
||||
pending[1].resolve(information);
|
||||
await settle();
|
||||
assert.equal(f.context.state._stationInfoCache.size, 0);
|
||||
assert.equal(f.layer.getStats().count, 0);
|
||||
assert.deepEqual(f.engine.movers.list(), []);
|
||||
});
|
||||
|
||||
test('a station without a published capacity re-derives it from every status poll', async () => {
|
||||
const f = fixture(fakeHarness);
|
||||
try {
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
const { rendering } = f.display;
|
||||
const { model } = f.context.parts;
|
||||
const info = model.parseStationInformation({
|
||||
data: {
|
||||
stations: [
|
||||
{ station_id: 'open', name: 'Open', lat: 30.26, lon: -97.74 },
|
||||
],
|
||||
},
|
||||
});
|
||||
rendering.ensureCityPoints(city, info);
|
||||
const poll = (stations) =>
|
||||
rendering.applyStatusToPoints(
|
||||
city,
|
||||
model.parseStationStatus({ data: { stations } }),
|
||||
);
|
||||
const open = f.context.state._stationRenderMap.get(`${city}:open`);
|
||||
poll([
|
||||
{ station_id: 'open', num_bikes_available: 10, num_docks_available: 20 },
|
||||
]);
|
||||
assert.equal(open.capacity, 30);
|
||||
near(
|
||||
f.point('bikeshare', open.index).pixelSize,
|
||||
capacityToPixelSize(30),
|
||||
'the point grows with it',
|
||||
);
|
||||
poll([
|
||||
{ station_id: 'open', num_bikes_available: 4, num_docks_available: 2 },
|
||||
]);
|
||||
assert.equal(open.capacity, 6, 'the second poll is not pinned to 30');
|
||||
assert.equal(
|
||||
f.context.state._stationRenderMap.get(key).capacity,
|
||||
10,
|
||||
'a published capacity is kept',
|
||||
);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
@@ -1,286 +0,0 @@
|
||||
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,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
COLOR_NEUTRAL,
|
||||
COLOR_OUTLINE,
|
||||
MAX_TOTAL_POINTS,
|
||||
POINT_HEIGHT_OFFSET_M,
|
||||
} from '../policy.js';
|
||||
import { capacityToPixelSize } from '../presentation.js';
|
||||
import { createBikeshareSelectedOverlayEntry } from '../selectionModel.js';
|
||||
import { createStationPoints } from '../stationPoints.js';
|
||||
|
||||
const LAYER_ID = 'bikeshare';
|
||||
|
||||
function pointSet(engine, { id, capacity, order, depthTest, point }) {
|
||||
return engine.movers.createSet({
|
||||
id,
|
||||
kind: 'point',
|
||||
capacity,
|
||||
order,
|
||||
pickable: true,
|
||||
sharpen: true,
|
||||
depthTest,
|
||||
point,
|
||||
});
|
||||
}
|
||||
|
||||
export function createBikeshareNavaraRenderer(engine, context) {
|
||||
const { state, services, parts } = context;
|
||||
const normalSet = pointSet(engine, {
|
||||
id: LAYER_ID,
|
||||
capacity: MAX_TOTAL_POINTS,
|
||||
order: 30,
|
||||
point: {
|
||||
sizePx: 8,
|
||||
outlinePx: 1,
|
||||
outlineColor: COLOR_OUTLINE.rgba(),
|
||||
scaleByDistance: [200, 1.35, 130000, 0.4],
|
||||
translucencyByDistance: [200, 1, 180000, 0.15],
|
||||
},
|
||||
depthTest: { disableWithinM: 2500 },
|
||||
});
|
||||
const selectedSet = pointSet(engine, {
|
||||
id: `${LAYER_ID}-selected`,
|
||||
capacity: 1,
|
||||
order: 31,
|
||||
point: { sizePx: 14, outlinePx: 2, outlineColor: [0, 0, 0, 1] },
|
||||
depthTest: 'always',
|
||||
});
|
||||
let selectionRemove = null;
|
||||
let cameraRemove = null;
|
||||
let destroyed = false;
|
||||
|
||||
const syncPoint = (record) => {
|
||||
const color = record.point.color;
|
||||
normalSet.set(record.index, {
|
||||
position: record.point.position,
|
||||
color: color.rgba(),
|
||||
scale: capacityToPixelSize(record.capacity) / 8,
|
||||
show: record.point.show,
|
||||
pickId: record.key,
|
||||
});
|
||||
};
|
||||
const resetNormalSet = () => {
|
||||
normalSet.setCount(state._stationRenderMap.size);
|
||||
let index = 0;
|
||||
for (const record of state._stationRenderMap.values()) {
|
||||
record.index = index++;
|
||||
syncPoint(record);
|
||||
}
|
||||
normalSet.commit();
|
||||
state._count = state._stationRenderMap.size;
|
||||
};
|
||||
const request = (reason) => services.render.governorRequestRender(reason);
|
||||
|
||||
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;
|
||||
const sampled = engine.surface.supported
|
||||
? engine.surface.sampleHeight(geo.cartographic.fromDegrees(lon, lat), [
|
||||
normalSet,
|
||||
selectedSet,
|
||||
])
|
||||
: undefined;
|
||||
const height =
|
||||
(Number.isFinite(sampled) ? sampled : 0) + POINT_HEIGHT_OFFSET_M;
|
||||
return geo.cartesian3.fromDegrees(lon, lat, height);
|
||||
},
|
||||
create(record, { position, pixelSize }) {
|
||||
record.index = state._stationRenderMap.size;
|
||||
record.point = { position, pixelSize, color: COLOR_NEUTRAL, show: true };
|
||||
syncPoint(record);
|
||||
return record.point;
|
||||
},
|
||||
afterAdd() {
|
||||
normalSet.setCount(state._stationRenderMap.size);
|
||||
normalSet.commit();
|
||||
},
|
||||
afterRemove: resetNormalSet,
|
||||
update: syncPoint,
|
||||
afterUpdate: () => normalSet.commit(),
|
||||
});
|
||||
|
||||
const selection = {
|
||||
refreshSelectedCard() {
|
||||
const key = state._selectedKey;
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record) return;
|
||||
state._overlayHost.setEntries(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
[createBikeshareSelectedOverlayEntry(key, record)],
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
},
|
||||
_clearSelection() {
|
||||
if (state._selectedKey) {
|
||||
const record = state._stationRenderMap.get(state._selectedKey);
|
||||
if (record?.point) {
|
||||
record.point.show = true;
|
||||
syncPoint(record);
|
||||
normalSet.commit();
|
||||
}
|
||||
}
|
||||
state._selectedKey = null;
|
||||
state._selectedEntity = null;
|
||||
selectedSet.setCount(0);
|
||||
selectedSet.commit();
|
||||
state._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID);
|
||||
request('bikeshare-selection-clear');
|
||||
},
|
||||
_selectStation(key) {
|
||||
this._clearSelection();
|
||||
const record = state._stationRenderMap.get(key);
|
||||
if (!record || !record.point?.position) return;
|
||||
state._selectedKey = key;
|
||||
record.point.show = false;
|
||||
syncPoint(record);
|
||||
normalSet.commit();
|
||||
selectedSet.setCount(1);
|
||||
selectedSet.set(0, {
|
||||
position: record.point.position,
|
||||
color: CYAN.rgba(),
|
||||
scale: 1,
|
||||
show: true,
|
||||
pickId: key,
|
||||
});
|
||||
selectedSet.commit();
|
||||
const entry = createBikeshareSelectedOverlayEntry(key, record);
|
||||
if (entry) {
|
||||
state._overlayHost.setEntries(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
[entry],
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
true,
|
||||
);
|
||||
}
|
||||
request('bikeshare-selection');
|
||||
},
|
||||
};
|
||||
|
||||
const viewport = createViewport({
|
||||
...context,
|
||||
camera: {
|
||||
getCameraAltitude: () => engine.camera.height(),
|
||||
getCameraCenterLatLon() {
|
||||
const rect = engine.camera.viewRectangle();
|
||||
if (rect) {
|
||||
const { latitude, longitude } = viewRectangleCenter(rect);
|
||||
return {
|
||||
lat: geo.math.toDegrees(latitude),
|
||||
lon: geo.math.toDegrees(longitude),
|
||||
};
|
||||
}
|
||||
const cartographic = engine.camera.pose()?.cartographic;
|
||||
return cartographic
|
||||
? {
|
||||
lat: geo.math.toDegrees(cartographic.latitude),
|
||||
lon: geo.math.toDegrees(cartographic.longitude),
|
||||
}
|
||||
: null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const lifecycle = {
|
||||
methods: {
|
||||
init() {
|
||||
if (destroyed) throw new Error('Bikeshare renderer is destroyed');
|
||||
state._engine = engine;
|
||||
state._viewer = null;
|
||||
normalSet.setCount(0);
|
||||
selectedSet.setCount(0);
|
||||
normalSet.commit();
|
||||
selectedSet.commit();
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
},
|
||||
enable() {
|
||||
if (destroyed || state._enabled) return;
|
||||
state._enabled = true;
|
||||
state._error = null;
|
||||
this.show();
|
||||
},
|
||||
show() {
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
true,
|
||||
);
|
||||
selectionRemove = selectionDispatcherFor(engine).register(LAYER_ID, {
|
||||
owns: (id) => state._stationRenderMap.has(id),
|
||||
onSelect: (id) => selection._selectStation(id),
|
||||
onEmptyClick: () => selection._clearSelection(),
|
||||
onEscape: () => selection._clearSelection(),
|
||||
});
|
||||
cameraRemove = engine.camera.moveEnd.addEventListener(() =>
|
||||
viewport.onCameraChanged(),
|
||||
);
|
||||
state._cameraChangedAttached = true;
|
||||
void viewport.runProximityCheck();
|
||||
},
|
||||
disable() {
|
||||
if (destroyed) return;
|
||||
state._enabled = false;
|
||||
state._proximityGeneration++;
|
||||
state._altitudeGateEnabled = false;
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = null;
|
||||
selection._clearSelection();
|
||||
state._overlayHost.setVisible(
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
false,
|
||||
);
|
||||
selectionRemove?.();
|
||||
selectionRemove = null;
|
||||
cameraRemove?.();
|
||||
cameraRemove = null;
|
||||
state._cameraChangedAttached = false;
|
||||
parts.ingestion.abortAllInFlight();
|
||||
viewport.deactivateAllCities();
|
||||
state._cityRuntime.clear();
|
||||
normalSet.setCount(0);
|
||||
selectedSet.setCount(0);
|
||||
normalSet.commit();
|
||||
selectedSet.commit();
|
||||
state._count = 0;
|
||||
state._loading = false;
|
||||
state._loadingOps = 0;
|
||||
},
|
||||
detach() {
|
||||
selection._clearSelection();
|
||||
selectionRemove?.();
|
||||
cameraRemove?.();
|
||||
state._cameraChangedAttached = false;
|
||||
normalSet.destroy();
|
||||
selectedSet.destroy();
|
||||
destroyed = true;
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
this.disable();
|
||||
parts.ingestion.abortAllInFlight();
|
||||
normalSet.destroy();
|
||||
selectedSet.destroy();
|
||||
state._stationInfoCache.clear();
|
||||
state._statusCache.clear();
|
||||
state._engine = null;
|
||||
state._viewer = null;
|
||||
destroyed = true;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return { rendering, selection, viewport, lifecycle };
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
|
||||
import { createBikeshareLayer } from '../index.js';
|
||||
import { createBikeshareNavaraRenderer } from './navara.js';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
|
||||
const city = 'austin-capmetro';
|
||||
const key = `${city}:central`;
|
||||
const information = {
|
||||
data: {
|
||||
stations: [
|
||||
{
|
||||
station_id: 'central',
|
||||
name: '中央 / Central',
|
||||
lat: 30.2672,
|
||||
lon: -97.7431,
|
||||
capacity: 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const status = (bikes = 7) => ({
|
||||
data: {
|
||||
stations: [
|
||||
{
|
||||
station_id: 'central',
|
||||
num_bikes_available: bikes,
|
||||
num_docks_available: 10 - bikes,
|
||||
is_installed: true,
|
||||
is_renting: true,
|
||||
is_returning: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
function fixture(getStations) {
|
||||
const engine = createFakeEngine({ kind: 'navara' });
|
||||
engine.fake.setPose({
|
||||
longitude: (-97.7431 * Math.PI) / 180,
|
||||
latitude: (30.2672 * Math.PI) / 180,
|
||||
height: 10000,
|
||||
});
|
||||
engine.fake.script('viewRectangle', null);
|
||||
const entries = new Map();
|
||||
let context, renderer;
|
||||
let bikes = 7;
|
||||
const source = {
|
||||
getStations:
|
||||
getStations ??
|
||||
(async (url) =>
|
||||
url.includes('station_information') ? information : status(bikes)),
|
||||
};
|
||||
const layer = createBikeshareLayer({
|
||||
source,
|
||||
services: {
|
||||
render: { governorRequestRender() {} },
|
||||
overlays: {
|
||||
setOverlayEntries: (id, value) => entries.set(id, value),
|
||||
setOverlaySourceVisible() {},
|
||||
clearOverlaySource: (id) => entries.delete(id),
|
||||
},
|
||||
},
|
||||
rendererFactory(value) {
|
||||
context = value;
|
||||
renderer = createBikeshareNavaraRenderer(engine, value);
|
||||
return renderer;
|
||||
},
|
||||
});
|
||||
layer.init(null, { engine });
|
||||
return {
|
||||
engine,
|
||||
layer,
|
||||
entries,
|
||||
context,
|
||||
renderer,
|
||||
setBikes: (value) => {
|
||||
bikes = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('Navara GBFS loads real parsed stations, picks stable IDs and refreshes a selected status card', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
assert.equal(f.layer.getStats().count, 1);
|
||||
const normal = f.engine.fake.moverSet('bikeshare');
|
||||
const selected = f.engine.fake.moverSet('bikeshare-selected');
|
||||
assert.equal(normal.options.sharpen, true);
|
||||
assert.equal(selected.options.sharpen, true);
|
||||
assert.equal(normal.store.pickIds[0], key);
|
||||
assert.deepEqual(
|
||||
normal.options.point.translucencyByDistance,
|
||||
[200, 1, 180000, 0.15],
|
||||
);
|
||||
assert.equal(selected.options.point.scaleByDistance, null);
|
||||
assert.deepEqual(selected.options.point.outlineColor, [0, 0, 0, 1]);
|
||||
f.engine.fake.script('pick', { id: key });
|
||||
f.engine.fake.input('click', { position: { x: 100, y: 100 } });
|
||||
assert.equal(selected.store.count, 1);
|
||||
assert.equal(normal.store.shows[0], 0);
|
||||
assert.equal(
|
||||
f.entries.get('bikeshare-selected')[0].title,
|
||||
'中央 / Central',
|
||||
);
|
||||
f.setBikes(2);
|
||||
await f.layer.update();
|
||||
assert.match(f.entries.get('bikeshare-selected')[0].details[0], /2 avail/);
|
||||
assert.equal(f.layer.getAnalystRecords()[0].bikesAvailable, 2);
|
||||
f.engine.fake.script('pick', null);
|
||||
f.engine.fake.input('click', { position: { x: 100, y: 100 } });
|
||||
assert.equal(selected.store.count, 0);
|
||||
assert.equal(normal.store.shows[0], 1);
|
||||
assert.equal(f.entries.size, 0);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('camera callbacks preserve hysteresis and ten enable/disable cycles leave no owned data or listeners', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
for (let cycle = 0; cycle < 10; cycle++) {
|
||||
f.layer.enable();
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
assert.equal(f.layer.getStats().count, 1);
|
||||
f.engine.fake.emit('camera.moveEnd');
|
||||
assert.ok(f.context.state._cameraDebounceTimer);
|
||||
f.layer.disable();
|
||||
assert.equal(f.context.state._cameraDebounceTimer, null);
|
||||
assert.equal(f.context.state._cameraChangedAttached, false);
|
||||
assert.equal(f.layer.getStats().count, 0);
|
||||
assert.deepEqual(f.layer.getDetectableObjects(), []);
|
||||
assert.equal(f.engine.fake.moverSet('bikeshare').store.count, 0);
|
||||
f.engine.fake.emit('camera.moveEnd');
|
||||
assert.equal(f.context.state._cameraDebounceTimer, null);
|
||||
}
|
||||
const gate = f.renderer.viewport.shouldActivateAtAltitude;
|
||||
assert.equal(gate(49000), false);
|
||||
assert.equal(gate(48000), true);
|
||||
assert.equal(gate(51000), true);
|
||||
assert.equal(gate(52000), false);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
f.layer.destroy();
|
||||
}
|
||||
assert.deepEqual(f.engine.movers.list(), []);
|
||||
});
|
||||
|
||||
test('an aborted response cannot repopulate caches or clear a newer request loading state', async () => {
|
||||
const pending = [];
|
||||
const f = fixture(
|
||||
(url, { signal }) =>
|
||||
new Promise((resolve) => pending.push({ url, signal, resolve })),
|
||||
);
|
||||
f.layer.enable();
|
||||
assert.equal(pending.length, 1);
|
||||
f.layer.disable();
|
||||
assert.equal(pending[0].signal.aborted, true);
|
||||
f.layer.enable();
|
||||
assert.equal(pending.length, 2);
|
||||
pending[0].resolve(information);
|
||||
await settle();
|
||||
assert.equal(f.context.state._stationInfoCache.size, 0);
|
||||
assert.equal(f.layer.getStats().loading, true);
|
||||
f.layer.destroy();
|
||||
pending[1].resolve(information);
|
||||
await settle();
|
||||
assert.equal(f.context.state._stationInfoCache.size, 0);
|
||||
assert.equal(f.layer.getStats().count, 0);
|
||||
assert.deepEqual(f.engine.movers.list(), []);
|
||||
});
|
||||
|
||||
test('station positions sample the visible surface with own point sets excluded', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
f.engine.fake.script('sampleHeight', 175);
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
const point = f.layer.getDetectableObjects()[0].position;
|
||||
const height = geo.cartographic.fromCartesian(point).height;
|
||||
assert.ok(Math.abs(height - 177) < 1e-6);
|
||||
const call = f.engine.fake.callsOf('surface.sampleHeight')[0];
|
||||
assert.deepEqual(
|
||||
call.args[1].map((set) => set.id),
|
||||
['bikeshare', 'bikeshare-selected'],
|
||||
);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('a Navara station without a published capacity re-derives it from every status poll', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
f.layer.enable();
|
||||
await settle();
|
||||
const { rendering } = f.renderer;
|
||||
const { model } = f.context.parts;
|
||||
const info = model.parseStationInformation({
|
||||
data: {
|
||||
stations: [
|
||||
{ station_id: 'open', name: 'Open', lat: 30.26, lon: -97.74 },
|
||||
],
|
||||
},
|
||||
});
|
||||
rendering.ensureCityPoints(city, info);
|
||||
const poll = (stations) =>
|
||||
rendering.applyStatusToPoints(
|
||||
city,
|
||||
model.parseStationStatus({ data: { stations } }),
|
||||
);
|
||||
const open = f.context.state._stationRenderMap.get(`${city}:open`);
|
||||
poll([
|
||||
{ station_id: 'open', num_bikes_available: 10, num_docks_available: 20 },
|
||||
]);
|
||||
assert.equal(open.capacity, 30);
|
||||
poll([
|
||||
{ station_id: 'open', num_bikes_available: 4, num_docks_available: 2 },
|
||||
]);
|
||||
assert.equal(open.capacity, 6, 'the second poll is not pinned to 30');
|
||||
assert.equal(
|
||||
f.context.state._stationRenderMap.get(key).capacity,
|
||||
10,
|
||||
'a published capacity is kept',
|
||||
);
|
||||
} finally {
|
||||
f.layer.destroy();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// How the bikeshare stations draw (engine.movers point sets).
|
||||
|
||||
import { CYAN } from '../../shared/color.js';
|
||||
import { COLOR_OUTLINE } from '../policy.js';
|
||||
|
||||
export const STATION_SET_ID = 'bikeshare';
|
||||
export const SELECTED_SET_ID = 'bikeshare-selected';
|
||||
|
||||
/**
|
||||
* A station's disc: sizePx times the point's scale (its capacity's pixel
|
||||
* size over sizePx), a faint outline, larger and opaque up close, smaller
|
||||
* and fading out with distance.
|
||||
*/
|
||||
export const STATION_POINT = Object.freeze({
|
||||
sizePx: 8,
|
||||
outlinePx: 1,
|
||||
outlineColor: COLOR_OUTLINE.rgba(),
|
||||
scaleByDistance: Object.freeze([200, 1.35, 130000, 0.4]),
|
||||
translucencyByDistance: Object.freeze([200, 1, 180000, 0.15]),
|
||||
});
|
||||
|
||||
/** On top within this distance of the camera, depth tested beyond. */
|
||||
export const STATION_DEPTH_TEST = Object.freeze({ disableWithinM: 2500 });
|
||||
|
||||
/** The selected station's highlight: a fixed-size cyan disc. */
|
||||
export const SELECTED_POINT = Object.freeze({
|
||||
sizePx: 14,
|
||||
outlinePx: 2,
|
||||
outlineColor: [0, 0, 0, 1],
|
||||
});
|
||||
export const SELECTED_COLOR = CYAN;
|
||||
Reference in new issue
Block a user