import React, {useEffect, useMemo, useRef, useState} from "react"; import {Button, Checkbox, NumberInput, Progress, Select} from "./ui"; import {decayFromH1, doseGrid, landedGrid, profileFromTable} from "../map-shared/fallout/model.js"; import {loadTerrainGrid} from "./falloutTerrain"; import {formatYield, formatYieldAndFission, WEAPON_GROUPS} from "../map-shared/fallout/weapons.js"; import { fieldCovers, forecastAge, forecastCoversFallout, forecastExpired, forecastRunsOut, nearestHour, prepareField, rainNear, } from "../map-shared/fallout/winds.js"; import {combineBursts, CUSTOM_WEAPON, targetWeapon} from "../map-shared/fallout/targets.js"; import {getFalloutClimatology, getFalloutClimatologyMonth, getLatestFalloutWinds} from "../api"; import {climateDay, dayCounter, gunzip, parseClimatology, reachedCells} from "../map-shared/fallout/climatology.js"; import {runPool, workerCount} from "../map-shared/fallout/pool.js"; import {makeFalloutWorker} from "../map-shared/fallout/falloutWorker.js"; import {burstSpots, burstsFrame, burstWinds, gridPart, gridParts, joinParts, portablePrepared} from "../map-shared/fallout/work.js"; import {downloadTime, useWeather} from "./MapWeather"; // The map's fallout view (nuclear mode), in steps: the targets (and how their fallout is carried), // then the fallout of all the targets at once, saved or only tried out: hour by // hour as it lands and weakens, or the total dose of the first two weeks. const SOURCE = "fallout-dose"; const LAYER = "fallout-dose"; const METERS_PER_DEGREE = 111320; // The dose-rate bands drawn (R/hr at H+1), from the highest. export const DOSE_BANDS = [ {rate: 1000, color: [110, 0, 30]}, {rate: 100, color: [200, 20, 40]}, {rate: 10, color: [240, 110, 20]}, {rate: 1, color: [250, 200, 40]}, {rate: 0.1, color: [250, 240, 150]}, ]; // The total dose bands drawn (R, outdoors), from the highest, with what such a dose, taken over // days, does to a person [Glasstone and Dolan, Table 12.108]. export const TOTAL_BANDS = [ {rate: 1000, color: DOSE_BANDS[0].color, meaning: "nearly everyone dies"}, {rate: 450, color: DOSE_BANDS[1].color, meaning: "about half die without care"}, {rate: 100, color: DOSE_BANDS[2].color, meaning: "radiation sickness"}, {rate: 25, color: DOSE_BANDS[3].color, meaning: "no sickness; a higher cancer risk"}, {rate: 5, color: DOSE_BANDS[4].color, meaning: "a radiation worker's yearly limit"}, ]; // What the map shows: the dose rate hour by hour, or the total dose of someone outdoors. const RATE = "rate"; const TOTAL = "total"; // The total dose is over the first two weeks, when fallout does most of its harm. const TWO_WEEKS = 336; // The steps of the panel: the targets, the wind which carries their fallout, then what is shown. // The first step is the nuclear button, which opens the panel. const TARGETS = "targets"; const WIND = "wind"; const VIEW = "view"; // The weapons, grouped by country, then a yield of the user's own. export const WEAPON_CHOICES = [ ...WEAPON_GROUPS.map((g) => ({ group: g.name, items: g.weapons.map((w) => ({value: w.key, label: `${w.name}, ${formatYieldAndFission(w.yield_kt, w.fission_fraction)}`})), })), {group: "Other", items: [{value: CUSTOM_WEAPON, label: "A yield of my own"}]}, ]; // The panel floats over the map (z-index 1002); its dropdowns open above it. const DROPDOWN = {zIndex: 1100}; const FORECAST = "forecast"; const MANUAL = "manual"; const WINDS = [ {value: FORECAST, label: "Forecast winds aloft"}, {value: MANUAL, label: "One wind at every height"}, ]; // Winds of past days: the climatology, the share of a month's days fallout reached each place. const CLIMATE = "climate"; const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; // The shares of days drawn, from the most; the last is "any of the days". export const CLIMATE_BANDS = [ {rate: 0.5, color: DOSE_BANDS[0].color, label: "half the days or more"}, {rate: 0.25, color: DOSE_BANDS[1].color, label: "a quarter of the days or more"}, {rate: 0.1, color: DOSE_BANDS[2].color, label: "a tenth of the days or more"}, {rate: 1e-6, color: DOSE_BANDS[4].color, label: "any of the days"}, ]; // The dose rates (R/hr at H+1) a day may be counted at. const CLIMATE_RATES = [1000, 100, 10, 1].map((r) => ({value: String(r), label: `${r}+ R/hr at H+1`})); // The cells days are counted on are at least this wide (m), and each is shown as the average of // itself and its neighbors this many cells around. const CLIMATE_CELL = 4000; const CLIMATE_SMOOTH = 1; // The hours after the bursts the fallout can be watched in: landing in the first hours, then // weakening over days and weeks. And how long each is shown (ms) when they play. export const HOURS = [1, 2, 3, 6, 12, 24, 48, 72, 120, 168, 336]; const FRAME_MS = 900; // Rain this heavy in the hours ahead (mm) is worth a warning. const RAIN_WARNING_MM = 0.5; // Web Mercator's y of `lat` (degrees), and back. const mercatorY = (lat) => Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)); const mercatorLat = (y) => (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI; // The map takes no latitude past the poles' edge of the Web Mercator world. const clampLat = (lat) => Math.min(Math.max(lat, -85), 85); // The grid's row (from the south) under each of `height` image rows (from the top), for a grid // around `lat`. The map stretches an image evenly in Web Mercator between its corners, but the // grid's rows are evenly apart in latitude: over many degrees they part ways, so each image row // takes the grid row at its own latitude. export function imageRows(grid, lat, height) { const north = clampLat(lat + (grid.y0 + grid.ny * grid.cell) / METERS_PER_DEGREE); const south = clampLat(lat + grid.y0 / METERS_PER_DEGREE); const top = mercatorY(north), bottom = mercatorY(south); const rows = new Int32Array(height); for (let r = 0; r < height; r++) { const rowLat = mercatorLat(top + (r + 0.5) / height * (bottom - top)); const j = Math.floor(((rowLat - lat) * METERS_PER_DEGREE - grid.y0) / grid.cell); rows[r] = Math.min(Math.max(j, 0), grid.ny - 1); } return rows; } // The grid as an image for a map, around `lat`: each cell colored by the highest band it reaches, // transparent below them. export function gridImage(grid, lat, bands = DOSE_BANDS) { const canvas = document.createElement("canvas"); canvas.width = grid.nx; canvas.height = grid.ny; const context = canvas.getContext("2d"); const image = context.createImageData(grid.nx, grid.ny); const rows = imageRows(grid, lat, grid.ny); for (let r = 0; r < grid.ny; r++) { const from = rows[r] * grid.nx, to = r * grid.nx; for (let i = 0; i < grid.nx; i++) { const band = bands.find((b) => grid.values[from + i] >= b.rate); if (!band) continue; const p = (to + i) * 4; image.data[p] = band.color[0]; image.data[p + 1] = band.color[1]; image.data[p + 2] = band.color[2]; image.data[p + 3] = 255; } } context.putImageData(image, 0, 0); return canvas.toDataURL(); } // The corners of the grid (top-left, top-right, bottom-right, bottom-left) as [lon, lat], around // `lon`, `lat`. export function gridCorners(grid, lon, lat) { const toLon = (x) => lon + x / (METERS_PER_DEGREE * Math.cos(lat * Math.PI / 180)); const toLat = (y) => clampLat(lat + y / METERS_PER_DEGREE); const west = toLon(grid.x0), east = toLon(grid.x0 + grid.nx * grid.cell); const south = toLat(grid.y0), north = toLat(grid.y0 + grid.ny * grid.cell); return [[west, north], [east, north], [east, south], [west, south]]; } // The image of the fallout `ran` ({grid, spots, origin}) as shown: the dose rate `after` hours after // the bursts, of the fallout landed by then; or the total dose outdoors in the first two weeks. export function frameOf(ran, show, after) { const grid = show === TOTAL ? doseGrid(ran.spots, ran.grid, TWO_WEEKS) : landedGrid(ran.spots, ran.grid, after); const url = gridImage(grid, ran.origin.lat, show === TOTAL ? TOTAL_BANDS : DOSE_BANDS); return {url, coordinates: gridCorners(grid, ran.origin.lon, ran.origin.lat)}; } // The wind profile the model takes, for a wind not of the forecast: one wind at every height (also // while there is no forecast). export function windProfile({direction, speed}) { return profileFromTable([[0, direction, speed]], 0); } // The area ([west, south, east, north], degrees) where the grid reaches the lowest band, with a margin. export function plumeBounds(grid, lon, lat) { const lowest = DOSE_BANDS[DOSE_BANDS.length - 1].rate; let x0 = 0, x1 = 0, y0 = 0, y1 = 0; for (let j = 0; j < grid.ny; j++) { for (let i = 0; i < grid.nx; i++) { if (grid.values[j * grid.nx + i] < lowest) continue; const x = grid.x0 + (i + 0.5) * grid.cell, y = grid.y0 + (j + 0.5) * grid.cell; x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); } } const margin = Math.max(0.25 * Math.max(x1 - x0, y1 - y0), 20000); const perLon = METERS_PER_DEGREE * Math.cos(lat * Math.PI / 180); return [lon + (x0 - margin) / perLon, lat + (y0 - margin) / METERS_PER_DEGREE, lon + (x1 + margin) / perLon, lat + (y1 + margin) / METERS_PER_DEGREE]; } // A forecast hour as the user reads it: the day and time where they are. export function hourLabel(time, nearest) { const label = new Date(time).toLocaleString(undefined, {weekday: "short", hour: "numeric", minute: "2-digit"}); return nearest ? `${label} (now)` : label; } // How often the progress is shown, at most (ms): each time redraws the panel. const PROGRESS_MS = 100; // `report(done, total)`, called at most every PROGRESS_MS, but always when all is done. export function everySoOften(report) { let last = -Infinity; return (done, total) => { const now = Date.now(); if (done < total && now - last < PROGRESS_MS) return; last = now; report(done, total); }; } // Let the page draw and answer the user when the model has had the thread for a while. A message // channel, not a timer: a browser holds a hidden tab's timers back to one a second. const SLICE_MS = 40; function yielder() { let since = performance.now(); return async () => { if (performance.now() - since < SLICE_MS) return; await new Promise((resolve) => { if (typeof MessageChannel === "undefined") { setTimeout(resolve, 0); return; } const channel = new MessageChannel(); channel.port1.onmessage = () => resolve(); channel.port2.postMessage(null); }); since = performance.now(); }; } // The fallout of `bursts` ([{lat, lon, yieldKt, fissionFraction}]) on one grid around the first: // {grid, spots (as combineBursts gives them, for the fallout hour by hour), origin, terrainStatus}. // `winds` are the winds over them, as burstWinds takes them. The bursts are spread over `workers` // workers (on the page, without them, or if they fail). `onProgress(done, total)` hears how far it // has got, `onFlat({grid, spots, origin})` gets the fallout on flat ground while the terrain is read, and it stops // (null) once `signal` (an AbortSignal) is aborted or `cancelled()`. export async function simulateBursts(bursts, {winds, useTerrain = true, workers = 0, signal = null, cancelled = () => false, onProgress = () => null, onFlat = () => null, makeWorker = makeFalloutWorker}) { const stopped = () => cancelled() || !!signal?.aborted; const origin = bursts[0]; const {windsFor, groundOf} = burstWinds(winds); const total = useTerrain ? bursts.length * 2 : bursts.length; // The bursts before this pass's, of the progress. let before = 0; const plain = bursts.map(({lat, lon, yieldKt, fissionFraction}) => ({lat, lon, yieldKt, fissionFraction})); // The bursts' spots, by the workers: null once stopped, undefined if they cannot. const spread = async (terrain) => { if (workers <= 0) return undefined; try { return await runPool({ tasks: bursts.length, total, count: workers, makeWorker, signal, start: {kind: 'bursts', bursts: plain, prepared: portablePrepared(winds.prepared), startMs: winds.startMs || 0, profile: winds.profile || null, terrain}, onProgress: (done) => onProgress(before + done, total), }); } catch (e) { console.error("Fallout: the workers failed; calculating on the page", e); return undefined; } }; const here = async (terrain) => { const pause = yielder(); const found = []; for (const b of bursts) { found.push(burstSpots(b, {windsFor, groundOf, terrain})); onProgress(before + found.length, total); await pause(); if (stopped()) return null; } return found; }; // The grid of the bursts' `spots`, its parts made by the workers (or here): null once stopped. const gridOf = async (spots) => { const frame = burstsFrame(spots, DOSE_BANDS[DOSE_BANDS.length - 1].rate); const parts = gridParts(spots); let made; if (workers > 0) { try { made = await runPool({ tasks: parts.length, total: parts.length, count: workers, makeWorker, signal, start: {kind: 'grid', frame}, payload: (k) => ({spots: parts[k]}), }); if (!made) return null; } catch (e) { console.error("Fallout: the workers failed; calculating on the page", e); } } if (!made) { const pause = yielder(); made = []; for (const part of parts) { made.push(gridPart(frame, part)); await pause(); if (stopped()) return null; } } return joinParts(frame, made); }; const run = async (terrain) => { if (stopped()) return null; let found = await spread(terrain); if (found === null) return null; if (!found) found = await here(terrain); if (!found || stopped()) return null; before += bursts.length; const runs = bursts.map((b, i) => ({burst: b, spots: found[i].spots, yieldKt: b.yieldKt, fissionFraction: b.fissionFraction})); const offMap = bursts.filter((b, i) => found[i].offMap); if (offMap.length) console.warn(`Fallout: some spots of ${offMap.length} bursts were not on the map`, offMap); const spots = combineBursts(origin, runs); const grid = await gridOf(spots); if (!grid || stopped()) return null; return {grid, spots}; }; // On flat ground first: that is where the plumes are, so the terrain under them can be read. let ran = await run(null); if (!ran) return null; let terrainStatus = "Flat ground (terrain is off)."; if (useTerrain) { onFlat({...ran, origin}); let loaded = null; try { loaded = await loadTerrainGrid(plumeBounds(ran.grid, origin.lon, origin.lat), origin.lon, origin.lat); } catch (e) { console.error("Could not read the terrain", e); } if (stopped()) return null; if (loaded) { ran = await run(loaded.grid); if (!ran) return null; const covered = Math.round(loaded.coverage * 100); terrainStatus = `Follows the terrain (zoom ${loaded.zoom}${covered < 100 ? `, ${covered}% of the area` : ""}).`; } else { terrainStatus = "No terrain file covers this place: flat ground."; } } return {grid: ran.grid, spots: ran.spots, origin, terrainStatus}; } // The fallout of `bursts` in each day of `clim` (as parseClimatology gives it): on what share of the // days each place had `rate` R/hr at H+1 or more, as a grid ({x0, y0, cell, nx, ny, values (0..1), // days}) around the first burst, smoothed; and that burst ({grid, origin}). On flat ground at sea // level: the days' winds are read by height above the sea. The days are spread over `workers` // workers (on the page, without them, or if they fail); null once `signal` (an AbortSignal) is // aborted or `cancelled()`. export async function simulateClimate(bursts, clim, {rate = 1, workers = 0, signal = null, cancelled = () => false, onProgress = () => null, makeWorker = makeFalloutWorker} = {}) { const stopped = () => cancelled() || !!signal?.aborted; if (stopped()) return null; let days = null; if (workers > 0) { try { const plain = bursts.map(({lat, lon, yieldKt, fissionFraction}) => ({lat, lon, yieldKt, fissionFraction})); days = await runPool({ tasks: clim.days, total: clim.days * bursts.length, count: workers, makeWorker, signal, onProgress, start: {kind: 'days', bytes: clim.bytes, bursts: plain, rate}, }); if (!days) return null; } catch (e) { console.error("Fallout: the workers failed; calculating on the page", e); days = null; } } if (!days) { days = []; const pause = yielder(); let done = 0; const total = clim.days * bursts.length; const onBurst = async () => { onProgress(++done, total); await pause(); }; for (let k = 0; k < clim.days; k++) { const grid = await climateDay(clim, k, bursts, {stopped, onBurst}); if (!grid || stopped()) return null; days.push(reachedCells(grid, rate)); } } if (stopped()) return null; // Counted on cells as wide as the coarsest day's: a finer count would leave holes between its cells. const counter = dayCounter(rate, Math.max(CLIMATE_CELL, ...days.map((d) => d.cell))); for (const day of days) counter.add(day); return {grid: counter.grid(CLIMATE_SMOOTH), origin: bursts[0]}; } // A weapon to burst with: one of those offered, or a yield of one's own. `value` and onChange's // argument are {weapon, yield_kt?, fission_fraction?}, as a target keeps them. export function WeaponPicker({value, onChange, label}) { const chosen = targetWeapon(value); const [customYield, setCustomYield] = useState(chosen.yieldKt); const [customFission, setCustomFission] = useState(Math.round(chosen.fissionFraction * 100)); useEffect(() => { setCustomYield(chosen.yieldKt); setCustomFission(Math.round(chosen.fissionFraction * 100)); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value?.weapon, value?.yield_kt, value?.fission_fraction]); const choose = (key) => { if (!key || key === chosen.key) return; if (key === CUSTOM_WEAPON) { onChange({weapon: key, yield_kt: chosen.yieldKt, fission_fraction: chosen.fissionFraction}); } else { onChange({weapon: key, fission_fraction: targetWeapon({weapon: key}).fissionFraction}); } }; // A yield of one's own is kept when the user has finished typing it. const keepCustom = () => { const kt = Number(customYield), fission = Number(customFission) / 100; if (!(kt > 0) || !(fission > 0 && fission <= 1)) return; if (kt === chosen.yieldKt && fission === chosen.fissionFraction) return; onChange({weapon: CUSTOM_WEAPON, yield_kt: kt, fission_fraction: fission}); }; return
key && onAllTargetsWeapon?.({ weapon: key, fission_fraction: targetWeapon({weapon: key}).fissionFraction, })}/>
}
{targets.map((t) => onRemoveTarget?.(t)} onWeapon={(weapon) => onTargetWeapon?.(t, weapon)}/>)}
{mustLoad &&
Saving replaces the saved targets: load them first, to keep them.
}
{close}
; if (step === WIND) return
Step 3 of 4: The wind
The wind carries the fallout from the targets.
setWeatherEnabled(true)}/> ({value: String(k + 1), label: name, disabled: !climateStatus?.months?.includes(k + 1)}))} onChange={(v) => v && setClimateMonth(Number(v))}/> onAfter(HOURS[Number(e.target.value)])}/>
H+{after}{when}: the fallout landed by then {after > 1 ? `, about ${weakerThanH1(after)} times weaker than at H+1` : ""}.
; } // A warning about the forecast for bursts at its hour `hour` (an index), or null: whether it is out of // date, and whether its winds run out before their fallout is down. The winds follow the hour chosen, // so the last hour is held for the whole simulation only when it is the hour chosen. export function forecastShortText(forecast, hour) { if (!forecast) return null; const last = forecast.hours.length - 1; let held = null; if (hour >= last) { held = "Its last hour's winds are held for the whole simulation."; } else if (forecastRunsOut(forecast, hour) !== null) { held = `It ends at ${hourLabel(forecast.hours[last], false)}, before all the fallout is down: ` + "its last hour's winds are held from then on."; } if (forecastExpired(forecast)) { return ["This forecast is out of date: its winds are past ones, not today's.", held, "Download a new one on the map's Manage tab, or use one wind at every height."] .filter(Boolean).join(" "); } return held && `This forecast is short. ${held}`; } // The forecast winds aloft: which hour, how old, where they reach, and whether they last until the // fallout is down. function ForecastControls({forecast, hour, onHour}) { const muted = {color: "var(--muted)", fontSize: "0.75rem"}; // Not again while the panel shows its progress: the hours' labels are slow to write. // Written again at half past each hour, when the hour nearest now moves on. const nowHour = Math.round(Date.now() / 3600000); const hours = useMemo(() => { if (!forecast) return []; const nearest = nearestHour(forecast.hours, new Date(nowHour * 3600000)); return forecast.hours.map((time, i) => ({value: String(i), label: hourLabel(time, i === nearest)})); }, [forecast, nowHour]); if (!forecast) { return
No forecast has been downloaded; until one is, this wind is used at every height:
; } const age = forecastAge(forecast); const points = forecast.points.length; const short = forecastShortText(forecast, hour); return