feat(perimeters): colour fire perimeters by age

The Fire Perimeters layer now draws a snapshot of fires and the pieces of
their burned area, each piece coloured by its age at the snapshot's moment
(under 6 h, 6-24 h, 1-3 days, older or unknown). Containment stays on the
card; the legend counts fires by last growth and shows the source's note.

- One source method, getSnapshot, returning {at, fetchedAt, stale,
  revision, note, fires, pieces}; getSnapshotDetail is removed.
- WFIGS: one piece per polygon, born at poly_PolygonDateTime, else
  poly_DateCurrent; a time more than 10 minutes ahead is unknown.
- Outlines are drawn apart from fills, so cut pieces have no line along
  the cut; redraws happen only on a new revision or a change of age band.
- The card ages from `at` and adds "last growth ... ago"; with a past
  `at` it links only to an InciWeb incident that began by then.
- perimeterOptions: { inciweb: false } creates no InciWeb sources.
- get_fire_perimeters filters by pieces, places fires at their anchor and
  returns last_growth; analyst items carry lastGrowthTime; spot
  conditions use the anchor.
This commit is contained in:
German Khokhlov committed 2026-11-23 15:48:54 +04:00
1 parent e51853de3d
commit d303d48693
48 files changed
+2127 -734

No files matched your search

+277 -143
View File
@@ -1,34 +1,64 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { hexColor } from '../../render/color.js';
import { drawOf } from '../../render/rendererOf.js';
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
import {
PERIMETER_OVERLAY_SOURCE_ID,
perimeterAnchorDegrees,
buildIncidentCard,
containmentAccent,
} from './cards.js';
import {
findInciwebLink,
findInciwebLinks,
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 {
normalizeFirePerimeterSnapshot,
perimeterAnchorDegrees,
} from './records.js';
export { createWfigsPerimeterSource } from './source.js';
export * from './cards.js';
export * from './inciweb.js';
const HOUR_MS = 3600000;
/**
* Fill/line colour for a perimeter by containment progress (same ramp as the
* card accent), as a renderer colour `[r, g, b, a]`.
* Piece colours by age, newest first. A piece of unknown birth, or born after
* the moment shown, is drawn as the oldest; the legend counts fires by
* `lastGrowthTime` the same way.
*/
export function containmentColor(containedPct) {
return hexColor(containmentAccent(containedPct));
export const PERIMETER_AGE_BANDS = Object.freeze(
[
{ upToMs: 6 * HOUR_MS, color: '#ffc72e', label: msg('Last 6 hours') },
{ upToMs: 24 * HOUR_MS, color: '#ff730d', label: msg('6–24 hours') },
{ upToMs: 72 * HOUR_MS, color: '#d9290d', label: msg('1–3 days') },
{
upToMs: Infinity,
color: '#730f0a',
label: msg('Older or unknown'),
},
].map((band) => Object.freeze(band)),
);
function perimeterAgeBand(time, atMs) {
const last = PERIMETER_AGE_BANDS.length - 1;
if (!Number.isFinite(time) || time > atMs) return last;
return PERIMETER_AGE_BANDS.findIndex(({ upToMs }) => atMs - time < upToMs);
}
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
const FILL_ALPHA = 0.35;
const LINE_ALPHA = 0.9;
const LINE_WIDTH_PX = 2;
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
const validLine = (line, min) =>
Array.isArray(line) &&
line.length >= min &&
line.every(
(point) =>
Array.isArray(point) &&
Number.isFinite(point[0]) &&
Number.isFinite(point[1]),
);
const validAnchor = (anchor) =>
Number.isFinite(anchor?.lon) && Number.isFinite(anchor?.lat);
/**
* The draw sets the perimeters are drawn in start with this; each layer has
@@ -52,10 +82,29 @@ 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.
* `source.getSnapshot({signal})` resolves to the snapshot the layer draws
* (records.js `firePerimeterSnapshot` builds it from WFIGS):
* - `at`: the moment shown, epoch ms, or null for now. Ages, colours and the
* legend count from it.
* - `fetchedAt` (epoch ms or null) and `stale`: a stale snapshot is dated by
* its `fetchedAt`.
* - `revision`: a string that changes whenever any piece does. Without a
* string revision the layer redraws on every read.
* - `note`: text the layer row shows with the legend, or null.
* - `fires`: `id` (string), `anchor` (`{lon, lat}` degrees, where the card
* stands), `lastGrowthTime` (epoch ms or null; the legend counts by it) and
* the card facts (`name`, `acres`, `containedPct`, `state`,
* `discoveredTime`, `updatedTime`, …). A fire without an id or anchor is
* dropped. A fire may have no pieces: it keeps its card and legend count.
* - `pieces`: `fireId` (a listed fire's id; any other piece is dropped),
* `born` (epoch ms or null; the piece's colour), `polygons` (each
* `[outer, ...holes]`, rings of `[lon, lat]`) and `outline` (lines of
* `[lon, lat]` drawn as the fire line, apart from the fill, so a piece cut
* from a larger area has no line along the cut).
*
* When to read again (a timeline, the camera) is the host's call, through
* the manager's `refreshLayer`. Given a Cesium viewer with no renderer bound,
* the caller loads the package's `./render/cesium/unbound` export first.
*/
export function createFirePerimetersLayer({
source,
@@ -71,12 +120,17 @@ export function createFirePerimetersLayer({
let _viewer = null;
let _request = null;
let _linkRequest = null;
let _snapshotSignature = null;
// What the sets show: the snapshot revision and each piece's age band.
let _drawnKey = null;
let _fills = null;
let _lines = null;
let _setIds = new Set();
let _count = 0;
let _lastUpdate = null;
// The moment the snapshot shows (null: now), and the source's legend note.
let _at = null;
let _note = null;
// The moment the drawn colours were computed at; the legend counts at it
// too, so it matches the map between reads.
let _bandsAt = null;
// The proxy's last snapshot, served while WFIGS is unreachable.
let _stale = false;
let _lastError = null;
@@ -88,16 +142,26 @@ export function createFirePerimetersLayer({
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();
let _fireById = new Map();
/** `<set id>\n<item id>` → the fire that item belongs to. */
const _fireByItem = new Map();
const shownAt = () => _at ?? Date.now();
const _linkPublications = new Map();
// Retry failed pages on reselection or when a read finds the card linkless.
const _linkFailures = new Set();
function abortLinkVerification() {
_linkRequest?.controller.abort();
_linkRequest = null;
}
function resetSelection() {
abortLinkVerification();
_linkFailures.clear();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
}
const canSelect = () => overlayHost && inputFor && picking;
/**
@@ -141,29 +205,57 @@ export function createFirePerimetersLayer({
.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();
_linkPublications.set(link, publication ?? {});
if (_selectedId === row.id) publishSelectedCard();
})
.catch(() => {
// Fail closed without caching: no link now, retry on reselection.
if (signal.aborted || _linkRequest !== request || !_enabled) return;
_linkFailures.add(link);
if (_selectedId === row.id) publishSelectedCard();
})
.finally(() => {
if (_linkRequest === request) _linkRequest = null;
});
}
function isCurrentLink(publication, row) {
if (
_at !== null &&
!(Number.isFinite(publication.createdMs) && publication.createdMs <= _at)
)
return false;
return isCurrentPublication(publication, {
discoveredTime: row.discoveredTime,
nowMs: shownAt(),
});
}
/**
* The current page among verified candidates: the one whose incident began
* nearest the fire's discovery, else (no discovery date) the newest.
*/
function chooseLink(links, row) {
let best = null;
let bestGap = Infinity;
for (const link of links) {
const publication = _linkPublications.get(link);
if (!publication || !isCurrentLink(publication, row)) continue;
const gap = Number.isFinite(row.discoveredTime)
? Math.abs(publication.createdMs - row.discoveredTime)
: 0;
if (best === null || gap < bestGap) {
best = link;
bestGap = gap;
}
}
return best;
}
function publishSelectedCard() {
if (!canSelect()) return;
const row = _selectedId ? _rowById.get(_selectedId) : null;
const row = _selectedId ? _fireById.get(_selectedId) : null;
if (!row) {
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
resetSelection();
overlayHost.setEntries(
PERIMETER_OVERLAY_SOURCE_ID,
[],
@@ -171,12 +263,36 @@ export function createFirePerimetersLayer({
);
return;
}
const candidate = findInciwebLink(_inciwebIndex, row);
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
_selectedLink =
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
// Live, the newest same-name page stands for the incident. A past `at`
// checks each own-name page, since the newest may postdate it, and the
// complex's pages only when none of those is current.
const groups =
_at === null
? [findInciwebLinks(_inciwebIndex, row).slice(0, 1)]
: [
findInciwebLinks(_inciwebIndex, {
name: row.name,
state: row.state,
}),
findInciwebLinks(_inciwebIndex, {
name: row.complexName,
state: row.state,
}),
];
_selectedLink = null;
for (const links of groups) {
const unverified = links.find(
(link) => !_linkPublications.has(link) && !_linkFailures.has(link),
);
if (unverified) {
verifyLink(unverified, row);
break;
}
_selectedLink = chooseLink(links, row);
if (_selectedLink) break;
}
const card = {
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
position: fromDegrees(row.anchor.lon, row.anchor.lat),
};
if (!openExternal) card.interactive = false;
@@ -201,11 +317,9 @@ export function createFirePerimetersLayer({
* 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;
if (!hit || hit.surface) return null;
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
}
function installClickHandler() {
@@ -236,6 +350,7 @@ export function createFirePerimetersLayer({
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
if (incidentId) {
abortLinkVerification();
_linkFailures.clear();
_selectedId = incidentId;
publishSelectedCard();
return;
@@ -247,23 +362,67 @@ export function createFirePerimetersLayer({
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
}
if (_selectedId) {
abortLinkVerification();
_selectedId = null;
publishSelectedCard();
}
});
}
function drawPieces(pieces, bands) {
const nextFills = [];
const nextLines = [];
const counts = new Map();
_fireByItem.clear();
// `fire-perimeter:<fire>:<n>` for fills, `…:<fire>:line:<n>` for lines.
const itemId = (fireId, kind) => {
const key = `${kind}${fireId}`;
const n = counts.get(key) ?? 0;
counts.set(key, n + 1);
const id = `${PICK_PREFIX}${fireId}:${kind}${n}`;
_fireByItem.set(`${kind ? _lines.id : _fills.id}\n${id}`, fireId);
return id;
};
for (const [index, piece] of pieces.entries()) {
const { color } = PERIMETER_AGE_BANDS[bands[index]];
// Each exterior keeps its own holes.
for (const rings of Array.isArray(piece.polygons) ? piece.polygons : []) {
if (!Array.isArray(rings) || !rings.every((ring) => validLine(ring, 3)))
continue;
nextFills.push({
id: itemId(piece.fireId, ''),
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: hexColor(color, FILL_ALPHA),
height: 'clampGround',
});
}
// The fire line: the piece's outline draped on the ground, apart from
// its fill, so a piece cut from a larger area has no line along the
// cut (lines take ECEF, draw.d.ts `LineItem`).
for (const line of Array.isArray(piece.outline) ? piece.outline : []) {
if (!validLine(line, 2)) continue;
nextLines.push({
id: itemId(piece.fireId, 'line:'),
positions: line.map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: LINE_WIDTH_PX,
mode: 'draped',
style: { kind: 'solid', color: hexColor(color, LINE_ALPHA) },
});
}
}
_fills.set(nextFills);
_lines.set(nextLines);
console.log(
`[Data:FirePerimeters] Drew ${pieces.length} pieces of ${_fireById.size} fires`,
);
}
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
}
function clearSelection() {
abortLinkVerification();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
resetSelection();
if (overlayHost) {
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
@@ -292,9 +451,7 @@ export function createFirePerimetersLayer({
clampTo: 'both',
show: false,
});
_setIds = new Set([_fills.id, _lines.id]);
_viewer = viewer;
_count = 0;
_lastUpdate = null;
_lastError = null;
_stale = false;
@@ -318,87 +475,58 @@ export function createFirePerimetersLayer({
clearSelection();
},
async update() {
async update(_viewerArg, { signal } = {}) {
if (!_enabled || !_fills) return false;
_request?.abort();
const request = new AbortController();
_request = request;
refreshInciwebIndex(request.signal);
const abort = () => request.abort(signal.reason);
if (signal?.aborted) abort();
else signal?.addEventListener('abort', abort, { once: true });
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 }) };
refreshInciwebIndex(request.signal);
const snapshot = await source.getSnapshot({ signal: request.signal });
if (request.signal.aborted || _request !== request || !_enabled)
return false;
const { rows } = snapshot;
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
throw new Error(msg('Malformed perimeter 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)),
_at = Number.isFinite(snapshot.at) ? snapshot.at : null;
_note = typeof snapshot.note === 'string' ? snapshot.note : null;
// A fire needs an id and the anchor its card stands on; a piece
// needs its fire.
const fires = new Map();
for (const fire of snapshot.fires)
if (typeof fire?.id === 'string' && validAnchor(fire.anchor))
fires.set(fire.id, fire);
const pieces = snapshot.pieces.filter((piece) =>
fires.has(piece?.fireId),
);
if (signature === _snapshotSignature) {
if (_selectedId) publishSelectedCard();
_lastUpdate = updatedAt;
_lastError = null;
return true;
const atMs = shownAt();
const bands = pieces.map((piece) => perimeterAgeBand(piece.born, atMs));
const drawKey =
typeof snapshot.revision === 'string'
? `${snapshot.revision}\n${bands.join('')}`
: null;
_fireById = fires;
_bandsAt = atMs;
if (drawKey === null || drawKey !== _drawnKey) {
drawPieces(pieces, bands);
_drawnKey = drawKey;
}
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),
});
// Refresh (or drop) the selected incident's card against the new
// snapshot: its ages move with `at` even when nothing is redrawn.
if (_selectedId) {
if (_selectedLink === null && !_linkRequest) _linkFailures.clear();
publishSelectedCard();
}
_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)
@@ -409,6 +537,7 @@ export function createFirePerimetersLayer({
_stale = false;
return false;
} finally {
signal?.removeEventListener('abort', abort);
if (_request === request) _request = null;
}
},
@@ -418,18 +547,20 @@ export function createFirePerimetersLayer({
_request = null;
removeClickHandler();
clearSelection();
_rowById.clear();
_snapshotSignature = null;
_fireById = new Map();
_fireByItem.clear();
_drawnKey = null;
_at = null;
_bandsAt = null;
_note = null;
_inciwebIndex = [];
_indexFetchedAt = 0;
_linkVerdicts.clear();
_linkPublications.clear();
_viewer = null;
_enabled = false;
_fills?.dispose();
_lines?.dispose();
_fills = _lines = null;
_setIds = new Set();
_count = 0;
_lastUpdate = null;
_lastError = null;
_stale = false;
@@ -442,11 +573,15 @@ export function createFirePerimetersLayer({
? Math.max(1, Math.floor(maxCount))
: 2000;
const result = [];
for (const row of _rowById.values()) {
for (const fire of _fireById.values()) {
if (result.length >= limit) break;
const { anchor, stableId, ...facts } = row;
const { anchor, id, ...facts } = fire;
// A time after the moment shown is unknown in this snapshot.
if (_at !== null)
for (const key of ['discoveredTime', 'updatedTime', 'lastGrowthTime'])
if (facts[key] > _at) facts[key] = null;
result.push({
id: stableId,
id,
...facts,
lat: anchor.lat,
lon: anchor.lon,
@@ -455,34 +590,33 @@ export function createFirePerimetersLayer({
return result;
},
/** The moment the analyst records show: the snapshot's `at`, or null for now. */
getAnalystRecordsAt() {
return _at;
},
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) },
];
const atMs = _bandsAt;
const counts = PERIMETER_AGE_BANDS.map(() => 0);
for (const fire of _fireById.values())
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
return {
chips: [],
legend: bands.map((band, index) => ({
...band,
count: [..._rowById.values()].filter(
(row) => containmentAccent(row.containedPct) === band.color,
).length,
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
label: t(band.label),
color: band.color,
count: counts[index],
...(index === 0
? {
blurb: t(
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
),
}
? { blurb: t('Colour shows the age of each area.') }
: {}),
})),
...(_note ? { info: t(_note) } : {}),
};
},
getStats() {
return {
count: _count,
count: _fireById.size,
lastUpdate: _lastUpdate,
error: _lastError,
stale: _stale,