mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-19 09:42:21 +00:00
Flight trails register their ids so every layer reads a trail click as a
no-op, and the directions route claims its line and markers though it acts
only on its maneuver steps. The quake card and magnitude labels yielded to
any registered owner, so over a trail or a route they did nothing. Pick
owners can now name the picks they never act on (registerPickOwner(...,
{ passive })); isActedOnByOtherLayer leaves those out while
isOwnedByOtherLayer is unchanged, so they are still not empty space.
Submarine cables and rocket launches acted on any scene pick, so a card or
label over a cable or a launch marker made both layers act. Both now stand
aside when a world-overlay entry is under the click, as drone airspace and
fire perimeters do through the top-entry check. Each of these layers, and
the quake discs, registers its shapes with registerCardBackground. CCTV
asks isCardBackground instead of matching other layers' set and id formats,
so a live top CCTV card acts once over any of them, while unknown
identified objects and registered owners still block it.
499 lines
16 KiB
JavaScript
499 lines
16 KiB
JavaScript
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||
import { drawOf } from '../../render/rendererOf.js';
|
||
import { hexColor } from '../../render/color.js';
|
||
import {
|
||
PERIMETER_OVERLAY_SOURCE_ID,
|
||
perimeterAnchorDegrees,
|
||
buildIncidentCard,
|
||
containmentAccent,
|
||
} from './cards.js';
|
||
import {
|
||
findInciwebLink,
|
||
inciwebNodeId,
|
||
isCurrentPublication,
|
||
} from './inciweb.js';
|
||
import { msg, t } from '../../i18n/index.js';
|
||
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
|
||
export { normalizeFirePerimeterSnapshot } from './records.js';
|
||
export { createWfigsPerimeterSource } from './source.js';
|
||
export * from './cards.js';
|
||
export * from './inciweb.js';
|
||
|
||
/**
|
||
* Fill/line colour for a perimeter by containment progress (same ramp as the
|
||
* card accent), as a renderer colour `[r, g, b, a]`.
|
||
*/
|
||
export function containmentColor(containedPct) {
|
||
return hexColor(containmentAccent(containedPct));
|
||
}
|
||
|
||
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
|
||
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
|
||
|
||
/**
|
||
* The draw sets the perimeters are drawn in start with this; each layer has
|
||
* its own (`fire-perimeters:1:fills`, …), so several can share a renderer.
|
||
* Picks name them as `Hit.set`.
|
||
*/
|
||
export const PERIMETER_SET_PREFIX = 'fire-perimeters';
|
||
let instances = 0;
|
||
|
||
const PICK_PREFIX = 'fire-perimeter:';
|
||
const CARD_HOST_OPTIONS = Object.freeze({
|
||
cohortLimit: 1,
|
||
collisionCapacity: 1,
|
||
moving: false,
|
||
});
|
||
// The InciWeb catalog changes on the order of days; refreshing it on the
|
||
// 5-minute perimeter cadence would hammer a public .gov endpoint for ~200 KB
|
||
// of near-identical bytes.
|
||
const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
|
||
|
||
/**
|
||
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
|
||
*
|
||
* Each perimeter is a ground-clamped fill in one renderer draw set and its
|
||
* fire line a draped line in another (`drawOf(viewer)`), made at `init`.
|
||
* Given a Cesium viewer with no renderer bound, the
|
||
* caller loads the package's `./render/cesium/unbound` export first.
|
||
*/
|
||
export function createFirePerimetersLayer({
|
||
source,
|
||
overlayHost = null,
|
||
inputFor = defaultInputFor,
|
||
picking = null,
|
||
inciwebSource = null,
|
||
inciwebPublications = null,
|
||
openExternal = null,
|
||
} = {}) {
|
||
if (typeof source?.getSnapshot !== 'function')
|
||
throw new TypeError('Fire perimeters require a snapshot source');
|
||
let _viewer = null;
|
||
let _request = null;
|
||
let _linkRequest = null;
|
||
let _snapshotSignature = null;
|
||
let _fills = null;
|
||
let _lines = null;
|
||
let _setIds = new Set();
|
||
let _count = 0;
|
||
let _lastUpdate = null;
|
||
// The proxy's last snapshot, served while WFIGS is unreachable.
|
||
let _stale = false;
|
||
let _lastError = null;
|
||
let _enabled = false;
|
||
let _clickSubscription = null;
|
||
let _selectedId = null;
|
||
let _selectedLink = null;
|
||
let _selectedCardId = null;
|
||
let _inciwebIndex = [];
|
||
let _indexFetchedAt = 0;
|
||
let _indexFetchInFlight = false;
|
||
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
|
||
const _rowById = new Map();
|
||
// Link → currency verdict from the publication check; unknown links are
|
||
// absent. Failed checks are not cached so a transient outage retries.
|
||
const _linkVerdicts = new Map();
|
||
function abortLinkVerification() {
|
||
_linkRequest?.controller.abort();
|
||
_linkRequest = null;
|
||
}
|
||
|
||
const canSelect = () => overlayHost && inputFor && picking;
|
||
|
||
/**
|
||
* Refresh the InciWeb catalog off the render path: a hanging or failed
|
||
* fetch only costs the link line, never the perimeter refresh — the
|
||
* catalog is consumed solely by the selected card.
|
||
*/
|
||
function refreshInciwebIndex(signal) {
|
||
if (!inciwebSource || _indexFetchInFlight) return;
|
||
if (Date.now() - _indexFetchedAt < INCIWEB_INDEX_TTL_MS) return;
|
||
_indexFetchInFlight = true;
|
||
inciwebSource
|
||
.getIndex({ signal })
|
||
.then((rows) => {
|
||
if (signal.aborted || !_enabled || !Array.isArray(rows)) return;
|
||
_inciwebIndex = rows;
|
||
_indexFetchedAt = Date.now();
|
||
if (_selectedId) publishSelectedCard();
|
||
})
|
||
.catch(() => {
|
||
// Catalog unavailable — cards stay linkless until the next attempt.
|
||
})
|
||
.finally(() => {
|
||
_indexFetchInFlight = false;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Verify that a matched publication describes the current incident, not
|
||
* an archived same-name fire — the catalog is all-time. Async: the card
|
||
* republishes with the link once (and only if) the check passes.
|
||
*/
|
||
function verifyLink(link, row) {
|
||
const id = inciwebNodeId(link);
|
||
if (!id || !inciwebPublications || _linkRequest?.link === link) return;
|
||
abortLinkVerification();
|
||
const request = { link, controller: new AbortController() };
|
||
_linkRequest = request;
|
||
const { signal } = request.controller;
|
||
inciwebPublications
|
||
.getPublication(id, { signal })
|
||
.then((publication) => {
|
||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||
_linkVerdicts.set(
|
||
link,
|
||
isCurrentPublication(publication, {
|
||
discoveredTime: row.discoveredTime,
|
||
}),
|
||
);
|
||
if (_selectedId === row.stableId) publishSelectedCard();
|
||
})
|
||
.catch(() => {
|
||
// Fail closed without caching: no link now, retry on reselection.
|
||
})
|
||
.finally(() => {
|
||
if (_linkRequest === request) _linkRequest = null;
|
||
});
|
||
}
|
||
|
||
function publishSelectedCard() {
|
||
if (!canSelect()) return;
|
||
const row = _selectedId ? _rowById.get(_selectedId) : null;
|
||
if (!row) {
|
||
_selectedId = null;
|
||
_selectedLink = null;
|
||
_selectedCardId = null;
|
||
overlayHost.setEntries(
|
||
PERIMETER_OVERLAY_SOURCE_ID,
|
||
[],
|
||
CARD_HOST_OPTIONS,
|
||
);
|
||
return;
|
||
}
|
||
const candidate = findInciwebLink(_inciwebIndex, row);
|
||
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
|
||
_selectedLink =
|
||
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
|
||
const card = {
|
||
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
|
||
position: fromDegrees(row.anchor.lon, row.anchor.lat),
|
||
};
|
||
if (!openExternal) card.interactive = false;
|
||
if (_selectedLink && openExternal) {
|
||
const link = _selectedLink;
|
||
// Keyboard/assistive activation mirrors the pointer click-through.
|
||
card.activate = () => {
|
||
openExternal(link);
|
||
return true;
|
||
};
|
||
}
|
||
_selectedCardId = card.id;
|
||
overlayHost.setEntries(
|
||
PERIMETER_OVERLAY_SOURCE_ID,
|
||
[card],
|
||
CARD_HOST_OPTIONS,
|
||
);
|
||
}
|
||
|
||
/**
|
||
* The incident a click's draw hit (`Hit`, query.d.ts) belongs to: an item
|
||
* of this layer's own sets, for an incident drawn now; else null.
|
||
*/
|
||
function pickedIncidentId(hit) {
|
||
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
|
||
if (typeof hit.id !== 'string' || !hit.id.startsWith(PICK_PREFIX))
|
||
return null;
|
||
const incidentId = hit.id.slice(PICK_PREFIX.length).split(':')[0];
|
||
return _rowById.has(incidentId) ? incidentId : null;
|
||
}
|
||
|
||
function installClickHandler() {
|
||
if (!canSelect() || _clickSubscription || !_viewer) return;
|
||
// Deliberately NOT registered in the pick-ownership registry: sibling
|
||
// layers yield to owned picks before their own overlay-card hit-tests,
|
||
// so claiming these large ground polygons would make FIRMS/vessel/CCTV
|
||
// cards inert anywhere over a perimeter. Unowned, our picks read as
|
||
// "empty space" to siblings — the pre-existing behavior for the globe.
|
||
// Our shapes stand aside for a card painted over them (below), so that
|
||
// card's layer may act on the click; without a hit-test they cannot.
|
||
if (overlayHost?.hitTest)
|
||
picking?.registerCardBackground?.(
|
||
layer.id,
|
||
(hit) => pickedIncidentId(hit) !== null,
|
||
);
|
||
_clickSubscription = inputFor(_viewer).onClick((event) => {
|
||
// A click on the incident card itself opens its InciWeb page (when the
|
||
// incident has one) and never disturbs the selection.
|
||
const cardHit = overlayHost.hitTest?.(
|
||
event.screenPosition?.x,
|
||
event.screenPosition?.y,
|
||
);
|
||
// Only the top painted card owns the click; this area's shapes are
|
||
// background when another layer has painted a card or label over them.
|
||
if (cardHit && cardHit.sourceId !== PERIMETER_OVERLAY_SOURCE_ID) return;
|
||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||
return;
|
||
}
|
||
const picked = event.topHit;
|
||
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
|
||
if (incidentId) {
|
||
abortLinkVerification();
|
||
_selectedId = incidentId;
|
||
publishSelectedCard();
|
||
return;
|
||
}
|
||
// A pick that belongs to a sibling layer (e.g. an aircraft) is not
|
||
// "empty space" — leave the selection alone and let that layer handle it.
|
||
if (picked) {
|
||
const pickId = picking.resolvePickId(picked);
|
||
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
|
||
}
|
||
if (_selectedId) {
|
||
abortLinkVerification();
|
||
_selectedId = null;
|
||
publishSelectedCard();
|
||
}
|
||
});
|
||
}
|
||
|
||
function removeClickHandler() {
|
||
_clickSubscription?.();
|
||
_clickSubscription = null;
|
||
picking?.unregisterCardBackground?.(layer.id);
|
||
}
|
||
|
||
function clearSelection() {
|
||
abortLinkVerification();
|
||
_selectedId = null;
|
||
_selectedLink = null;
|
||
_selectedCardId = null;
|
||
if (overlayHost) {
|
||
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
|
||
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
|
||
}
|
||
}
|
||
|
||
const layer = {
|
||
id: 'fire-perimeters',
|
||
name: 'Fire Perimeters',
|
||
icon: '🔥',
|
||
source: 'NIFC WFIGS',
|
||
updateInterval: 300000,
|
||
|
||
init(viewer) {
|
||
if (_viewer)
|
||
throw new Error('Fire perimeter layer is already initialized');
|
||
const draw = drawOf(viewer);
|
||
const prefix = `${PERIMETER_SET_PREFIX}:${++instances}`;
|
||
_fills = draw.shapes({
|
||
id: `${prefix}:fills`,
|
||
clampTo: 'both',
|
||
show: false,
|
||
});
|
||
_lines = draw.lines({
|
||
id: `${prefix}:lines`,
|
||
clampTo: 'both',
|
||
show: false,
|
||
});
|
||
_setIds = new Set([_fills.id, _lines.id]);
|
||
_viewer = viewer;
|
||
_count = 0;
|
||
_lastUpdate = null;
|
||
_lastError = null;
|
||
_stale = false;
|
||
_enabled = false;
|
||
console.log('[Data:FirePerimeters] Initialized');
|
||
},
|
||
|
||
enable() {
|
||
_enabled = true;
|
||
if (_fills) _fills.show = _lines.show = true;
|
||
overlayHost?.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, true);
|
||
installClickHandler();
|
||
},
|
||
|
||
disable() {
|
||
_request?.abort();
|
||
_request = null;
|
||
_enabled = false;
|
||
if (_fills) _fills.show = _lines.show = false;
|
||
removeClickHandler();
|
||
clearSelection();
|
||
},
|
||
|
||
async update() {
|
||
if (!_enabled || !_fills) return false;
|
||
_request?.abort();
|
||
const request = new AbortController();
|
||
_request = request;
|
||
refreshInciwebIndex(request.signal);
|
||
try {
|
||
// The source contract is getSnapshot; a source that can also say how
|
||
// fresh its rows are (the WFIGS proxy) offers getSnapshotDetail.
|
||
const snapshot =
|
||
typeof source.getSnapshotDetail === 'function'
|
||
? await source.getSnapshotDetail({ signal: request.signal })
|
||
: { rows: await source.getSnapshot({ signal: request.signal }) };
|
||
if (request.signal.aborted || _request !== request || !_enabled)
|
||
return false;
|
||
const { rows } = snapshot;
|
||
_stale = snapshot.stale === true;
|
||
// A stale snapshot is as old as its fetch, not this poll.
|
||
const updatedAt =
|
||
_stale && Number.isFinite(snapshot.fetchedAt)
|
||
? snapshot.fetchedAt
|
||
: Date.now();
|
||
|
||
// Incident facts may change independently of the polygon's source clock.
|
||
const signature = JSON.stringify(
|
||
rows
|
||
.map(({ polygons, ...facts }) => facts)
|
||
.sort((a, b) => a.stableId.localeCompare(b.stableId)),
|
||
);
|
||
if (signature === _snapshotSignature) {
|
||
if (_selectedId) publishSelectedCard();
|
||
_lastUpdate = updatedAt;
|
||
_lastError = null;
|
||
return true;
|
||
}
|
||
abortLinkVerification();
|
||
const nextFills = [];
|
||
const nextLines = [];
|
||
_rowById.clear();
|
||
for (const row of rows) {
|
||
const color = containmentColor(row.containedPct);
|
||
for (const [index, rings] of row.polygons.entries()) {
|
||
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
|
||
// Each exterior keeps its own holes.
|
||
nextFills.push({
|
||
id,
|
||
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
|
||
fill: withAlpha(color, 0.25),
|
||
height: 'clampGround',
|
||
});
|
||
// The fire line: the exterior ring draped on the ground (lines
|
||
// take ECEF, draw.d.ts `LineItem`).
|
||
nextLines.push({
|
||
id,
|
||
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
|
||
widthPx: 2,
|
||
mode: 'draped',
|
||
style: { kind: 'solid', color: withAlpha(color, 0.9) },
|
||
});
|
||
}
|
||
// Keep a geometry-free projection: the coordinate arrays would
|
||
// otherwise be retained for the layer's lifetime while only the
|
||
// anchor is ever read again.
|
||
const { polygons, ...facts } = row;
|
||
_rowById.set(row.stableId, {
|
||
...facts,
|
||
anchor: perimeterAnchorDegrees(polygons),
|
||
});
|
||
}
|
||
|
||
_fills.set(nextFills);
|
||
_lines.set(nextLines);
|
||
_snapshotSignature = signature;
|
||
// Refresh (or drop) the selected incident's card against the new feed.
|
||
if (_selectedId) publishSelectedCard();
|
||
_count = rows.length;
|
||
_lastUpdate = updatedAt;
|
||
_lastError = null;
|
||
console.log(
|
||
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
|
||
);
|
||
return true;
|
||
} catch (e) {
|
||
if (request.signal.aborted || _request !== request || !_enabled)
|
||
return false;
|
||
console.warn('[Data:FirePerimeters] Fetch error:', e);
|
||
_lastError = e?.message || msg('Perimeter source unavailable');
|
||
// A failure now outranks the stale snapshot still drawn.
|
||
_stale = false;
|
||
return false;
|
||
} finally {
|
||
if (_request === request) _request = null;
|
||
}
|
||
},
|
||
|
||
destroy() {
|
||
_request?.abort();
|
||
_request = null;
|
||
removeClickHandler();
|
||
clearSelection();
|
||
_rowById.clear();
|
||
_snapshotSignature = null;
|
||
_inciwebIndex = [];
|
||
_indexFetchedAt = 0;
|
||
_linkVerdicts.clear();
|
||
_viewer = null;
|
||
_enabled = false;
|
||
_fills?.dispose();
|
||
_lines?.dispose();
|
||
_fills = _lines = null;
|
||
_setIds = new Set();
|
||
_count = 0;
|
||
_lastUpdate = null;
|
||
_lastError = null;
|
||
_stale = false;
|
||
},
|
||
|
||
/** Snapshot incident facts (with card-anchor coordinates) for the analyst query engine. */
|
||
getAnalystRecords(maxCount = 2000) {
|
||
if (!_fills || !_fills.show) return [];
|
||
const limit = Number.isFinite(maxCount)
|
||
? Math.max(1, Math.floor(maxCount))
|
||
: 2000;
|
||
const result = [];
|
||
for (const row of _rowById.values()) {
|
||
if (result.length >= limit) break;
|
||
const { anchor, stableId, ...facts } = row;
|
||
result.push({
|
||
id: stableId,
|
||
...facts,
|
||
lat: anchor.lat,
|
||
lon: anchor.lon,
|
||
});
|
||
}
|
||
return result;
|
||
},
|
||
|
||
getRowControls() {
|
||
const bands = [
|
||
{ label: t('Not contained or unknown'), color: containmentAccent(0) },
|
||
{ label: t('Under 50% contained'), color: containmentAccent(1) },
|
||
{ label: t('50–99% contained'), color: containmentAccent(50) },
|
||
{ label: t('Fully contained'), color: containmentAccent(100) },
|
||
];
|
||
return {
|
||
chips: [],
|
||
legend: bands.map((band, index) => ({
|
||
...band,
|
||
count: [..._rowById.values()].filter(
|
||
(row) => containmentAccent(row.containedPct) === band.color,
|
||
).length,
|
||
...(index === 0
|
||
? {
|
||
blurb: t(
|
||
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
|
||
),
|
||
}
|
||
: {}),
|
||
})),
|
||
};
|
||
},
|
||
|
||
getStats() {
|
||
return {
|
||
count: _count,
|
||
lastUpdate: _lastUpdate,
|
||
error: _lastError,
|
||
stale: _stale,
|
||
};
|
||
},
|
||
};
|
||
return layer;
|
||
}
|