feat(bikeshare): render GBFS stations on Navara

This commit is contained in:
German Khokhlov committed 2026-10-28 13:12:19 +04:00
1 parent 1a694baf5a
commit d82a6f1550
32 files changed
+1394 -278

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
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),
};
}
@@ -0,0 +1,192 @@
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,
}) {
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._enabled = false;
layerState._cameraDebounceTimer = null;
layerState._cameraChangedAttached = false;
layerState._altitudeGateEnabled = false;
layerState._proximityGeneration = 0;
layerState._activeCityIds = new Set();
layerState._cityRuntime = new Map();
layerState._stationInfoCache = new Map();
layerState._statusCache = new Map();
layerState._inFlightInfo = new Map();
layerState._inFlightStatus = new Map();
layerState._stationRenderMap = new Map();
layerState._clickHandler = null;
layerState._selectedKey = null;
layerState._selectedEntity = null;
layerState._count = 0;
layerState._lastUpdate = null;
layerState._loading = false;
layerState._loadingOps = 0;
layerState._error = null;
layerState._limitWarned = 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;
viewer = layerState._viewer;
layerState._enabled = true;
layerState._error = null;
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(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(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;
},
/** 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(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 };
}
@@ -0,0 +1,55 @@
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);
});
@@ -0,0 +1,214 @@
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';
export function createRendering({
state: layerState,
services,
parts,
source,
}) {
const { governorRequestRender } = services.render;
/**
* 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);
}
/**
* 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({
position,
pixelSize: capacityToPixelSize(station.capacity),
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: key,
});
layerState._stationRenderMap.set(key, {
key,
cityId,
stationId: station.stationId,
stationName: station.name,
point,
capacity: 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;
const capacity = resolveCapacity(parts.model, record.capacity, 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,
};
}
@@ -0,0 +1,150 @@
import * as Cesium from 'cesium';
import { isPointerFree } from '../../../../data/inputOwnership.js';
import {
buildBikeshareSelectionLabel,
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,
buildSelectionLabel: buildBikeshareSelectionLabel,
createBikeshareSelectedOverlayEntry,
_clearSelection,
_selectStation,
_installClickHandler,
_onKeyDown,
};
}
@@ -0,0 +1,54 @@
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 },
});
}
+408
View File
@@ -0,0 +1,408 @@
import * as geo from '../../../geo/index.js';
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
import { CYAN } from '../../shared/color.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,
resolveCapacity,
statusToColor,
} from '../presentation.js';
import {
buildBikeshareSelectionLabel,
createBikeshareSelectedOverlayEntry,
} from '../selectionModel.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) {
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,
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 = {
resolveCapacity: (capacity, status) =>
resolveCapacity(parts.model, capacity, status),
capacityToPixelSize,
statusToColor: (status, capacity) =>
statusToColor(parts.model, status, capacity),
createStationPosition(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);
},
ensureCityRuntime(cityId) {
let runtime = state._cityRuntime.get(cityId);
if (!runtime) {
runtime = { stationKeys: new Set() };
state._cityRuntime.set(cityId, runtime);
}
return runtime;
},
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),
bikesAvailable: null,
docksAvailable: null,
isInstalled: station.isInstalled,
isRenting: station.isRenting,
isReturning: station.isReturning,
};
state._stationRenderMap.set(key, record);
runtime.stationKeys.add(key);
syncPoint(record);
}
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;
record.capacity = resolveCapacity(parts.model, record.capacity, 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();
},
};
const selection = {
buildSelectionLabel(record) {
return buildBikeshareSelectionLabel(record);
},
createBikeshareSelectedOverlayEntry,
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');
},
_installClickHandler() {},
_onKeyDown(event) {
if (event.key === 'Escape' && state._selectedKey) this._clearSelection();
},
};
const viewport = createViewport({
...context,
camera: {
getCameraAltitude: () => engine.camera.height(),
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;
return {
lat: geo.math.toDegrees((rect.south + rect.north) / 2),
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;
state._enabled = false;
state._cameraDebounceTimer = null;
state._cameraChangedAttached = false;
state._altitudeGateEnabled = false;
state._proximityGeneration = 0;
state._activeCityIds = new Set();
state._cityRuntime = new Map();
state._stationInfoCache = new Map();
state._statusCache = new Map();
state._inFlightInfo = new Map();
state._inFlightStatus = new Map();
state._stationRenderMap = new Map();
state._clickHandler = null;
state._selectedKey = null;
state._selectedEntity = null;
state._count = 0;
state._lastUpdate = null;
state._loading = false;
state._loadingOps = 0;
state._error = null;
state._limitWarned = false;
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;
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;
},
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 };
}
+196
View File
@@ -0,0 +1,196 @@
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();
}
});