Compare commits

..
Author SHA1 Message Date
Mazeyar Moeini FeizabadiandClaude Fable 5.2 e9c9de0878 docs(changelog): add the #1907 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 04:13:45 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 01187cbe7a feat(vessels): draw vessels as shaded sprites seen from the camera's angle
Vessels on the map were flat, top-down hulls turned along their course,
drawn at one size at every range.

Each hull shape (the ten vessel kinds, a dredger and a pilot boat) is
now rendered in Blender into a view sheet like the aircraft's
(public/sprites/vessel-views.webp: 208 views a shape, 7.5 degrees apart
from straight above down to the horizon, 4096 x 2496, grey, 2.2 MB),
cut at the waterline. On a renderer with `viewSheets` the Vessels layer
draws a vessel as the view of its hull from where the eye is, with the
flat hull as the fallback while the sheet loads or if it cannot load.
A vessel keeps its kind's colour; aids to navigation keep their upright
buoy; a renderer without view sheets draws the flat hulls as before.

Every AIS ship type code 0-99 maps to a shape in the sheet
(`vesselShape`, vesselTypes.js), pinned by a test. Type text such as
"Search & Rescue" and "Anti Pollution" is now recognised, which also
gives those vessels their right kind colour.

Size: a vessel's icon now follows its range from the eye on the same
range aircraft icons use (1.5 times its former size up close, its
former size at about 1,000 km, a third from 8,000 km out), so it stays
under an aircraft's icon at every range, and the vessel set recedes
toward the horizon as the aircraft sets do.

Tools: the bake script handles both sheets
(scripts/bake-view-sheet.py; `npm run build:aircraft-views`,
`npm run build:vessel-views`), and refuses a partial bake over a shipped
sheet. scripts/qa-view-sheet.mjs writes contact sheets of a bake;
scripts/qa-aircraft-views.mjs takes `--layer vessels`. The aircraft
sheet is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 04:10:58 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 b4ff9b1e07 docs(changelog): add the #1903 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 01:22:05 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 efdac0ba70 feat(aircraft): draw far-away aircraft as shaded sprites seen from the camera's angle
Aircraft on the map were flat, top-down SVG silhouettes turned along
their course: from an oblique camera they read as paper cut-outs lying
on the ground.

Each aircraft class (and each helicopter rotor frame) is now rendered in
Blender from a sphere of directions into one sheet of shaded sprites
(public/sprites/aircraft-views.webp: 302 views a class, 7.5 degrees
apart from straight above to 30 degrees below the horizon, 4096 x 3648,
grey, 3.1 MB). The renderer lays a contact flat on the ground along its
course, works out where the eye is in that frame and draws the nearest
view, mirrored for the port side. The view is a card standing at the
contact, square to the direction it was rendered from, so between views
the sprite is tilted (foreshortened and turned) as the aircraft would
be; views are not blended. Sprites are neutral, so the fleet, tracked
and military tints still apply.

Renderer: a new `viewSheets` capability, `DrawPort.views(id, sheet)` and
an image `{views, first, fallback}` for icon items (src/data/viewSheet.js
holds the layout and maths, in JS and GLSL). A view row draws from the
sheet's own texture, kept as luminance and alpha; until the sheet has
loaded, and if it cannot load, it draws its flat `fallback` along its
course as before. View sheets are offered on WebGL 2 only, and on
WebGL 1 the icon shader is as it was.

Layers: Flights, Military Flights (fleet and tracked contact) and Local
ADS-B draw views; the TR-3B, airport vehicles, ground stations and
Cockpit's far pips stay flat, as does any renderer without the
capability.

Tools: `npm run build:aircraft-views` bakes the sheet from the repo's
own fleet models (about 7 minutes); scripts/qa-aircraft-view-sheet.mjs
writes contact sheets of a bake and scripts/qa-aircraft-views.mjs
photographs a grid of every class in the app from above, tilted, from
below and round an orbit.

With 5,000 contacts on an M3 Max the frame takes 5.9-6.1 ms against
5.9 ms with the flat glyphs.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 01:21:39 +01:00
Sameh Khamis d9d79ebc4d A line can be drawn as several runs (breaks) (#1895)
* A line can be drawn as several runs (`breaks`)

LineItem.breaks (capability lineBreaks) lists the positions that start a new
run of a line: the segment into each is not drawn nor picked, and the line
does not join across it, each run having ends of its own. Many lines in one
style, such as many moving objects' trails, can then be sent as one item.
Segment colours and shows stay one a pair of positions, age times one a
position, and the reveal runs along the runs in order. The Cesium port draws
a line in runs a piece a run, draped or not, and lists the capability; the
stub picks the runs only; the conformance check draw.lines.breaks pins it.

* A line in runs is cut by time run by run, whatever their order

The conformance check draw.lines.breaks.timeWindow draws a line in runs,
draped and not, whose first run is later than its second, and reads each
run drawn and cut by its own times as the scene clock moves.

It found that a plain line drawn in a polyline collection after an aged one
was the page's first of its style's type stopped the frame: Cesium keeps a
material type's uniform names from the first material of it, and a part of
a composite material has them renumbered. A part's type is now made on its
own first.

* Changelog for line breaks (#1895)
2026-11-21 13:04:19 -08:00
Sameh Khamis e4caf5d3af A line can show only the part of it within a time span of the scene clock (#1894)
* A line can show only the part of it within a time span of the scene clock

LineAgeFade.showMs (capability lineTimeWindow) draws only the part of an aged
line whose time, interpolated along it, lies between showMs before the scene
clock and the clock itself, cut as the clock moves without the line being sent
again. A moving trail can then be sent once as its whole track. The Cesium
port discards by time in its aged line material, draped or not, and the
conformance check draw.lines.timeWindow pins it. Without showMs the fade is
unchanged.

* Changelog for line time window (#1894)
2026-11-21 07:45:43 -08:00
Sameh Khamis 561f5885c2 Opening the phone Context tab no longer switches Contacts on (#1893)
* Opening the phone Context tab no longer switches Contacts on

With an aircraft tracked, the tab now only presents the Context panel, which
shows that aircraft's card as on desktop. The tab bar's open callback had no
other use and is removed.

* Add changelog fragment for #1893
2026-11-21 06:44:57 -08:00
Sameh Khamis 7ff536299a Lines can fade with the age of their points, drawn by the renderer on the GPU (#1892)
* Lines can fade with the age of their points, drawn by the renderer on the GPU

A LineItem's ageFade gives each position a time, a window and floors; the
renderer fades the line's alpha (and optionally its width) by each point's
recency on the scene clock, so a moving trail is not re-sent each frame.
Capability lineAgeFade; the Cesium port draws it in its line materials from a
small float texture of the points' times and a per-frame uniform, and the
conformance check draw.lines.ageFade pins it.

* Changelog for line age fade (#1892)
2026-11-21 06:29:57 -08:00
Sameh Khamis 918435ddc7 A voice or chat selection shows its card in the Context panel (#1890)
* fix(voice): a selection steps a docked assistant panel down so Context shows; the panel keeps the last reply

A voice or chat action that selects an entity (select_nearest_aircraft,
track_entity) now minimizes a voice or chat panel docked in the right rail's
lane, so the rail and its Context panel show as after a click. The voice
card inside the panel no longer hides 14 s after its last update: the reply
stays until the next turn, Stop or a dismissal. The floating card keeps its
idle deadline.

* fix(voice): a voice or chat selection opens its card in the Context panel

A successful select_nearest_aircraft or track_entity now selects the entity
in the Context panel's entity card store the same way a click does, so the
panel opens on its details; the docked assistant panel then steps down so it
shows. track_entity reports the id it tracked. Nothing opens in Cockpit,
where Context is hidden.

* fix(voice): a slow selection never replaces a card picked since; Cockpit is read from its own state

The entity card store counts selections and clears. A voice or chat
selection notes that count when it is asked and opens its card only if no
other card was picked or cleared before it finished. Whether Cockpit is
running is read from the style manager's Cockpit state when it has one.

* Add the changelog entry

* fix(voice): the app hands voice its Context card opener

The voice package no longer imports the entity card store. The app builds
the opener (createContextCardOpener) and passes it to the voice commands as
contextCard, which keeps the voice package inside its own boundary.
2026-11-20 22:19:16 -08:00
Sameh Khamis fbbe6cd91f Voice Cockpit entry no longer switches Contacts on (#1889)
* fix(voice): voice Cockpit entry no longer turns Contacts on

Voice entry now changes no Context mode or detection setting, as the COCKPIT
button does not. An entry that names a layer or class searches that layer's
own aircraft, nearest first from the followed aircraft or the ground under
the camera, and follows the nearest match before entering; the followed
aircraft counts when it matches. A military request while Military Flights
is off switches that layer on as a plain layer. The class filter is shared
with Contacts navigation.

* fix(voice): a military Cockpit entry waits for the layer's first data and leaves no layer behind

A military entry that switched Military Flights on waits for that layer to
report its first data before searching it, bounded by that update, the
layer failing or going off, and the request's cancellation. If entry then
fails, the layer is switched off again; a layer that was already on stays
on. The search covers only the aircraft the person's filters show.

* Add the changelog entry
2026-11-20 22:01:03 -08:00
Sameh Khamis 5608b12a25 Show JTWC cyclones: western Pacific, Indian Ocean and Southern Hemisphere (#1891)
* Show JTWC warnings in Cyclone advisories

Cyclone advisories now also read the Joint Typhoon Warning Center (keyless,
public domain) for the western North Pacific, North Indian Ocean and Southern
Hemisphere, beside NHC and CPHC.

- server/providers/jtwc.js reads JTWC's warnings feed, each storm's JMV 3.0
  warning (.tcw) and its overlay (.kmz). /api/cyclones merges them with NHC's:
  one storm per id, NHC's advisory where NHC lists the storm. A failed JTWC
  read keeps its last storms, marked stale, and never hides NHC's.
- Storms carry an agency. A JTWC warning has no cone; its 34-knot wind danger
  area is drawn as its own dashed area and named for the selected storm.
- A JTWC storm's card notes that the regional centre's warning is official
  and that JTWC winds are 1-minute averages. Source and coverage wording names
  both agencies.
- Each storm is served while its own advisory is usable (12 hours for NHC,
  13 for JTWC).

* Keep one JTWC failure from affecting other storms or NHC

- A storm whose JTWC warning cannot be read or parsed is left out and the
  others are shown; the read fails only when every listed storm's does.
- JTWC is read under its own 8-second deadline. A failed or slow JTWC read
  keeps JTWC's last good storms and never delays, fails or stales the NHC
  answer.
- Danger-swath longitudes past ±180 (a ring crossing the antimeridian) are
  wrapped into -180..180 instead of dropping the ring.

* Add the changelog entry for JTWC cyclones
2026-11-20 21:48:15 -08:00
Bilawal Sidhu ae212e5b63 Place trademark attribution below the README install links (#1888) 2026-11-20 22:42:21 -06:00
Sameh Khamis deff042265 fix(satellites): releasing a tracked satellite clears its focus dimming (#1887)
_clearTracking cleared the focus rectangle, then told the camera to stop
following before marking the satellite released. A follow listener that read
the tracked position in between (the Cockpit entry button does) published the
rectangle again, and nothing cleared it: every icon inside a centred screen
rectangle stayed at 25% opacity once the camera was farther than the old
follow distance.

The satellite is now marked released before the camera hears of it.
2026-11-20 20:05:40 -08:00
Sameh Khamis aac6be7773 test(scenes): drop the resumed-flight timing test (#1885)
It timed a 0.2 s camera flight against real timers with a few milliseconds of slack, so slow runners failed it at random. The resumed-hold tests next to it still cover resuming a run partway through a scene.
2026-11-20 18:43:35 -08:00
Sameh Khamis 84324ea678 Put the globe actions back on the title row, with the loading line under them (#1884)
The desktop search layout had moved the round globe actions down to the
HUD's top rows, where the loading line (top: 74px) was drawn over them.
They now sit on the title row again (top: 32px), level with the title,
and the loading line stays under them. Narrower than 1180px, where the
centred row would reach the title, the actions keep their lower place and
the loading line moves 42px under them.
2026-11-20 18:30:17 -08:00
German Khokhlov 41c792208e Merge pull request #1543 from Byrd-IT/byrdit/cctv-visible-only-fetch
perf(cctv): fetch the active camera's pictures only while they can be seen
2026-11-20 19:42:08 +04:00
German Khokhlov b94e556693 Merge branch 'main' into byrdit/cctv-visible-only-fetch 2026-11-20 19:26:40 +04:00
German Khokhlov 20647f6549 Merge origin/main into byrdit/cctv-visible-only-fetch
# Conflicts:
#	src/layers/cctv/frames.test.mjs
2026-11-20 17:33:48 +04:00
German Khokhlov 2c5f9f89f7 fix(cctv): keep the camera card's bigger view refreshing
An open bigger view now counts as a viewer of the camera's still, so it
keeps refreshing after the layout turns phone and the Cameras sheet is
not the one open. The card releases it in the watcher's cleanup, which
also runs when the card unmounts in the same tick the popup closes.
2026-11-20 03:35:32 +04:00
German Khokhlov d19ae89630 Merge origin/main into byrdit/cctv-visible-only-fetch 2026-11-19 18:33:29 +04:00
German Khokhlov 99a70a0e0c fix(cctv): keep the Context camera card's still and tidy the visibility port
The still preview gate looked only at the CCTV panel, so the Context
camera card, which reads the same frame, stopped updating while the
panel was collapsed or another phone sheet was open. A mounted card now
counts itself in the CCTV store, and the still is requested while the
panel or a card is shown; live video still follows the panel only.

Review follow-ups in the same area:
- visiblePoints is registered once, in createCesiumPorts, and drops
  checks for input that cannot happen; the contract documents
  horizonMarginM and when it answers false or null.
- The layer passes the mount and the four corners once each and asks
  findCamera for the port.
- Phone sheet names come from a shared module instead of literals.
- Layer tests cover the fetch gate; the geometry cases moved to the
  camera port tests. Comments and CURRENT-STATE match the code.
2026-11-19 18:28:51 +04:00
brandonabyrd b020a1cd91 docs: describe camera point visibility capability 2026-11-18 17:13:06 -06:00
brandonabyrd 28007e20ef fix(cctv): register camera point visibility capability 2026-11-18 17:13:06 -06:00
brandonabyrd 02c60c0a20 fix(cctv): fail open before projection geometry exists 2026-11-18 17:13:06 -06:00
brandonabyrd b98b9d390f fix(cctv): reuse renderer visibility scratch state 2026-11-18 17:13:06 -06:00
brandonabyrd c0752784d2 fix(cctv): cull frames through renderer camera port 2026-11-18 17:13:06 -06:00
Byrd-IT 147d1f5e4e docs: CURRENT-STATE describes the 200 m horizon margin and the phone Cameras sheet rule (#1543) 2026-11-18 17:13:06 -06:00
brandonabyrd 5887235894 docs(cctv): describe conservative horizon geometry 2026-11-18 17:13:06 -06:00
brandonabyrd 564383e4b5 fix(cctv): retain far-side culling below ellipsoid 2026-11-18 17:13:06 -06:00
brandonabyrd b1b66e9717 fix(cctv): keep below-ellipsoid planes refreshing 2026-11-18 17:13:06 -06:00
Byrd-IT 9a3fc84935 fix(cctv): address review of #1543 (horizon test, resume guard, no per-frame allocation, mobile sheet)
- frames.test: viewerAt uses Cesium's default far (5e8) so the below-horizon
  test fails without occluder.isPointVisible
- cctvControls: install the resume observer for a still-only panel too
- cctvPresentation: panelShown also requires the Cameras sheet on phones;
  the observer watches body class/data-mobile-sheet
- frames.projectionInView: shared horizonOccluder + scratch sphere/array
2026-11-18 17:13:06 -06:00
Byrd-IT 0151c178a4 docs: changelog fragment for #1543 2026-11-18 17:13:06 -06:00
Byrd-IT 3bda877a8a perf(cctv): fetch the active camera's pictures only while they can be seen 2026-11-18 17:13:06 -06:00
148 changed files with 10671 additions and 2228 deletions

No files matched your search

+22 -1
View File
@@ -20,6 +20,7 @@ How to read this:
| **NOAA nowCOAST observed weather** (`nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite}/ows`, WMS 1.1.1) | Rain radar (MRMS base reflectivity, contiguous US, about 4-minute updates) and Satellite clouds (GOES-19/18 Band 14 regional infrared, about 5-minute updates; global infrared mosaic, hourly). Keyless; layer metadata refreshed every 2 minutes, exact-time images cached for up to 24 hours | [NOAA disclaimer](https://oceanservice.noaa.gov/disclaimer.html) | "NOAA nowCOAST · NWS/OAR MRMS radar; NESDIS GOES and global satellite partners" |
| **NOAA nowCOAST lightning density** (`nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows`) | Lightning density: 15-minute accumulated strike density on an approximately 8 km grid, Americas and Pacific. Keyless; layer metadata refreshed every 10 minutes, exact-time images cached for up to 24 hours | NOAA Level-5 derived product from Vaisala NLDN/GLD360; the [product description](https://ocean.weather.gov/lightning/lightning_pdd.php) permits public distribution of this density product, not of raw Vaisala detections | "NOAA/NWS nowCOAST; derived from Vaisala NLDN/GLD360" |
| **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" |
| **Joint Typhoon Warning Center (JTWC) warnings** (`www.metoc.navy.mil/jtwc/rss/jtwc.rss`, each storm's `.tcw` and `.kmz`) | Cyclone advisories for the western North Pacific, North Indian Ocean and Southern Hemisphere: positions, forecast tracks and 34-knot wind danger areas. Keyless through `/api/cyclones`, read beside NHC | US government work (U.S. Navy / U.S. Air Force); not the official regional warning; no endorsement implied | "Joint Typhoon Warning Center" |
| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles kept in server memory for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
| **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer |
| **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
@@ -43,7 +44,7 @@ How to read this:
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
| **Environment and Climate Change Canada** (MSC GeoMet OGC API) | Air quality (AQHI) — Canadian station observations | [ECCC Data Servers End-use Licence](https://eccc-msc.github.io/open-data/licence/readme_en/) (open, attribution required, no endorsement implied) | "Contains information licensed under the Environment and Climate Change Canada Data Servers End-use Licence" |
| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) |
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts; perimeters are coloured by when they were mapped (`poly_PolygonDateTime`, else the record's last edit `poly_DateCurrent`, which also moves when only the incident's attributes are edited, so such a fire can look newly grown) | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app |
| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer, both sections: the last 24 h of reports from many publishers. Set, the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to it and Core reads none of the three sources below. Which providers stand behind its feed is the news server's to state | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. The Data attribution popover states that places, categories, severity and English headlines are derived automatically and can be wrong |
| **GDELT 2.0 events and GKG** (`data.gdeltproject.org/gdeltv2/`; no key; used only without a news server) | News layer, Conflicts: the last 24 h of GDELT's 15-minute event exports (`*.export.CSV.zip`, about 100 KB each), read server-side as they appear. Physical violence only (CAMEO roots 18–20); one report per story, copies of one agency story merged; placed at GDELT's location for it (a town the article's words name beats a bare country). Titled by the article's page title from the GKG export of the same quarter hour (`*.gkg.csv.zip`, about 6 MB each) for the newest 3 h, else by the words of the article's address. GDELT's actor coding is never shown. Categories, relevance and severity by bundled rules | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic, commercial and governmental use, with citation and a link to the GDELT Project. Coded events, page titles and article links only; linked articles keep their publishers' terms | "GDELT Project" with a link to gdeltproject.org in the Data attribution popover; "via GDELT Project", the publisher's domain and the article link on every card |
@@ -709,6 +710,26 @@ This implementation is original; those contributions have not been merged here.
fixed upstream endpoints, bounded bodies/geometry/deadline, explicit unavailable/stale states.
Direct status fetching is unsuitable in browsers because NHC does not advertise CORS.
### Weather: JTWC cyclone warnings
- **Sources:** the [JTWC warnings feed](https://www.metoc.navy.mil/jtwc/rss/jtwc.rss), and for each
storm it lists, the warning's JMV 3.0 data (`products/<storm>.tcw`) and Google Earth overlay
(`products/<storm>.kmz`).
- **Rights/credit:** Joint Typhoon Warning Center (U.S. Navy / U.S. Air Force), a US government
work. JTWC warns for US government interests; the official warning for each basin is its
regional centre's (for example JMA, IMD, RSMC Nadi, BoM, Météo-France La Réunion). No bundled
archive and no endorsement implied.
- **Coverage/meaning:** western North Pacific, North Indian Ocean and Southern Hemisphere. Where
NHC or CPHC lists the same storm, theirs is shown. Winds are 1-minute averages. The 34-knot wind
danger area is the swath of 34-knot winds widened by forecast track error, drawn as its own
area and never as a cone; it comes only from the overlay of the same warning number, and the
geometry waits for it.
- **Delivery:** read in `/api/cyclones` beside NHC under its own 8-second deadline, bounded
bodies, no redirects. A warning is usable for 13 hours after issuance (some storms are on
12-hourly warnings). A storm whose warning cannot be read is left out and the others shown; a
failed or slow JTWC read keeps JTWC's last good storms and never delays or stales NHC's. Swath
longitudes past ±180 (a ring crossing the antimeridian) are wrapped, not dropped.
### Weather: observed lightning density
- **Source:** [NOAA nowCOAST lightning detection WMS](https://nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows),
+6 -4
View File
@@ -16,6 +16,8 @@ Click any satellite, plane, ship or public camera and you can track it. Turn on
**[One-click install with Pinokio](https://pinokio.co/apps/github-com-bilawalsidhu-gods-eye-view)** · **[Run it from the terminal](#-quick-start)** · **[Hosted version waitlist](https://godseyeview.ai/online/)**
God’s Eye View™ is a trademark of Metaversity LLC, used under license by Halfpixel, Inc. [Official download page](https://godseyeview.ai/download/).
🏆 **#1 on GitHub Trending**, daily and weekly · **[#8 Product of the Day](https://www.producthunt.com/products/god-s-eye-view?launch=god-s-eye-view)**, hunted by Chris Messina · _“pretty cool”_ — [Brendan Eich](https://x.com/BrendanEich/status/2094592096401490266), creator of JavaScript · Featured on **[Pinokio](https://pinokio.co/posts/01m1m4p9xxm3qw7dnnpj2wr93g)**
▶️ **From the project behind the God's Eye View series** _(formerly WorldView)_ — [25M+ views on YouTube](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q)
@@ -94,7 +96,7 @@ We've got a plurality of sensor systems watching the planet right now. Satellite
- **🎥 Scene director:** Capture cinematic camera tours for clips and demos.
- **🔗 Share Links:** Camera, style, layers, and even one tracked target serialize into a URL — a live target is a handoff, not a bookmark.
- **🏠 Reset Globe:** One control — or one sentence — back to the full Earth.
- **🌦️ Weather:** Animate GFS or ECMWF forecast wind, replay observed radar, satellite clouds and lightning on one timeline, and follow NHC/CPHC cyclone tracks. No key needed.
- **🌦️ Weather:** Animate GFS or ECMWF forecast wind, replay observed radar, satellite clouds and lightning on one timeline, and follow NHC/CPHC and JTWC cyclone tracks. No key needed.
- **📷 Mapped ALPR cameras:** License-plate-reader camera locations tagged in OpenStreetMap, one city at a time. Locations and tags only; no key needed.
- **🔭 Satellite passes:** Ask by voice when any loaded satellite next rises over you: rise, peak and set times, and whether you can see it.
- **🔎 Analyst answers:** Count, filter and rank satellites, datacenters and dams by voice, alongside flights, ships, fires and quakes; answers say when a feed is stale or on a fallback.
@@ -441,7 +443,7 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
| ✈️ **Live Flights** | 11,000+ live aircraft + route history | OpenSky + adsb.lol | 🟢 (🟡 optional for more polling credits) |
| 🎖️ **Military Flights** | ADS-B military traffic in amber, emergency broadcasts in red | adsb.lol | 🟢 |
| 📡 **GNSS Integrity** | Regional navigation accuracy scores; anomalies do not confirm interference | adsb.lol, GPSJAM aggregation | 🟢 |
| 🔥 **Fire Perimeters** | Incident boundaries coloured by how recently they were mapped; size, containment and cause on each card | WFIGS / NIFC | 🟢 |
| 🔥 **Fire Perimeters** | Incident boundaries and reported containment | WFIGS / NIFC | 🟢 |
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
| 🛰️ **Satellites** | About 1,300 objects in six classes (Stations, Imaging, Telecom, Starlink, Probes, Debris) with a toggle and a live count each; Starlink loads its whole shell | CelesTrak | 🟢 |
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
@@ -464,11 +466,11 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
| 🦉 **Wildlife Sightings** | Wildlife observed within 48 h (whales 7 d): density glow, taxon badges and anchored photo cards with creator/licence credit. Salish Sea marine mammals via Acartia; sensitive locations shown as 0.2° cells. Not a census | iNaturalist, Acartia | 🟢 |
| 🌬️ **Wind** | Animated 10 m forecast wind with an optional speed, temperature or pressure color field and a reading at map center | NOAA GFS / ECMWF IFS | 🟢 |
| 🌦️ **Observed Weather** | Rain radar (contiguous US), Satellite clouds (GOES regional or global infrared, Clouds only or Full image) and Lightning density (Americas and Pacific) on one history timeline | NOAA nowCOAST | 🟢 |
| 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones for the Atlantic and eastern/central North Pacific | NOAA NHC / CPHC | 🟢 |
| 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones (Atlantic, eastern/central North Pacific); warnings with 34-knot wind danger areas elsewhere | NOAA NHC / CPHC · JTWC | 🟢 |
</details>
**Weather, keyless.** **Wind** animates 10 m forecast flow from NOAA GFS or ECMWF IFS, with an optional color field and a reading at map center. **Rain radar**, **Satellite clouds** and **Lightning density** are observations on one history timeline in the **WEATHER** panel (step back, **Play**, **Latest**); **Cyclone advisories** draw NHC and CPHC positions, forecast tracks and cones. On Google 3D Tiles the observed layers float above the city as translucent shells, sharpened around your view.
**Weather, keyless.** **Wind** animates 10 m forecast flow from NOAA GFS or ECMWF IFS, with an optional color field and a reading at map center. **Rain radar**, **Satellite clouds** and **Lightning density** are observations on one history timeline in the **WEATHER** panel (step back, **Play**, **Latest**); **Cyclone advisories** draw NHC and CPHC positions, forecast tracks and cones, and JTWC warnings with their 34-knot wind danger areas for the other basins. On Google 3D Tiles the observed layers float above the city as translucent shells, sharpened around your view.
In the app, **Data Layers** groups them as Movement, Cameras, Infrastructure, Events, Weather and Audio; Directions and OSM Places sit in the separate **Utilities** panel with Draw and Import.
@@ -0,0 +1,4 @@
- Stop fetching the active CCTV camera's pictures when nobody can see them. The
monitor plane skips its 10 s still while it is off screen or below the
horizon, and the still preview waits for a visible tab and an open panel or
Context camera card (on phones, the open Cameras or Context sheet) (Byrd-IT, #1543).
@@ -0,0 +1,3 @@
- Voice Cockpit entry no longer switches Contacts on; a request for a class
such as a military helicopter finds the nearest matching aircraft itself
and switches on only the layer it needs (samehkhamis, #1889).
@@ -0,0 +1,3 @@
- A voice or chat selection opens its card in the Context panel, as a click
does, and a docked assistant panel steps down so the card shows; the reply
stays until the next one (samehkhamis, #1890).
+5
View File
@@ -0,0 +1,5 @@
- Cyclone advisories show the Joint Typhoon Warning Center's storms beside
NHC's: the western Pacific, the Indian Ocean and the Southern Hemisphere.
JTWC's 34-knot wind danger area is drawn where it publishes no cone, its
cards say the regional centre's warning is the official one, and each storm
now ages out on its own (samehkhamis, #1891).
+4
View File
@@ -0,0 +1,4 @@
- Lines can fade with the age of their points (`LineItem.ageFade`, capability
`lineAgeFade`), drawn by the renderer on the GPU on the scene clock, so a
moving trail is not re-sent each frame; the Cesium renderer draws it, draped
or not (samehkhamis, #1892).
@@ -0,0 +1,2 @@
- Opening the phone Context tab with an aircraft tracked shows its card and no
longer switches Contacts on (samehkhamis, #1893).
+5
View File
@@ -0,0 +1,5 @@
- A line can show only the part of it within a span of the scene clock
(`LineAgeFade.showMs`, capability `lineTimeWindow`): the renderer cuts it by
time on the GPU as the clock moves, so a moving trail can be sent once as
its whole track; the Cesium renderer draws it, draped or not (samehkhamis,
#1894).
+5
View File
@@ -0,0 +1,5 @@
- A line can be drawn as several runs (`LineItem.breaks`, capability
`lineBreaks`): the segments across its breaks are not drawn nor picked,
and each run has ends of its own, so many lines in one style, such as
many moving objects' trails, can be sent as one item; the Cesium renderer
draws it, draped or not (samehkhamis, #1895).
@@ -0,0 +1,8 @@
- Aircraft on the map are shaded sprites that show the view of the aircraft
from where the camera is, instead of flat top-down silhouettes: each class
(and each helicopter rotor frame) is drawn from a sheet rendered from a
sphere of camera angles, laid flat along its course, so a plane seen at an
oblique angle looks solid. Flights, Military Flights (fleet and tracked
contact) and Local ADS-B use it; the TR-3B, airport vehicles, ground
stations and Cockpit's far pips stay flat, and a renderer without view
sheets draws the flat glyphs as before (Mazeyar Moeini Feizabadi, #1903).
+10
View File
@@ -0,0 +1,10 @@
- Vessels on the map are shaded sprites that show the view of the ship from
where the camera is, instead of flat top-down hulls: each hull shape (the
ten vessel kinds, a dredger and a pilot boat) is drawn from a sheet
rendered from straight above down to the horizon, laid flat on the water
along its course, so a ship seen at an oblique angle looks solid. A
vessel keeps its kind's colour; aids to navigation keep their upright buoy,
and a renderer without view sheets draws the flat hulls as before. A
vessel's size now follows the camera's range: larger up close, smaller
than an aircraft from far out, and shrinking and fading toward the
horizon as aircraft do (Mazeyar Moeini Feizabadi, #1907).
+45 -25
View File
@@ -1123,19 +1123,17 @@ Catalog calls check their cancellation signal immediately before executing a
tool. Already-cancelled queries do not start; cancellation after execution starts
continues to follow the existing tool and caller behavior.
Fire-perimeter queries test the polygon interiors and holes of each fire's
pieces on continuous unwrapped longitudes, matching the short-edge convention
used for boundary intersections: a fire is in the area when one of its pieces
is. An outline crossing ±180° contains nearby boxes and radius areas without
also containing their counterparts near Greenwich. A fire is returned at its
card anchor, which the source gives; for WFIGS it is a circular longitude mean
over the largest outer ring (excluding its repeated closing vertex), with the
relative-area comparison following short longitude edges so a small
dateline-crossing part cannot outweigh a larger ordinary part. Context's
hazard list measures distance to the same anchor. Regression coverage lives in
`src/tools/area.test.mjs`, `src/tools/queries/environment.test.mjs`,
`src/layers/perimeters/cards.test.mjs` and
`src/layers/perimeters/records.test.mjs`.
Fire-perimeter queries test polygon interiors and holes on continuous unwrapped
longitudes, matching the short-edge convention used for boundary intersections.
An outline crossing ±180° contains nearby boxes and radius areas without also
containing their counterparts near Greenwich. Returned perimeter coordinates
use a circular mean for longitude, including multipart outlines. Incident cards
also use a circular longitude mean over the largest outer ring (excluding its
repeated closing vertex). Their relative-area comparison follows short longitude
edges so a small dateline-crossing part cannot outweigh a larger ordinary part.
Regression coverage lives in `src/tools/area.test.mjs`,
`src/tools/queries/environment.test.mjs` and
`src/layers/perimeters/cards.test.mjs`.
## Scope display controls
@@ -1629,7 +1627,7 @@ warning, capped and unknown cost states also appear in the dock heading when
Settings is closed. The existing hard cost cap still stops the session and
announces the reason.
Automatic Voice Preview uses output from the active mounted provider, including late replies that may answer an older request. Manual panel choices remain until genuine local input rearms automatic presentation. Preview stays off when disabled, remains hidden in Cockpit, and retires on Stop or provider replacement. Display events do not grant command authority.
Automatic Voice Preview uses output from the active mounted provider, including late replies that may answer an older request. Manual panel choices remain until genuine local input rearms automatic presentation. Preview stays off when disabled, remains hidden in Cockpit, and retires on Stop or provider replacement. In the panel, the last reply stays until the next turn replaces it; only the voice card floating on a control without the panel hides 14 s after its last update. Display events do not grant command authority.
Typed chat sits beside voice in the dock. Chat replies are silent and never
request microphone access. The first message connects with the selected
@@ -1659,6 +1657,12 @@ and the chat shows a matching message.
Chat and the voice panel sit above the dock or dock into the right rail's lane,
which hides the rail until the panel minimizes or closes, or a rail panel opens.
A voice or chat action that selects something (`select_nearest_aircraft`,
`track_entity`) opens its card in the Context panel as a click on it does
(`createContextCardOpener` in `src/ui/stores/entityCard.js`, handed to voice by the app), except in
Cockpit (as Cockpit's own state reports it) or when another card was picked
while the action ran, which then stays, and steps a panel docked in the lane down to its bar so the rail
shows it; a panel above the dock leaves the rail in view and stays as it is.
Minimized panels always sit as a bar centred above the dock; restoring returns a
docked panel to the lane. A centred panel steps down to its bar when the pointer
reaches the Location or Visual Presets button and rests above an open tray,
@@ -2089,6 +2093,16 @@ already shows, so the list cannot pick that camera: FOCUS does, and so does
NEAREST when that camera is the nearest. Closing the list without a choice
keeps automatic selection.
The active camera's pictures follow what can be seen. The monitor plane skips
its 10 s still while the renderer reports it off screen or below the horizon,
and fetches on the first refresh tick after it is back. Activating or
calibrating a camera bypasses visibility and the usual refresh interval, but
still waits for an in-flight request and the provider's minimum interval.
The panel's still and live video run only while the tab is visible and the
panel is open (on phones, the Cameras sheet). The still also loads while
Context shows the camera's card (on phones, the Context sheet) or its bigger
view is open.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them.
Traffic and bikeshare expose factories through `./layers/traffic` and
@@ -3738,9 +3752,10 @@ that misses onto the map surface, it searches at most eight hits in a 14px squar
and accepts the first registered layer hit, stopping at non-map objects. Civil
and military aircraft and vessels share this rule; fine pointers stay exact.
Manually opening Context with a tracked civilian or military aircraft enters
the existing Contacts mode when Context is off. Contacts adopts that aircraft
without restarting its tracking. Programmatic sheet changes and closing the tab do not activate a mode.
Opening the Context tab only presents the Context panel, as on desktop: with
an aircraft tracked it shows that aircraft's card (a click on it opened the card
whether or not the panel was open). It never switches Contacts or any other
Context mode on, and changes no layer or detection.
Sheets borrow panels. Opening one expands its panels without persisting them or
claiming a user choice, and share links keep reporting each borrowed panel's
@@ -6389,11 +6404,7 @@ MLAT-positioned GPS loss, derived-field exclusions and the NIC 0 exception.
anchors, recovery, keyboard and mobile states; emergency repainting is covered
by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Link checks cancel on disable or selection change.
Fire Perimeters draws a snapshot of fires and the pieces of their burned area: the source's `getSnapshot({ signal })` answers `{ at, fetchedAt, stale, revision, note, fires, pieces }` (`src/layers/perimeters/records.js`). Each piece is filled and its `outline` drawn as separate draped lines, so a piece cut from a larger area has no line along the cut; a piece whose fire is not listed is dropped. Pieces are coloured by age at `at` (or now) on the WorldFX scale: under 6 hours yellow, 6–24 hours orange, 1–3 days red, older or of unknown birth dark red. The layer redraws only when `revision` changes or a piece moves to another age band. The legend counts fires by `lastGrowthTime` in the same four bands and shows the source's `note` below them; the card keeps its containment accent, ages from `at`, and adds "last growth … ago". A selected fire keeps its card while the snapshot lists it, with or without pieces. A failed read keeps the last picture and the row shows the error. When to read again (a timeline, the camera) is the host's call through the manager's `refreshLayer`. `createApplicationCatalog({ perimeterOptions: { inciweb: false } })` creates no InciWeb sources: the cards carry no links and InciWeb is never asked.
WFIGS keeps one current perimeter per fire, so each of its polygons is one piece, outlined by all its rings, and colour is the age of that perimeter: `poly_PolygonDateTime`, or the record's last edit `poly_DateCurrent` when that is empty (about one fire in seven), which moves with any edit to the record. A time more than 10 minutes ahead of the browser clock counts as unknown. Its `revision` follows fire ids and `poly_DateCurrent`, `at` is always null, and the note reads "Perimeters are simplified to about 100 m.".
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
The incident card rounds the WFIGS size to whole acres, except under one acre,
where it keeps the reported hundredths: a 0.25-acre fire reads `0.25 ac`, not
@@ -8898,7 +8909,7 @@ pins and share links already supply complete boxes.
30-second backoff ahead of the current clock are ignored. A smaller rollback
can retain a bounded retry delay of up to 30 seconds.
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the emergency red is mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. Tracking never recolours a model or an icon: the tracked contact draws in the colours it has untracked, and only its alpha changes (faded while stale, clear while its model draws it; `trackedIconColor`, `src/data/trackedAircraftIcon.js`). IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), in the same colour while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Angle-aware aircraft sprites.** On a renderer with the `viewSheets` capability, each aircraft class (and each of the helicopter's three rotor frames) draws from the aircraft view sheet instead of its flat glyph: `/sprites/aircraft-views.webp`, the classes rendered shaded in neutral grey from a sphere of camera angles (`src/data/viewSheet.js`, baked by `scripts/bake-view-sheet.py --sheet aircraft`, `npm run build:aircraft-views`). The icon lies flat on the earth along its course and the renderer draws the view that matches where the eye is, so an aircraft seen obliquely looks solid; the tints (white fleet, cyan tracked, amber military) multiply the grey as before. `src/data/aircraftViews.js` maps an icon kind and rotor frame to its block of the sheet and registers the sheet once per draw port. Only an icon drawn along its course (`rotationMode: 'course'`) takes a view, and it has no near image (`imageLod`), the sheet having one resolution. Flights and Military Flights draw every fleet contact this way, and their tracked billboard too (drawn along the tracked display course instead of turned on screen, so selecting a contact still changes only its colour); Local ADS-B draws its markers along their track. The TR-3B triangle, airport vehicles, ground stations and Cockpit's far-contact pips keep their flat sprites, and on a renderer without the capability every icon is the flat glyph with its near image, as before. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, milLine truncated
- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
@@ -9089,8 +9100,17 @@ apply to `public/` assets or built-preview serving.
ending, by its own switch or one of its layers going off, restores the
pre-Contacts layers but keeps the ridden one and the view; Live Signals then
drops the rows Contacts built and shows `CONTEXT STANDBY`. The visible
Cockpit actions, double-click and voice use the same gate; voice entry still
opens Contacts first, as its layer-targeted entry navigates through Contacts.
Cockpit actions, double-click and voice use the same gate. Voice entry, like
the COCKPIT button, never turns Contacts or detection on. A
voice entry that names a layer or class ("a military helicopter") searches
the aircraft that layer shows under the person's filters, nearest first,
from the followed aircraft or the ground under the camera, and follows the
nearest match (the followed aircraft counts when it matches) before it
enters (`_retargetCockpitEntryLayer` in `src/ui/cockpitCoordinator.js`). A
military request while Military Flights is off switches that layer on as a
plain layer the person can switch off, waits for its first data before
searching, and switches it off again if entry then fails; a layer that was
already on stays on. Contacts stays as it is.
The ship bridge and the orbital view have their own own-layer gates
(`bridgeEntryAllowed`, `orbitEntryAllowed`; see
[Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)).
+7 -3
View File
@@ -105,9 +105,13 @@ Status: Open (source limits, by design)
15-minute density product derived from Vaisala NLDN/GLD360 on an approximately
8 km grid, for the Americas and Pacific only (110°E across the dateline to 0°,
25°S–80°N). It is not a live strike counter or an all-clear.
- **Cyclone advisories cover NOAA's basins only:** the Atlantic and the
eastern/central North Pacific (NHC and CPHC). Storms elsewhere do not appear.
The cone is forecast-center uncertainty, not storm size.
- **Cyclone advisories come from two agencies:** NHC and CPHC for the Atlantic
and the eastern/central North Pacific, and the Joint Typhoon Warning Center
(JTWC) for the western North Pacific, North Indian Ocean and Southern
Hemisphere. JTWC is not the official warning centre for those basins, and its
winds are 1-minute averages, higher than the 10-minute winds regional centres
quote. The NHC cone is forecast-center uncertainty, not storm size; JTWC's
34-knot wind danger area is not a cone.
- **Satellite clouds:** global infrared is hourly with typically 2–3 hours of
source latency. Clouds only is a brightness filter, not a cloud mask.
- **Wind is a forecast.** The animation flows through one forecast on an
+59
View File
@@ -81,6 +81,13 @@ optional:
target's east-north-up frame, or the identity. `setView` keeps that frame
while it places a world pose. A share link's follow offset is
re-expressed in it, satellites included.
- `camera.visiblePoints(points, horizonMarginM)` (capability `pointVisibility`)
is whether any of the points may be on screen: `false` only when their
bounding sphere is outside the view or all of them are below the horizon
of the WGS84 ellipsoid shrunk by `horizonMarginM` metres; `null` when it
cannot tell (not a 3D scene, an empty point set, or a non-finite point or
camera vector), and callers count that as visible. Supply a finite,
nonnegative margin smaller than the shortest WGS84 radius.
- `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that
changes whenever what surface heights answer against changes (base,
terrain or photoreal route swapped, the globe shown or hidden) and never
@@ -115,6 +122,58 @@ optional:
- A line item's `depthFail` style, solid or dashed, draws the parts behind
the surface (the Draw tool's rubber band is dashed there too); without one
they are hidden.
- `LineItem.ageFade` (capability `lineAgeFade`, `LineAgeFade`) fades a
line with the age of its points on the scene clock (`frame.setTime`):
each position has a time, a point's recency is
`1 - clamp((now - time) / windowMs, 0, 1)`, running evenly between
positions, and the line's colour (its style's or a segment's) draws at its
alpha times `mix(alphaFloor, 1, smoothstep(0, 1, recency))`, times
`mix(squaredAlphaFloor, 1, recency²)` with `squaredAlphaFloor`, and
`widthPx` times `mix(widthFloor, 1, recency)` wide with `widthFloor`. Time
passing changes the drawing, not the line, so a trail whose points stay
put is never sent again; new times with new positions are an ordinary
update. A renderer without the capability draws the line unfaded. The
Cesium port lists it where its context has floating-point textures: an
aged line's material reads its points' times from a small texture and the
scene's time from a uniform set each frame, per fragment (draped lines
along their length, others per vertex), and an undraped one moves and
recolours in place in its polyline collection. The check
`draw.lines.ageFade` covers it, draped and not, narrowed too.
- `LineAgeFade.showMs` (capability `lineTimeWindow`) draws only the part of
an aged line within `showMs` of the scene clock: where its time, running
evenly between positions as the fade's does, is after now or before
`now - showMs`, it is not drawn (nor picked), cut there along the line,
not at a position. The cut follows `frame.setTime` as the fade does, so a
moving object's trail can be its whole track, sent once and drawn from
`showMs` ago up to where the object is now; `Infinity` cuts at now alone.
A renderer without the capability draws the whole line. The Cesium port
lists it with `lineAgeFade` and discards by time in the same material;
the check `draw.lines.timeWindow` covers it, draped and not.
- `LineItem.breaks` (capability `lineBreaks`, `LineBreaks`) draws one line
as several runs, so many lines that share one style can be sent as one
item: thousands of moving objects' trails as one line, say, which the
renderer then handles as one item instead of thousands. Each break is the
index `i` of a position that starts a new run, sorted, with
`0 < i < positions.length`; the segment from position `i - 1` to `i` is
not drawn nor picked, and the line does not join across it: each run has
two ends of its own, capped and joined as a line of its own would be.
`segmentColors` and `segmentShow` stay one a pair of neighbouring
positions (`j`, from position `j` to `j + 1`), so the entry of a pair
across a break is ignored; `ageFade.times` stays one a position; and
`revealFraction` runs along all the runs, in order, as one length (the
gaps have none). It is an optimisation: a renderer without it is never
sent `breaks`, and is sent the same lines as an item a run instead,
drawing the same picture. The Cesium port lists it and draws a line
in runs a piece a run (a polyline each in the set's collection, undraped;
a ground polyline each, draped; a primitive each with a depth-fail style
or in the sky's frame), each taking its own points' times, share of the
reveal and segment colours, and picked as the line. A draped solid line
with segment colours stays one ground instance a segment, none across a
break. Colours and shows change in place; new positions, times, reveal or
breaks draw the line anew. The check `draw.lines.breaks` covers it,
draped and not, with segment colours and without, and
`draw.lines.breaks.timeWindow` a line in runs cut by time whose first
run is later than its second, each run cut by its own times.
- A solid line's `outline.widthPx` is the outline's whole width, half on
each side, inside the line's own width: an 8 px line with a 4 px outline
is 2 px of outline, 4 px of colour and 2 px of outline, as Cesium draws
+1 -1
View File
@@ -310,7 +310,7 @@ and the development server's internal routes. See SECURITY.md.
| `get_bhote_koshi_flood` | `events` | The 2026 Bhote Koshi flood: evidence trail in story order, flood path and imagery dates (CC BY-NC 4.0) |
| `get_regional_brief` | `regional` | What and where a location is, its weather and recent headlines |
| `get_cyclones` | `cyclones` | Active NHC/CPHC tropical cyclones, optionally in an area |
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first, with when each last grew |
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first |
| `get_terrain_height` | `terrain` | Ground, geoid and ellipsoid heights at up to 20 points |
| `find_military_installations` | `installations` | OpenStreetMap military sites in an area of at most 10° per side |
| `get_map_features` | `features` | Administrative areas, named places or monuments at a location (needs Overpass) |
+2
View File
@@ -49,6 +49,8 @@
"opensky:import": "./scripts/opensky-import-client.sh",
"build": "vite build",
"build:panel": "node scripts/build-panel.mjs",
"build:aircraft-views": "node scripts/build-view-sheet.mjs --sheet aircraft",
"build:vessel-views": "node scripts/build-view-sheet.mjs --sheet vessels",
"preview": "vite preview",
"test": "node scripts/run-unit-tests.mjs",
"test:perf": "node scripts/run-perf-tests.mjs",
+4
View File
@@ -35,6 +35,10 @@ How the layers use them:
the route or category colour is painted.
- The whole set loads once, up front, when a layer that draws it starts; no
model is fetched while a session runs.
- The aircraft and helicopter models are also rendered from every side into
the aircraft view sheet, the shaded sprites far-away aircraft are drawn
with, and one ship model for each vessel hull shape, cut at its waterline,
into the vessel view sheet ([`../sprites/`](../sprites/README.md)).
`src/data/fleetModels.js` reads the set and chooses each vehicle's model;
`src/data/fleetModels.test.mjs` checks that every model `types.json` names is
+106
View File
@@ -0,0 +1,106 @@
# View Sheets
A view sheet is one image of small shaded sprites: each subject rendered from
a sphere of camera angles. On a renderer with the `viewSheets` capability a
layer lays a contact flat on the earth along its course and the renderer
draws the frame nearest to where the eye is, as a card that tilts as the eye
moves off its direction until the next frame is the nearer (frames are not
blended), so a contact seen at an oblique angle looks solid and turns with
the camera.
- `aircraft-views.webp` holds the far-away aircraft of Flights, Military
Flights and Local ADS-B.
- `vessel-views.webp` holds the vessels of the vessel layer.
Each has a manifest beside it (`.json`).
The sprites are rendered from the project's own procedural fleet models
([`../models/fleet/`](../models/README.md)), so, like them, they contain no
third-party artwork and are covered by the repository's
[MIT license](../../LICENSE).
| Path | What it holds |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aircraft-views.webp` | 4096 × 3648 px, lossless WebP: 64 px cells, 64 a row, 57 rows. Grey: every pixel's red, green and blue are equal. |
| `aircraft-views.json` | The layout (`cellPx`, `columns`, `rows`, `ringStepDeg`, `rings`, `fill`, `grey`) and each subject's first cell, fleet model and bounding radius in metres. |
| `vessel-views.webp` | 4096 × 2496 px, lossless WebP: 64 px cells, 64 a row, 39 rows. Grey. |
| `vessel-views.json` | Its manifest, of the same shape. |
## Layout
A sheet holds each subject as a block of consecutive cells, row-major:
subject `i` starts at cell `i × frames`. Within a block the frames lie in
rings 7.5° apart from straight above (ring 0, one frame) downward. A ring
runs from the eye dead ahead of the nose or bow, round the starboard side, to
dead astern. The renderer mirrors a starboard frame for an eye on the port
side, so the light is symmetric about the subject's centre plane. A frame is
an orthographic view centred on the model's origin, its bounding sphere
spanning 0.92 of the cell, turned so that straight above the nose points up
the image. `src/data/viewSheet.js` holds the layouts (`AIRCRAFT_VIEWS`,
`VESSEL_VIEWS`) and the maths that picks a frame;
`src/data/viewSheet.test.mjs` checks the manifests, the shipped images and
the bake script against them.
| Sheet | Frames a subject | Rings | Subjects, in order |
| -------- | ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Aircraft | 302 | 17, to 30° below the horizon: 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22 | `airliner`, `widebody`, `quadjet`, `turboprop`, `light`, `glider`, `fastjet`, `bizjet`, `uav`, and `helicopter0` to `helicopter2` (the helicopter's three rotor frames, `src/data/rotorFrames.js`) |
| Vessels | 208 | 13, to the horizon (a ship is never seen from below): 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25 | `cargo`, `tanker`, `passenger`, `highspeed`, `fishing`, `tug`, `sailing`, `pleasure`, `military`, `other` (the kinds of `vesselKind`, `src/data/vesselTypes.js`), `dredger`, `pilot` |
The sprites are neutral (light paint, grey shading, dark glass, a dark edge)
so each layer's tint multiplies them, as it does the flat glyphs. They are
exactly grey (`"grey": true`): the renderer keeps a sheet as grey and alpha,
reading its red channel, which halves its memory. The bake refuses a frame
that is not grey, and so does the step that writes the WebP. Every cell keeps
its outer 2 px transparent, so the renderer's mipmaps never pull in a
neighbour.
Thin subjects are thickened a little before their edge so they still read
20 to 30 px wide: the glider, UAV, light aircraft and helicopter, and every
vessel (the container ship, tanker and patrol boat most).
Vessels differ from aircraft in four ways:
- **Waterline.** A ship model's origin is its waterline. Each model is cut
there before it is rendered, so no hull below the water is drawn, even from
the horizon.
- **Paint.** The ship models are many colours (hull paint, decks,
containers). The vessel paint makes every colour a light grey, black hull
paint included, except the windows (a dark colour whose blue stands above
its red), which stay dark.
- **Beam.** Hulls are long and thin, so most are widened across the beam
(1.2 to 1.5 times; the trawler and tug as built). The side view keeps its
true height.
- **Sailboat.** The sailboat's mast is taller than its hull is long. Above
1.2 m it is squashed to 0.4 of its height, so the hull fills its cell from
above and the sail still reads from the side.
## Rebuilding
```
npm run build:aircraft-views # about 7 minutes
npm run build:vessel-views # about 4 minutes
npm run build:vessel-views -- --only tug,sailing --out /tmp/views
```
This needs Blender (`$BLENDER`, else `blender` on the `PATH`, else
`/Applications/Blender.app`). Each runs `scripts/build-view-sheet.mjs`, which
runs `scripts/bake-view-sheet.py --sheet aircraft|vessels` headless (one
script, with each sheet's layout, models, paint and adjustments). The bake
renders every frame with Cycles and refuses a frame whose pixels reach
within 2 px of its cell's edge. `build-view-sheet.mjs` then writes the PNG as
lossless WebP here with the manifest. With `--only`, the other subjects'
cells are left empty, so ship only a full bake. Cycles is not
bit-reproducible, so a rebuild changes the WebP's bytes slightly; rebuild a
sheet only to change it.
To review a bake, write a contact sheet per subject: its rings as rows, plus
a few frames at 40, 30 and 20 px in each tint the layers draw it with.
- Aircraft: over a dark sea, pale land and a mid satellite tone, in the
fleet, tracked and military tints.
- Vessels: over a dark sea, pale shallow water and a satellite ocean tone,
in white and the kind's colour.
```
node scripts/qa-view-sheet.mjs --manifest public/sprites/vessel-views.json [--out qa-shots/vessel-views]
```
+90
View File
@@ -0,0 +1,90 @@
{
"image": "aircraft-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 57,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25,
25,
24,
23,
22
],
"fill": 0.92,
"grey": true,
"subjects": {
"airliner": {
"first": 0,
"model": "aircraft/a320.glb",
"radiusM": 18.883
},
"widebody": {
"first": 302,
"model": "aircraft/b789.glb",
"radiusM": 32.121
},
"quadjet": {
"first": 604,
"model": "aircraft/b744.glb",
"radiusM": 37.959
},
"turboprop": {
"first": 906,
"model": "aircraft/at72.glb",
"radiusM": 14.14
},
"light": {
"first": 1208,
"model": "aircraft/c172.glb",
"radiusM": 5.825
},
"glider": {
"first": 1510,
"model": "aircraft/glider.glb",
"radiusM": 7.506
},
"fastjet": {
"first": 1812,
"model": "aircraft/t38.glb",
"radiusM": 7.408
},
"bizjet": {
"first": 2114,
"model": "aircraft/glf4.glb",
"radiusM": 17.211
},
"uav": {
"first": 2416,
"model": "aircraft/mq9.glb",
"radiusM": 9.811
},
"helicopter0": {
"first": 2718,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter1": {
"first": 3020,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter2": {
"first": 3322,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

+86
View File
@@ -0,0 +1,86 @@
{
"image": "vessel-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 39,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25
],
"fill": 0.92,
"grey": true,
"subjects": {
"cargo": {
"first": 0,
"model": "ships/container_ship.glb",
"radiusM": 160.913
},
"tanker": {
"first": 208,
"model": "ships/tanker.glb",
"radiusM": 130.314
},
"passenger": {
"first": 416,
"model": "ships/cruise_ship.glb",
"radiusM": 168.583
},
"highspeed": {
"first": 624,
"model": "ships/fast_ferry.glb",
"radiusM": 23.032
},
"fishing": {
"first": 832,
"model": "ships/trawler.glb",
"radiusM": 13.229
},
"tug": {
"first": 1040,
"model": "ships/tug.glb",
"radiusM": 16.418
},
"sailing": {
"first": 1248,
"model": "ships/sailboat.glb",
"radiusM": 8.358
},
"pleasure": {
"first": 1456,
"model": "ships/motor_yacht.glb",
"radiusM": 10.073
},
"military": {
"first": 1664,
"model": "ships/patrol.glb",
"radiusM": 36.28
},
"other": {
"first": 1872,
"model": "ships/generic_vessel.glb",
"radiusM": 21.828
},
"dredger": {
"first": 2080,
"model": "ships/dredger.glb",
"radiusM": 53.542
},
"pilot": {
"first": 2288,
"model": "ships/pilot_boat.glb",
"radiusM": 10.774
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

+678
View File
@@ -0,0 +1,678 @@
"""Bake a view sheet: each subject of a sheet (an aircraft class, a vessel
kind) seen from a sphere of directions, as one image of small shaded sprites.
blender -b --factory-startup --python scripts/bake-view-sheet.py -- \
--sheet aircraft|vessels --out <dir> [--cell 64] [--supersample 4]
[--only airliner,light] [--preview <dir>]
It writes `<name>.png` and its manifest `<name>.json` to `--out`, `<name>`
being the sheet's name (`aircraft-views`, `vessel-views`). The manifest names
the shipped image, `<name>.webp`, which `npm run build:aircraft-views` or
`npm run build:vessel-views` (scripts/build-view-sheet.mjs) makes from the
PNG (lossless) and writes to `public/sprites/` with the manifest.
The layers draw a contact with the frame that shows it from where the eye is
(`src/data/viewSheet.js` holds the same layouts and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's sheets and the shipped
manifests against it). A frame is an orthographic view of the subject's
fleet model (`public/models/fleet/`, nose or bow toward -X, +Y starboard, +Z
up), centred on the model's origin, the model's bounding sphere filling
`FILL` of the cell.
Directions. `d` is the unit vector from the subject to the eye in the
subject's own frame (forward, right, up), the subject lying flat on the
earth: up is the ground's normal, forward its course. Rings of frames lie
the sheet's `ring_step_deg` apart from straight above (ring 0, one frame)
down to its last ring (30 degrees below the horizon for aircraft, the horizon
for vessels). A ring holds the eye's bearings from dead ahead (first frame)
round the starboard side to dead astern (last frame); the port side is the
starboard frame mirrored, which is why the light is symmetric about the
subject's centre plane.
Roll. A frame's image up is where the subject's forward goes under the
smallest rotation that takes "up" to `d`: straight above, the nose points up
the image, and the roll then changes smoothly all the way round and below
(it has no meaning only from straight below, which no ring reaches).
The sprites are neutral (light paint, grey shading, dark glass and a dark
edge) so a layer's tint multiplies them, as it does the flat glyphs; every
pixel's red, green and blue are equal (`"grey": true` in the manifest), as
the renderer keeps the sheet as grey and alpha, and the bake refuses a frame
that is not. Each sheet has its paint ramp (`PAINTS`), and a subject may
have its own. A helicopter's body and blades are painted light as well (its
blades a solid light grey), and its rotor frames share one scale: each rotor
vertex counts at the farthest point of the circle it sweeps about the
rotor's axis. A vessel is cut at its waterline (its origin, z = 0) before it
is rendered, so no hull below the water is drawn and its bounding sphere is
of what floats; a subject's model may be widened across the beam (`beam`)
or squashed above a height (`squash_above`: a sailboat's mast). Thin
subjects are thickened before their edge (`bold_px`), and every cell keeps
`CLEAR_EDGE_PX` clear at its edges for the renderer's mipmaps; the bake
refuses a frame that does not.
"""
import json
import math
import os
import struct
import sys
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
# --- The sheets (their layouts mirrored in src/data/viewSheet.js) -----------
# A sheet: its name (the files it writes), its rings of frames (each ring's
# frame count, from dead ahead round starboard to dead astern), its paint,
# whether its models are cut at the waterline, and its subjects, in the order
# of their blocks of frames. A subject is (name, model, options); options:
# rotor_deg a helicopter's rotor frame: the rotors turned this far
# paint its own paint ramp (a key of PAINTS)
# bold_px cell pixels it is thickened by before its edge, so thin
# wings, blades and hulls still read 20 to 30 px wide
# beam its model scaled across the beam by this much
# squash_above [z, k]: its model above z metres scaled up by k
AIRCRAFT = {
"name": "aircraft-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22],
"columns": 64,
"paint": "aircraft",
"waterline": False,
"subjects": [
("airliner", "aircraft/a320.glb", {}),
("widebody", "aircraft/b789.glb", {}),
("quadjet", "aircraft/b744.glb", {}),
("turboprop", "aircraft/at72.glb", {}),
("light", "aircraft/c172.glb", {"bold_px": 0.35}),
("glider", "aircraft/glider.glb", {"bold_px": 1.0}),
("fastjet", "aircraft/t38.glb", {}),
("bizjet", "aircraft/glf4.glb", {}),
("uav", "aircraft/mq9.glb", {"bold_px": 1.0}),
# The helicopter has one block for each rotor frame (rotorFrames.js).
("helicopter0", "helicopters/generic_heli.glb", {"rotor_deg": 15, "paint": "helicopter", "bold_px": 0.4}),
("helicopter1", "helicopters/generic_heli.glb", {"rotor_deg": 45, "paint": "helicopter", "bold_px": 0.4}),
("helicopter2", "helicopters/generic_heli.glb", {"rotor_deg": 75, "paint": "helicopter", "bold_px": 0.4}),
],
}
# Vessels: down to the horizon only, as a ship is never seen from below. The
# subjects are the hull kinds of vesselKind (src/data/vesselTypes.js), then
# the dredger (AIS 33) and the pilot boat (pilot, rescue, tender and
# anti-pollution craft).
VESSELS = {
"name": "vessel-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25],
"columns": 64,
"paint": "ship",
"waterline": True,
"subjects": [
("cargo", "ships/container_ship.glb", {"beam": 1.4, "bold_px": 1.0}),
("tanker", "ships/tanker.glb", {"beam": 1.4, "bold_px": 1.0}),
("passenger", "ships/cruise_ship.glb", {"beam": 1.4, "bold_px": 0.5}),
("highspeed", "ships/fast_ferry.glb", {"beam": 1.2, "bold_px": 0.5}),
("fishing", "ships/trawler.glb", {"bold_px": 0.5}),
("tug", "ships/tug.glb", {"bold_px": 0.5}),
("sailing", "ships/sailboat.glb", {"beam": 1.3, "bold_px": 0.5, "squash_above": [1.2, 0.4]}),
("pleasure", "ships/motor_yacht.glb", {"beam": 1.25, "bold_px": 0.5}),
("military", "ships/patrol.glb", {"beam": 1.5, "bold_px": 1.0}),
("other", "ships/generic_vessel.glb", {"beam": 1.3, "bold_px": 0.5}),
("dredger", "ships/dredger.glb", {"beam": 1.3, "bold_px": 0.5}),
("pilot", "ships/pilot_boat.glb", {"beam": 1.2, "bold_px": 0.5}),
],
}
SHEETS = {"aircraft": AIRCRAFT, "vessels": VESSELS}
# How much of a cell the model's bounding sphere spans.
FILL = 0.92
# Cells keep this many pixels at each edge clear: the renderer samples the
# sheet with mipmaps (to level 1), so a neighbour's pixels must not reach
# into a cell's footprint.
CLEAR_EDGE_PX = 2
FORWARD = Vector((-1.0, 0.0, 0.0))
RIGHT = Vector((0.0, 1.0, 0.0))
UP = Vector((0.0, 0.0, 1.0))
def frame_directions(sheet):
"""Every frame's (ring, index, d) with d in the model's axes."""
out = []
for ring, count in enumerate(sheet["rings"]):
alpha = math.radians(ring * sheet["ring_step_deg"])
for i in range(count):
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
d = (
FORWARD * (math.sin(alpha) * math.cos(phi))
+ RIGHT * (math.sin(alpha) * math.sin(phi))
+ UP * math.cos(alpha)
)
out.append((ring, i, d.normalized()))
return out
def frame_up(d):
"""A frame's image up: forward, turned as `UP` turns onto `d`."""
return (UP.rotation_difference(d) @ FORWARD).normalized()
# --- Scene -------------------------------------------------------------------
def args_after_dashes():
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
opts = {
"sheet": "aircraft",
"out": "public/sprites",
"cell": 64,
"supersample": 4,
"only": None,
"preview": None,
"samples": 48,
}
i = 0
while i < len(argv):
key = argv[i].lstrip("-")
if key not in opts:
raise SystemExit(f"unknown option {argv[i]}")
opts[key] = argv[i + 1]
i += 2
opts["cell"] = int(opts["cell"])
opts["supersample"] = int(opts["supersample"])
opts["samples"] = int(opts["samples"])
if opts["sheet"] not in SHEETS:
raise SystemExit(f"--sheet is one of {', '.join(SHEETS)}")
return opts
def setup_scene(render_px, samples):
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = samples
scene.cycles.use_denoising = False
scene.cycles.max_bounces = 3
scene.cycles.pixel_filter_type = "BOX"
scene.cycles.filter_width = 1.0
scene.render.film_transparent = True
scene.render.resolution_x = render_px
scene.render.resolution_y = render_px
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.image_settings.color_depth = "8"
scene.view_settings.view_transform = "Standard"
scene.view_settings.look = "None"
scene.display_settings.display_device = "sRGB"
# Sky: even light from every side, so the underside is lit and the
# wings shade the fuselage softly where they meet.
world = bpy.data.worlds.new("sky")
world.use_nodes = True
background = world.node_tree.nodes["Background"]
background.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)
background.inputs["Strength"].default_value = SKY_STRENGTH
scene.world = world
# Sun: from above, leaning toward the nose, in the aircraft's centre
# plane (so a mirrored frame is lit as its twin).
sun_data = bpy.data.lights.new("sun", "SUN")
sun_data.energy = SUN_STRENGTH
sun_data.angle = math.radians(18)
sun = bpy.data.objects.new("sun", sun_data)
scene.collection.objects.link(sun)
lean = math.radians(28)
to_sun = (UP * math.cos(lean) + FORWARD * math.sin(lean)).normalized()
sun.rotation_euler = to_sun.to_track_quat("Z", "Y").to_euler()
# Fill: a weak light from the eye, so what faces the viewer is lighter
# than what turns away and a round body reads as round from any side.
fill_data = bpy.data.lights.new("fill", "SUN")
fill_data.energy = FILL_STRENGTH
fill_data.angle = math.radians(30)
fill = bpy.data.objects.new("fill", fill_data)
scene.collection.objects.link(fill)
camera_data = bpy.data.cameras.new("camera")
camera_data.type = "ORTHO"
camera_data.clip_start = 0.1
camera_data.clip_end = 10000
camera = bpy.data.objects.new("camera", camera_data)
scene.collection.objects.link(camera)
scene.camera = camera
return scene, camera, fill
# Paint by the model's own colour value (its largest channel, linear), as
# (value, grey) stops. Aircraft: glass and tyres stay dark, a livery's accent
# becomes mid grey, and every body colour a light paint, so a tint reads on
# any model. Ships: windows and the darkest fittings stay dark, and hull
# paint, decks and cargo all become light greys a little apart.
PAINTS = {
"aircraft": [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)],
"helicopter": [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)],
"ship": [(0.0, 0.62), (0.25, 0.78), (0.85, 0.95)],
}
# Glass by its colour, for a paint that lifts even black hull paint: a dark
# colour (value at most `value`) whose blue is at least `blue` and
# `blue_over_red` times its red (the ship models' windows) is painted `grey`.
GLASS = {"ship": {"value": 0.08, "blue": 0.025, "blue_over_red": 2.5, "grey": 0.07}}
SUN_STRENGTH = 1.4
SKY_STRENGTH = 0.38
FILL_STRENGTH = 0.9
def paint_material(paint_ramp, solid=None, glass=None):
"""Neutral paint that keeps the model's light and dark parts apart."""
material = bpy.data.materials.new("paint")
material.use_nodes = True
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = nodes["Principled BSDF"]
bsdf.inputs["Roughness"].default_value = 0.6
if solid is not None:
bsdf.inputs["Base Color"].default_value = (solid, solid, solid, 1.0)
return material
colour = nodes.new("ShaderNodeVertexColor")
colour.layer_name = "Color"
split = nodes.new("ShaderNodeSeparateColor")
links.new(colour.outputs["Color"], split.inputs["Color"])
red_green = nodes.new("ShaderNodeMath")
red_green.operation = "MAXIMUM"
links.new(split.outputs[0], red_green.inputs[0])
links.new(split.outputs[1], red_green.inputs[1])
value = nodes.new("ShaderNodeMath")
value.operation = "MAXIMUM"
links.new(red_green.outputs[0], value.inputs[0])
links.new(split.outputs[2], value.inputs[1])
ramp = nodes.new("ShaderNodeValToRGB")
elements = ramp.color_ramp.elements
while len(elements) < len(paint_ramp):
elements.new(0.5)
for element, (position, grey) in zip(elements, paint_ramp):
element.position = position
element.color = (grey, grey, grey, 1.0)
links.new(value.outputs[0], ramp.inputs["Fac"])
if glass is None:
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
return material
def math_node(operation, a, b, c=None):
node = nodes.new("ShaderNodeMath")
node.operation = operation
for i, x in enumerate((a, b, c)):
if x is None:
continue
if isinstance(x, (int, float)):
node.inputs[i].default_value = x
else:
links.new(x, node.inputs[i])
return node.outputs[0]
dark = math_node("LESS_THAN", value.outputs[0], glass["value"] + 1e-4)
blue = math_node("GREATER_THAN", split.outputs[2], glass["blue"] - 1e-4)
red_scaled = math_node("MULTIPLY", split.outputs[0], glass["blue_over_red"])
over_red = math_node(
"GREATER_THAN", math_node("SUBTRACT", split.outputs[2], red_scaled), -1e-4
)
is_glass = math_node("MULTIPLY", math_node("MULTIPLY", dark, blue), over_red)
ramp_grey = nodes.new("ShaderNodeSeparateColor")
links.new(ramp.outputs["Color"], ramp_grey.inputs["Color"])
to_glass = math_node("SUBTRACT", glass["grey"], ramp_grey.outputs[0])
grey = math_node("MULTIPLY_ADD", is_glass, to_glass, ramp_grey.outputs[0])
combine = nodes.new("ShaderNodeCombineColor")
for i in range(3):
links.new(grey, combine.inputs[i])
links.new(combine.outputs["Color"], bsdf.inputs["Base Color"])
return material
def model_parts(path):
"""The part table in a fleet model's root node (`render/modelParts.js`)."""
with open(path, "rb") as f:
data = f.read()
length = struct.unpack("<I", data[12:16])[0]
document = json.loads(data[20 : 20 + length])
for node in document.get("nodes", []):
parts = (node.get("extras") or {}).get("parts")
if parts:
return parts
return []
def gltf_to_blender(v):
"""A glTF (Y up) vector in Blender's axes (Z up)."""
return Vector((v[0], -v[2], v[1]))
def turn_rotors(mesh, parts, degrees, rotor_material):
"""Pose the rotors and bound each vertex over its entire rotation."""
part_of = mesh.data.attributes.get("_PART")
if part_of is None:
return {}
mesh.data.materials.append(rotor_material)
swept_radii = {}
to_world = mesh.matrix_world
to_local = to_world.inverted()
for index, part in enumerate(parts):
if part.get("kind") != "spin" or not part["name"].startswith("rotor"):
continue
pivot = gltf_to_blender(part["pivot"])
axis = gltf_to_blender(part["axis"]).normalized()
turn = Matrix.Rotation(math.radians(degrees), 4, axis)
move = to_local @ Matrix.Translation(pivot) @ turn @ Matrix.Translation(-pivot) @ to_world
if part_of.domain == "POINT":
members = [i for i, item in enumerate(part_of.data) if item.value == index]
else:
members = sorted(
{
mesh.data.loops[i].vertex_index
for i, item in enumerate(part_of.data)
if item.value == index
}
)
for i in members:
vertex = mesh.data.vertices[i]
relative = to_world @ vertex.co - pivot
axial = relative.dot(axis)
center = pivot + axial * axis
# The sweep lies in a plane perpendicular to the axis. Its
# farthest point adds the circle radius to the projected center.
radial = (relative - axial * axis).length
offset = (center - center.dot(axis) * axis).length
swept_radii[i] = math.hypot(center.dot(axis), offset + radial)
vertex.co = move @ vertex.co
for polygon in mesh.data.polygons:
if all(i in swept_radii for i in polygon.vertices):
polygon.material_index = 1
return swept_radii
def reshape(mesh, waterline, beam, squash_above):
"""Bring a mesh into the scene's axes, cut away what lies below the
waterline (z = 0) and scale it across the beam and above a height."""
world = mesh.matrix_world.copy()
mesh.parent = None
mesh.matrix_world = Matrix.Identity(4)
mesh.data.transform(world)
bm = bmesh.new()
bm.from_mesh(mesh.data)
if waterline:
bmesh.ops.bisect_plane(
bm,
geom=bm.verts[:] + bm.edges[:] + bm.faces[:],
dist=1e-4,
plane_co=(0.0, 0.0, 0.0),
plane_no=(0.0, 0.0, 1.0),
clear_inner=True,
)
for vertex in bm.verts:
vertex.co.y *= beam
if squash_above and vertex.co.z > squash_above[0]:
height, k = squash_above
vertex.co.z = height + (vertex.co.z - height) * k
bm.to_mesh(mesh.data)
bm.free()
def load_model(path, material, rotor_deg, rotor_material, waterline=False, options=None):
options = options or {}
before = set(bpy.data.objects)
bpy.ops.import_scene.gltf(filepath=path)
objects = [o for o in bpy.data.objects if o not in before]
meshes = [o for o in objects if o.type == "MESH"]
bpy.context.view_layer.update()
parts = model_parts(path) if rotor_deg is not None else []
beam = options.get("beam", 1.0)
squash_above = options.get("squash_above")
radius = 0.0
for mesh in meshes:
if waterline or beam != 1.0 or squash_above:
reshape(mesh, waterline, beam, squash_above)
mesh.data.materials.clear()
mesh.data.materials.append(material)
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
for vertex in mesh.data.vertices:
distance = swept_radii.get(vertex.index)
if distance is None:
distance = (mesh.matrix_world @ vertex.co).length
radius = max(radius, distance)
return objects, radius
def aim(camera, fill, d, radius):
fill.rotation_euler = d.to_track_quat("Z", "Y").to_euler()
up = frame_up(d)
right = up.cross(d).normalized()
rotation = Matrix((right, up, d)).transposed()
camera.matrix_world = Matrix.Translation(d * (radius * 4 + 10)) @ rotation.to_4x4()
camera.data.ortho_scale = 2 * radius / FILL
# --- Pixels ------------------------------------------------------------------
def read_pixels(path):
image = bpy.data.images.load(path)
width, height = image.size
pixels = np.array(image.pixels[:], dtype=np.float32).reshape(height, width, 4)
bpy.data.images.remove(image)
return pixels[::-1] # top row first
def dilate(alpha, radius):
out = alpha.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
shifted = np.zeros_like(alpha)
ys = slice(max(dy, 0), alpha.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), alpha.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), alpha.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), alpha.shape[1] + min(-dx, 0))
shifted[ys, xs] = alpha[yd, xd]
np.maximum(out, shifted, out=out)
return out
def disk_sum(values, radius):
"""Each pixel's sum of `values` over a disk of `radius` around it."""
out = values.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
ys = slice(max(dy, 0), values.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), values.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), values.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), values.shape[1] + min(-dx, 0))
out[ys, xs] += values[yd, xd]
return out
# Neutral, as the whole sheet is: the renderer keeps it as grey + alpha.
EDGE_RGB = np.array([0.045, 0.045, 0.045], dtype=np.float32)
EDGE_ALPHA = 0.62
def inside_mask(size, supersample):
"""1 within the disk that keeps CLEAR_EDGE_PX of the cell clear, fading
to 0 over half a cell pixel inside its rim. Only what the bake adds round
the model (its thickening and dark edge) is faded by it: the model's own
bounding sphere ends at FILL, inside it."""
cell = size / supersample
centre = size / 2
y, x = np.mgrid[0:size, 0:size] + 0.5
r = np.hypot(x - centre, y - centre) / supersample
outer = cell / 2 - CLEAR_EDGE_PX
return np.clip((outer - r) / 0.5, 0, 1).astype(np.float32)
def finish(pixels, supersample, bold_px=0.0):
"""Thicken the sprite by `bold_px` cell pixels, put a dark edge round it,
then bring it down to the cell by area."""
rgb = pixels[..., :3]
alpha = pixels[..., 3]
premultiplied = rgb * alpha[..., None]
mask = inside_mask(pixels.shape[0], supersample)
radius = round(supersample * bold_px)
if radius > 0:
# Under the model, its own colour spread outward: each new pixel the
# mean colour of the model round it.
grown = dilate(alpha, radius) * mask
weight = disk_sum(alpha, radius)
spread = disk_sum(premultiplied, radius) / np.maximum(weight, 1e-6)[..., None]
under = grown * (1 - alpha)
premultiplied = premultiplied + spread * under[..., None]
alpha = alpha + under
# About 0.9 cell pixels of edge.
halo = dilate(alpha, max(1, round(supersample * 0.9))) * EDGE_ALPHA * mask
out_alpha = alpha + halo * (1 - alpha)
premultiplied = premultiplied + EDGE_RGB * (halo * (1 - alpha))[..., None]
size = pixels.shape[0] // supersample
def area(a):
return a.reshape(size, supersample, size, supersample, -1).mean(axis=(1, 3))
small_alpha = area(out_alpha[..., None])[..., 0]
small = area(premultiplied)
colour = np.where(
small_alpha[..., None] > 1e-4, small / np.maximum(small_alpha[..., None], 1e-4), 0
)
return np.dstack([np.clip(colour, 0, 1), np.clip(small_alpha, 0, 1)])
# How far a frame's red, green and blue may differ (in 0..1) before the bake
# refuses it as not grey: rendering noise, never a colour.
GREY_TOLERANCE = 1.5 / 255
def to_grey(frame, name, n):
"""The frame with equal red, green and blue (their mean), refusing one
whose channels differ by more than rendering noise: the sheet ships as
grey (`"grey": true`), its red channel read as the grey."""
rgb = frame[..., :3]
lit = frame[..., 3] > 0
spread = (rgb.max(axis=2) - rgb.min(axis=2))[lit]
if spread.size and spread.max() > GREY_TOLERANCE:
raise SystemExit(
f"{name} frame {n}: not grey (its channels differ by "
f"{spread.max() * 255:.1f}/255); the sheet ships as grey"
)
grey = rgb.mean(axis=2, keepdims=True)
return np.dstack([np.repeat(grey, 3, axis=2), frame[..., 3:]])
def check_clear_edge(frame, name, n):
"""Refuse a frame with anything but transparent pixels near its edge."""
e = CLEAR_EDGE_PX
alpha = frame[..., 3]
band = np.concatenate(
[alpha[:e].ravel(), alpha[-e:].ravel(), alpha[:, :e].ravel(), alpha[:, -e:].ravel()]
)
if band.max() >= 0.5 / 255:
raise SystemExit(
f"{name} frame {n}: pixels within {e} px of the cell edge "
f"(alpha {band.max():.3f}); the fill leaves them no room"
)
def save_png(path, pixels):
height, width = pixels.shape[:2]
image = bpy.data.images.new("out", width, height, alpha=True)
image.alpha_mode = "STRAIGHT"
image.pixels.foreach_set(pixels[::-1].astype(np.float32).ravel())
image.filepath_raw = path
image.file_format = "PNG"
image.save()
bpy.data.images.remove(image)
# --- Bake --------------------------------------------------------------------
def main():
opts = args_after_dashes()
config = SHEETS[opts["sheet"]]
name_of_sheet = config["name"]
columns = config["columns"]
subjects = config["subjects"]
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
models = os.path.join(root, "public", "models", "fleet")
cell = opts["cell"]
supersample = opts["supersample"]
only = set(opts["only"].split(",")) if opts["only"] else None
scene, camera, fill = setup_scene(cell * supersample, opts["samples"])
materials = {
key: paint_material(ramp, glass=GLASS.get(key)) for key, ramp in PAINTS.items()
}
rotor_material = paint_material(None, solid=0.82)
directions = frame_directions(config)
frames = len(directions)
tmp = os.path.join(bpy.app.tempdir, "view-frame.png")
rows = math.ceil(len(subjects) * frames / columns)
sheet = np.zeros((rows * cell, columns * cell, 4), dtype=np.float32)
manifest = {
"image": f"{name_of_sheet}.webp",
"cellPx": cell,
"columns": columns,
"rows": rows,
"ringStepDeg": config["ring_step_deg"],
"rings": config["rings"],
"fill": FILL,
# Every pixel's red, green and blue are equal.
"grey": True,
"subjects": {},
}
for index, (name, model, options) in enumerate(subjects):
first = index * frames
manifest["subjects"][name] = {"first": first, "model": model}
if only and name not in only:
continue
objects, radius = load_model(
os.path.join(models, model),
materials[options.get("paint", config["paint"])],
options.get("rotor_deg"),
rotor_material,
config["waterline"],
options,
)
manifest["subjects"][name]["radiusM"] = round(radius, 3)
for n, (ring, i, d) in enumerate(directions):
aim(camera, fill, d, radius)
scene.render.filepath = tmp
bpy.ops.render.render(write_still=True)
frame = finish(read_pixels(tmp), supersample, options.get("bold_px", 0.0))
check_clear_edge(frame, name, n)
frame = to_grey(frame, name, n)
at = first + n
y = (at // columns) * cell
x = (at % columns) * cell
sheet[y : y + cell, x : x + cell] = frame
if opts["preview"]:
os.makedirs(opts["preview"], exist_ok=True)
save_png(
os.path.join(opts["preview"], f"{name}-r{ring}-{i:02d}.png"), frame
)
for obj in objects:
bpy.data.objects.remove(obj, do_unlink=True)
print(f"baked {name}: {frames} frames, radius {radius:.2f} m", flush=True)
out = os.path.join(root, opts["out"]) if not os.path.isabs(opts["out"]) else opts["out"]
os.makedirs(out, exist_ok=True)
save_png(os.path.join(out, f"{name_of_sheet}.png"), sheet)
with open(os.path.join(out, f"{name_of_sheet}.json"), "w") as f:
json.dump(manifest, f, indent=1)
f.write("\n")
print(f"wrote {out}/{name_of_sheet}.png ({columns * cell}x{rows * cell})")
main()
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env node
/**
* build-view-sheet.mjs: bake a view sheet (aircraft or vessels) and ship it.
*
* Runs `scripts/bake-view-sheet.py` in Blender (headless) into a scratch
* directory, then writes the sheet to `public/sprites/` as
* `<name>.webp` (lossless WebP of the baked PNG) and `<name>.json` (its
* manifest): `aircraft-views` or `vessel-views`. See
* `public/sprites/README.md`.
*
* Run: node scripts/build-view-sheet.mjs --sheet aircraft|vessels
* [--only airliner,light] [--out public/sprites]
* (npm run build:aircraft-views, npm run build:vessel-views)
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
const ONLY = opt('--only', null);
const SHEET = opt('--sheet', null);
if (SHEET !== 'aircraft' && SHEET !== 'vessels')
throw new Error('--sheet is aircraft or vessels');
// A bake of some subjects leaves the others' cells empty: it is for looking
// at, never for the sheet the app loads.
if (ONLY && !argv.includes('--out'))
throw new Error(
'--only bakes part of a sheet: give it its own --out, not public/sprites',
);
function blender() {
if (process.env.BLENDER) return process.env.BLENDER;
const which = spawnSync('which', ['blender'], { encoding: 'utf8' });
if (which.status === 0 && which.stdout.trim()) return which.stdout.trim();
const mac = '/Applications/Blender.app/Contents/MacOS/Blender';
if (fs.existsSync(mac)) return mac;
throw new Error('no Blender: set BLENDER to its executable');
}
/**
* Refuse a sheet the manifest calls grey whose red, green and blue differ
* anywhere: the renderer reads its red channel as the grey.
*/
async function assertGrey(file) {
const { data, info } = await sharp(file)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
for (let i = 0; i < data.length; i += info.channels)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
const pixel = i / info.channels;
throw new Error(
`the sheet is not grey at (${pixel % info.width}, ${Math.floor(pixel / info.width)})`,
);
}
}
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'view-sheet-'));
try {
const bake = spawnSync(
blender(),
[
'-b',
'--factory-startup',
'--python',
path.join(root, 'scripts', 'bake-view-sheet.py'),
'--',
'--sheet',
SHEET,
'--out',
scratch,
...(ONLY ? ['--only', ONLY] : []),
],
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8' },
);
for (const line of bake.stdout.split('\n'))
if (/^(baked|wrote)\b/.test(line)) console.log(line);
if (bake.status !== 0) {
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
throw new Error(`the bake failed (exit ${bake.status})`);
}
const [json] = fs.readdirSync(scratch).filter((f) => f.endsWith('.json'));
const name = path.basename(json, '.json');
const manifest = JSON.parse(
fs.readFileSync(path.join(scratch, json), 'utf8'),
);
const png = path.join(scratch, `${name}.png`);
if (manifest.grey) await assertGrey(png);
fs.mkdirSync(OUT, { recursive: true });
const webp = path.join(OUT, manifest.image);
await sharp(png)
.webp({ lossless: true, effort: 6, exact: true })
.toFile(webp);
fs.copyFileSync(path.join(scratch, json), path.join(OUT, json));
const kb = Math.round(fs.statSync(webp).size / 1024);
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
} finally {
fs.rmSync(scratch, { recursive: true, force: true });
}
+2 -2
View File
@@ -80,6 +80,8 @@
"src/render/cesium/tileRequests.test.mjs",
"src/queries/heights.test.mjs",
"src/render/cesium/heights.test.mjs",
"src/render/cesium/drawLineAges.test.mjs",
"src/render/cesium/drawLineBreaks.test.mjs",
"docs/CODE-BOUNDARIES.md",
"src/main.js",
"docs/APPLICATION.md",
@@ -467,8 +469,6 @@
"src/layers/perimeters/cards.test.mjs",
"src/layers/perimeters/inciweb.test.mjs",
"src/layers/perimeters/ownership.test.mjs",
"src/app/layers/perimeters.test.mjs",
"src/ui/spotConditions.test.mjs",
"src/layers/droneAirspace/index.js",
"src/layers/droneAirspace/records.js",
"src/layers/droneAirspace/source.js",
+68 -31
View File
@@ -68,7 +68,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -279,7 +280,6 @@
"src/i18n/marker.js",
"src/sources/httpBody.js",
"src/layers/perimeters/source.js",
"src/layers/perimeters/records.js",
"src/ui/spotConditions.js",
"src/ui/views/panels/SpotConditions.vue",
"src/data/wikidataCities.js",
@@ -1104,6 +1104,7 @@
"src/ui/cctv.js",
"src/ui/cctvBindings.js",
"src/ui/cctvCalibration.js",
"src/ui/mobileSheets.js",
"src/ui/cctvControls.js",
"src/ui/cctvFrames.js",
"src/ui/cctvVideo.js",
@@ -1303,7 +1304,8 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js"
"src/layers/satellites/tiangongMounts.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1344,6 +1346,7 @@
"src/data/distanceFormat.js",
"src/i18n/marker.js",
"src/ui/mobileShell.js",
"src/ui/mobileSheets.js",
"src/exclusiveSurfaces.js",
"src/ui/placeNames.js",
"src/hudLayouts.js",
@@ -1714,7 +1717,8 @@
"src/data/liveStreams.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js"
"src/ui/liveControls.js",
"src/data/viewSheet.js"
],
"external": [
"cesium",
@@ -1918,7 +1922,8 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/scenes/storyTags.js",
"src/scenes/storyThumb.js"
"src/scenes/storyThumb.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"]
},
@@ -2085,7 +2090,9 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js"
"src/data/courseFromFixes.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2231,7 +2238,9 @@
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js",
"src/data/approxDistance.js"
"src/data/approxDistance.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2389,7 +2398,9 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js"
"src/data/openVesselPhoto.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2520,7 +2531,8 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/sky/assets.js",
"src/render/cesium/cardPreviews.js"
"src/render/cesium/cardPreviews.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2618,7 +2630,8 @@
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/time/frameWait.js"
"src/time/frameWait.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2770,7 +2783,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2893,7 +2907,8 @@
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
"src/layers/satellites/tiangongArticulation.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "satellite.js", "kdbush"]
},
@@ -2997,7 +3012,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3109,7 +3125,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3191,7 +3208,8 @@
"src/data/installationFeedback.js",
"src/ui/layerNames.js",
"src/render/cesium/zoomOutGuard.js",
"src/ui/statusText.js"
"src/ui/statusText.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3317,7 +3335,8 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3511,7 +3530,8 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
],
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3641,7 +3661,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": [
"cesium",
@@ -3734,7 +3755,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3846,7 +3868,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3921,7 +3944,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -4062,7 +4086,8 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -4796,6 +4821,7 @@
"src/ui/applicationShell.js",
"src/ui/railEdgeScroll.js",
"src/ui/mobileShell.js",
"src/ui/mobileSheets.js",
"src/ui/localePicker.js",
"src/ui/cyberSonarControls.js",
"src/ui/locationNavigation.js",
@@ -5595,7 +5621,10 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
"src/layers/satellites/tiangongArticulation.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
@@ -6451,7 +6480,10 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js"
"src/layers/satellites/tiangongModel.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
@@ -6600,7 +6632,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": [
"cesium",
@@ -6714,7 +6747,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -7549,7 +7583,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "egm96-universal", "pbf", "kdbush"]
},
@@ -7679,7 +7714,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "pbf", "kdbush"]
},
@@ -7991,7 +8027,8 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
],
"external": ["cesium", "kdbush"]
},
@@ -8188,7 +8225,6 @@
"src/data/militaryInstallationData.js",
"src/layers/launches/source.js",
"src/layers/perimeters/source.js",
"src/layers/perimeters/records.js",
"src/layers/radio/source.js",
"src/layers/radio/policy.js",
"src/layers/satellites/source.js",
@@ -8441,7 +8477,8 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/render/recession.js",
"src/render/modelParts.js"
"src/render/modelParts.js",
"src/data/viewSheet.js"
],
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
},
+382
View File
@@ -0,0 +1,382 @@
#!/usr/bin/env node
/**
* qa-aircraft-views.mjs: screenshots of the aircraft view sheet in the app.
*
* Seeds a grid of synthetic military contacts (every icon class down the
* rows, eight courses across) through a fetch shim, then photographs it from
* straight above, tilted from several sides and from below, so a person can
* check that each sprite shows its aircraft from where the camera is: the
* nose along the course, the far wing foreshortened, the underside from
* below.
*
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
* [--layer military|flights|vessels] [--block-sheet] [--headful]
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
* Needs the dev server (`npm run dev`).
*/
import fs from 'node:fs';
import path from 'node:path';
import puppeteer from 'puppeteer';
import { stubPlanespotters } from './qa-photo-stub.mjs';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const APP_URL = opt('--url', 'http://localhost:4173');
const OUT = path.resolve(opt('--out', 'qa-shots/views'));
const HEADFUL = argv.includes('--headful');
// `military` (amber, every class by type code), `flights` (white, the
// classes an ADS-B emitter category gives) or `vessels` (every hull kind by
// AIS ship type, at sea level).
const LAYER = opt('--layer', 'military');
const VESSELS = LAYER === 'vessels';
// The app's id of the layer.
const LAYER_ID = VESSELS ? 'ais-live-vessels' : LAYER;
// Fail the sheet's request: the contacts should draw their flat glyphs.
const BLOCK_SHEET = argv.includes('--block-sheet');
const GPU = argv.includes('--gpu');
// A type code for each icon class (aircraftClass.js).
const CLASSES = [
['airliner', 'A320'],
['widebody', 'C17'],
['quadjet', 'B744'],
['turboprop', 'C130'],
['light', 'C172'],
['glider', 'DISC'],
['fastjet', 'F16'],
['bizjet', 'GLF4'],
['uav', 'Q9'],
['helicopter', 'H60'],
];
// The classes a flight's emitter category gives (OpenSky has no type code).
const CATEGORIES = [
['airliner', 4],
['widebody', 6],
['light', 2],
['fastjet', 7],
['glider', 9],
['helicopter', 8],
];
// An AIS ship type for each hull kind (vesselTypes.js).
const HULLS = [
['cargo', 70],
['tanker', 80],
['passenger', 60],
['highspeed', 40],
['fishing', 30],
['tug', 52],
['sailing', 36],
['pleasure', 37],
['military', 35],
['other', 90],
['dredger', 33],
['pilot', 50],
];
const ROWS = VESSELS ? HULLS : LAYER === 'flights' ? CATEGORIES : CLASSES;
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
// Aircraft over Austin; vessels on open water in the North Sea.
const CENTRE = VESSELS ? { lon: 3.2, lat: 52.6 } : { lon: -97.74, lat: 30.3 };
const STEP_DEG = 0.03;
const ALT_FT = VESSELS ? 0 : 12000;
const contacts = [];
ROWS.forEach(([klass, type], row) =>
COURSES.forEach((courseDeg, column) =>
contacts.push({
hex: `ee${row.toString(16)}${column.toString(16)}00`.slice(0, 6),
flight: `${klass.slice(0, 4).toUpperCase()}${courseDeg}`,
t: type,
klass,
courseDeg,
lon: CENTRE.lon + (column - (COURSES.length - 1) / 2) * STEP_DEG,
lat: CENTRE.lat - (row - (ROWS.length - 1) / 2) * STEP_DEG,
altFt: ALT_FT,
}),
),
);
// Each shot: where the camera looks from. `heading` is the way it looks
// (degrees clockwise from north), `pitch` down from level, `rangeKm` from
// the grid's centre at the contacts' height.
const SHOTS = [
{ name: '1-above', heading: 0, pitch: -90, rangeKm: 44 },
{ name: '2-tilt30-north', heading: 0, pitch: -60, rangeKm: 46 },
{ name: '3-tilt55-north', heading: 0, pitch: -35, rangeKm: 50 },
{ name: '4-tilt55-east', heading: 90, pitch: -35, rangeKm: 50 },
{ name: '5-tilt55-southwest', heading: 225, pitch: -35, rangeKm: 50 },
{ name: '6-tilt75-north', heading: 0, pitch: -15, rangeKm: 52 },
// From below, looking up at the grid; a vessel is never seen from there,
// so vessels get a shot from just above the water in its place.
VESSELS
? { name: '7-horizon-north', heading: 0, pitch: -5, rangeKm: 30 }
: { name: '7-below-north', heading: 0, pitch: 12, rangeKm: 15.5 },
];
// `--orbit`: the camera swung round the grid a little at a time, a frame
// each step, to watch the sprites turn from one view to the next.
const ORBIT_STEP_DEG = Number(opt('--orbit-step', 2));
const ORBIT_SHOTS = Array.from(
{ length: Math.floor(90 / ORBIT_STEP_DEG) + 1 },
(_, i) => ({
name: `orbit-${String(i).padStart(3, '0')}`,
heading: i * ORBIT_STEP_DEG,
pitch: Number(opt('--orbit-pitch', -35)),
rangeKm: 50,
settleMs: i === 0 ? 6000 : 900,
}),
);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
fs.mkdirSync(OUT, { recursive: true });
const browser = await puppeteer.launch({
headless: HEADFUL ? false : 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
...(GPU ? [] : ['--use-gl=angle', '--use-angle=swiftshader']),
'--disable-web-security',
'--disable-background-timer-throttling',
'--disable-renderer-backgrounding',
'--window-size=1500,1000',
],
});
const errors = [];
try {
const page = await browser.newPage();
await stubPlanespotters(page);
await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 2 });
page.on('console', (msg) => {
if (
msg.type() === 'error' &&
!/Failed to load resource/i.test(msg.text())
)
errors.push(msg.text());
});
page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
if (BLOCK_SHEET) {
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.isInterceptResolutionHandled()) return;
if (/\/sprites\/[a-z]+-views\./.test(request.url())) request.abort();
else request.continue();
});
}
await page.evaluateOnNewDocument(
(seed) => {
const realFetch = window.fetch.bind(window);
// Each contact flies its course, slowly: a feed whose fixes stand
// still while claiming a track makes the layers work a heading out
// of no movement, and the contacts turn north over a run.
const SPEED_MPS = 6;
const started = Date.now();
const at = (c) => {
const flown = (SPEED_MPS * (Date.now() - started)) / 1000;
const course = (c.courseDeg * Math.PI) / 180;
return {
lat: c.lat + (flown * Math.cos(course)) / 111320,
lon:
c.lon +
(flown * Math.sin(course)) /
(111320 * Math.cos((c.lat * Math.PI) / 180)),
};
};
const json = (body) =>
new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
window.fetch = (input, init) => {
const url =
typeof input === 'string' ? input : (input && input.url) || '';
if (url.includes('/api/openai/hud-summary'))
return Promise.resolve(json({ summary: 'view QA' }));
if (url.includes('/api/military/track'))
return Promise.resolve(
json({ timestamp: Math.floor(Date.now() / 1000), trace: [] }),
);
if (url.includes('/api/military'))
return Promise.resolve(
json({
msg: 'No error',
now: Date.now(),
ac: (seed.layer === 'military' ? seed.contacts : []).map(
(c) => ({
hex: c.hex,
flight: c.flight,
...at(c),
alt_baro: c.altFt,
track: c.courseDeg,
gs: SPEED_MPS * 1.9438,
t: c.t,
r: `QA-${c.hex.slice(-3)}`,
ownOp: 'QA',
seen_pos: 0,
}),
),
}),
);
if (url.includes('/api/vessels') && seed.layer === 'vessels') {
const now = Date.now();
return Promise.resolve(
json({
rows: seed.contacts.map((c, i) => ({
...at(c),
name: c.flight,
mmsi: String(235000000 + i),
imo: '0',
type: String(c.t),
destination: 'QA',
length: 120,
beam: 20,
speed: SPEED_MPS * 1.9438,
course: c.courseDeg,
heading: c.courseDeg,
last_position_UTC: new Date(now).toISOString(),
last_position_epoch: Math.floor(now / 1000),
})),
source: 'AISStream',
status: 'live',
error: null,
refreshing: false,
newestPositionAt: now,
lastMessageAt: now,
silentForMs: 0,
reconnectAttempt: 0,
nextAttemptAt: null,
staleAfterMs: 120000,
watchdog: 'armed',
}),
);
}
if (url.includes('/api/flights/track'))
return Promise.resolve(json({ path: [] }));
if (url.includes('/api/flights') && seed.layer === 'flights') {
const now = Math.floor(Date.now() / 1000);
return Promise.resolve(
json({
time: now,
states: seed.contacts.map((c) => [
c.hex,
c.flight,
'QA',
now,
now,
at(c).lon,
at(c).lat,
c.altFt * 0.3048,
false,
SPEED_MPS,
c.courseDeg,
0,
null,
null,
null,
false,
0,
c.t,
]),
}),
);
}
if (url.includes('/api/adsbdb/'))
return Promise.resolve(json({ found: false }));
return realFetch(input, init);
};
},
{ layer: LAYER, contacts },
);
console.log(`Loading ${APP_URL} ...`);
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForFunction(
() => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager,
{ timeout: 60000, polling: 200 },
);
const seeded = await page.evaluate(
async (name, centre) => {
const { dataManager, viewer } = window.__godsEyeView;
// Over the grid first: a layer may ask only for what is in view.
const Cartesian3 = viewer.camera.position.constructor;
viewer.camera.setView({
destination: Cartesian3.fromDegrees(centre.lon, centre.lat, 60000),
});
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) {
await layer.update(viewer);
await new Promise((resolve) => setTimeout(resolve, 500));
}
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
},
LAYER_ID,
CENTRE,
);
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
if (seeded !== contacts.length)
throw new Error(
`the ${LAYER} layer took ${seeded} of ${contacts.length} contacts`,
);
// Past the layer's render delay, so every contact is drawn.
await sleep(20000);
for (const shot of argv.includes('--orbit') ? ORBIT_SHOTS : SHOTS) {
await page.evaluate(
({ shot, centre, altM }) => {
const { viewer } = window.__godsEyeView;
const Cartesian3 = viewer.camera.position.constructor;
const heading = (shot.heading * Math.PI) / 180;
const pitch = (shot.pitch * Math.PI) / 180;
const range = shot.rangeKm * 1000;
// The eye sits `range` back along the way it looks.
const east = -range * Math.sin(heading) * Math.cos(pitch);
const north = -range * Math.cos(heading) * Math.cos(pitch);
const up = -range * Math.sin(pitch);
const lat = centre.lat + north / 111320;
const lon =
centre.lon +
east / (111320 * Math.cos((centre.lat * Math.PI) / 180));
viewer.camera.setView({
destination: Cartesian3.fromDegrees(
lon,
lat,
Math.max(50, altM + up),
),
orientation: { heading, pitch, roll: 0 },
});
viewer.scene.requestRender();
},
{ shot, centre: CENTRE, altM: ALT_FT * 0.3048 },
);
await sleep(shot.settleMs ?? 6000);
// The globe's own canvas, read right after a render: no HUD, dialogs
// or label overlays in the way.
const png = await page.evaluate(() => {
const { viewer } = window.__godsEyeView;
viewer.scene.render();
return viewer.scene.canvas.toDataURL('image/png');
});
const file = path.join(OUT, `${shot.name}.png`);
fs.writeFileSync(file, Buffer.from(png.split(',')[1], 'base64'));
console.log(` wrote ${file}`);
}
} finally {
await browser.close();
}
if (errors.length) {
console.log(`\nConsole errors (${errors.length}):`);
for (const error of errors.slice(0, 20)) console.log(` ${error}`);
process.exitCode = 1;
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env node
/**
* qa-view-sheet.mjs: contact sheets of a baked view sheet (aircraft or
* vessels), for reviewing a bake (`scripts/bake-view-sheet.py`) before it
* ships.
*
* For each subject it writes one image: its frames with the rings as rows
* (straight above at the top, the last ring at the bottom, each ring from
* dead ahead to dead astern), in white, over three grounds the subject is
* seen over. Under them, a few frames (above, oblique, abeam, and below or
* low on the horizon) shrunk to the sizes a contact is drawn at, in each
* tint the layers draw it with, to judge whether thin wings and hulls still
* read. Aircraft: a dark sea, pale land and a mid satellite tone; the fleet,
* tracked and military tints. Vessels: a dark sea, pale shallow water and a
* satellite ocean tone; white and the colour of each kind the subject is
* drawn for (`VESSEL_KIND_STYLES`).
*
* Run: node scripts/qa-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/<name>] [--zoom 2] [--sizes 40,30,20]
* [--only airliner,glider]
* `--sheet` defaults to the manifest's `image`, next to it.
*/
import fs from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
import { VESSEL_KIND_STYLES } from '../src/data/vesselTypes.js';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const MANIFEST = path.resolve(
opt('--manifest', 'public/sprites/aircraft-views.json'),
);
const ZOOM = Number(opt('--zoom', '2'));
const SIZES = opt('--sizes', '40,30,20').split(',').map(Number);
const ONLY = opt('--only', '').split(',').filter(Boolean);
const GAP = 8;
const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
const VESSELS = manifest.image.startsWith('vessel');
const OUT = path.resolve(
opt('--out', `qa-shots/${path.basename(manifest.image, '.webp')}`),
);
const WHITE = { name: 'white', rgb: [1, 1, 1] };
/** `#rrggbb` as 0..1 channels. */
const rgbOf = (css) =>
[1, 3, 5].map((i) => parseInt(css.slice(i, i + 2), 16) / 255);
/** Grounds a contact is seen over. */
const GROUNDS = VESSELS
? [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'shallows', css: '#8fc3c1' },
{ name: 'satellite', css: '#0f2e44' },
]
: [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The kinds a vessel shape that is not a kind of its own is coloured as: a
* vessel takes its kind's colour (`vesselKind`), whatever its shape. */
const SHAPE_KINDS = { dredger: ['other'], pilot: ['tug', 'military'] };
/** A subject's tints, multiplied into the neutral sprite as the layers do. */
const tintsOf = (name) =>
VESSELS
? [
WHITE,
...(SHAPE_KINDS[name] ?? [name]).map((kind) => ({
name: kind,
rgb: rgbOf(VESSEL_KIND_STYLES[kind].css),
})),
]
: [
WHITE,
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const sheetPath = path.resolve(
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
);
const { cellPx: cell, columns, rings } = manifest;
const firsts = [];
rings.reduce((at, count) => (firsts.push(at), at + count), 0);
const widest = Math.max(...rings);
/** The ring nearest `offDeg` from straight above. */
const ringAt = (offDeg) =>
Math.min(rings.length - 1, Math.round(offDeg / manifest.ringStepDeg));
const last = rings.length - 1;
/** Frames shown shrunk, as ring and index: straight above, oblique from
* ahead and to the right, abeam on the horizon, and the last ring from
* below abeam or, if the last ring is the horizon, from the bow quarter. */
const PICKS = [
[0, 0],
[ringAt(45), Math.floor((rings[ringAt(45)] - 1) / 3)],
[ringAt(90), Math.round((rings[ringAt(90)] - 1) / 2)],
last === ringAt(90)
? [last, Math.round((rings[last] - 1) / 4)]
: [last, Math.round((rings[last] - 1) / 2)],
];
const sheet = sharp(sheetPath, { limitInputPixels: false });
const { data: pixels, info } = await sheet
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
/** One cell as raw RGBA, tinted. */
function cellPixels(index, tint) {
const out = Buffer.alloc(cell * cell * 4);
const left = (index % columns) * cell;
const top = Math.floor(index / columns) * cell;
for (let y = 0; y < cell; y++)
for (let x = 0; x < cell; x++) {
const from = ((top + y) * info.width + left + x) * 4;
const to = (y * cell + x) * 4;
for (let c = 0; c < 3; c++)
out[to + c] = Math.round(pixels[from + c] * tint.rgb[c]);
out[to + 3] = pixels[from + 3];
}
return out;
}
async function cellImage(index, tint, size) {
let image = sharp(cellPixels(index, tint), {
raw: { width: cell, height: cell, channels: 4 },
});
if (size !== cell) image = image.resize(size, size, { kernel: 'lanczos3' });
else if (ZOOM !== 1)
image = image.resize(cell * ZOOM, cell * ZOOM, { kernel: 'nearest' });
return image.png().toBuffer();
}
async function subjectSheet(name, first) {
const TINTS = tintsOf(name);
const tile = cell * ZOOM;
const panelW = widest * tile;
const panelH = rings.length * tile;
const stripH = Math.max(...SIZES) + GAP;
const blockH = panelH + GAP + TINTS.length * stripH;
const width = GROUNDS.length * (panelW + GAP) + GAP;
const height = blockH + 2 * GAP;
const layers = [];
for (const [g, ground] of GROUNDS.entries()) {
const x0 = GAP + g * (panelW + GAP);
layers.push({
input: {
create: {
width: panelW,
height: blockH,
channels: 4,
background: ground.css,
},
},
left: x0,
top: GAP,
});
// Rings as rows, white.
for (let ring = 0; ring < rings.length; ring++)
for (let i = 0; i < rings[ring]; i++)
layers.push({
input: await cellImage(first + firsts[ring] + i, WHITE, cell),
left: x0 + i * tile,
top: GAP + ring * tile,
});
// The picked frames shrunk to drawn sizes, one row a tint.
for (const [t, tint] of TINTS.entries()) {
let x = x0 + GAP;
const y = GAP + panelH + GAP + t * stripH;
for (const [ring, index] of PICKS)
for (const size of SIZES) {
layers.push({
input: await cellImage(first + firsts[ring] + index, tint, size),
left: x,
top: y + (stripH - GAP - size),
});
x += size + 4;
}
}
}
const file = path.join(OUT, `${name}.png`);
await sharp({
create: { width, height, channels: 4, background: '#111111' },
})
.composite(layers)
.png()
.toFile(file);
return file;
}
fs.mkdirSync(OUT, { recursive: true });
for (const [name, entry] of Object.entries(manifest.subjects)) {
if (ONLY.length && !ONLY.includes(name)) continue;
const first = typeof entry === 'number' ? entry : entry.first;
console.log('wrote', await subjectSheet(name, first));
}
+97 -12
View File
@@ -1,4 +1,8 @@
import { readResponseTextCapped } from './common/http.js';
import {
readResponseBytesCapped,
readResponseTextCapped,
} from './common/http.js';
import { JTWC_USABLE_MS, readJtwcStorms } from './jtwc.js';
const STATUS_URL = 'https://www.nhc.noaa.gov/CurrentStorms.json';
const GIS =
@@ -7,7 +11,14 @@ const HOUR = 3600_000;
// Data, not UI copy: src/layers/cyclones/index.js keeps the same English in
// msg() and translates it when shown (likewise 'Cyclone data unavailable').
const COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
const SOURCE = 'NOAA NHC / CPHC · JTWC';
const ATTRIBUTION =
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center; Joint Typhoon Warning Center (U.S. Navy / U.S. Air Force)';
/** How long a storm's advisory stays usable after issuance, by agency. */
export function cycloneUsableMs(storm) {
return storm?.agency === 'jtwc' ? JTWC_USABLE_MS : 12 * HOUR;
}
const LAYERS = [
{ id: 5, cap: 512 * 1024, count: 500, kind: 'points' },
{ id: 6, cap: 512 * 1024, count: 32, kind: 'track' },
@@ -114,6 +125,7 @@ export function parseCycloneStatus(payload, now = Date.now()) {
const positionAt = iso(raw.lastUpdate, now);
return {
id: raw.id,
agency: 'nhc',
name: text(raw.name),
classification: text(raw.classification, 16),
basin: raw.id.slice(0, 2).toUpperCase(),
@@ -138,6 +150,7 @@ export function parseCycloneStatus(payload, now = Date.now()) {
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
});
}
@@ -262,8 +275,13 @@ export function cycloneProxy({
fetchImpl = fetch,
now = () => Date.now(),
timeoutMs = 12_000,
// JTWC's own deadline, inside NHC's: a slow JTWC never holds NHC's answer.
jtwcTimeoutMs = 8_000,
readJtwc = readJtwcStorms,
} = {}) {
let cache = null;
// JTWC's storms from its last good read, reused while a read fails.
let jtwcCache = null;
let operation = null;
let attemptedAt = -Infinity;
async function upstream(url, cap, signal) {
@@ -286,7 +304,64 @@ export function cycloneProxy({
signal.throwIfAborted();
return result;
}
// A JTWC product: text or bytes; null when JTWC has none posted (403/404).
async function jtwcRead(url, kind, signal) {
signal.throwIfAborted();
const response = await fetchImpl(url, {
signal,
redirect: 'error',
headers: { 'User-Agent': 'Gods Eye View (public JTWC warning context)' },
});
if (
kind === 'bytes' &&
(response.status === 403 || response.status === 404)
) {
await response.body?.cancel();
return null;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error('cyclone_upstream_unavailable');
}
return kind === 'bytes'
? readResponseBytesCapped(response, 4 * 1024 * 1024, signal)
: readResponseTextCapped(response, 256 * 1024, signal);
}
/**
* JTWC's storms, read under their own deadline. A read that fails or runs
* out of time gives JTWC's last good storms still usable, so it never fails,
* delays past its deadline or stales NHC's answer.
*/
async function jtwc(signal) {
const controller = new AbortController();
const abort = () => controller.abort();
signal.addEventListener('abort', abort, { once: true });
const timer = setTimeout(abort, jtwcTimeoutMs);
try {
const storms = await Promise.race([
readJtwc((url, kind) => jtwcRead(url, kind, controller.signal), now()),
new Promise((_, reject) =>
controller.signal.addEventListener(
'abort',
() => reject(new Error('jtwc_timeout')),
{ once: true },
),
),
]);
jtwcCache = storms;
return storms;
} catch {
return (jtwcCache || []).filter(
(storm) => now() - Date.parse(storm.issuedAt) <= JTWC_USABLE_MS,
);
} finally {
clearTimeout(timer);
signal.removeEventListener('abort', abort);
}
}
async function refresh(signal) {
// JTWC is read beside NHC and never rejects.
const pendingJtwc = jtwc(signal);
let storms = parseCycloneStatus(
await upstream(STATUS_URL, 128 * 1024, signal),
now(),
@@ -323,6 +398,14 @@ export function cycloneProxy({
}));
}
}
// One storm per id: NHC's advisory where NHC lists the storm (a storm
// crossing 180° keeps its id), JTWC's elsewhere.
const fromJtwc = await pendingJtwc;
const listed = new Set(storms.map((storm) => storm.id));
storms = [
...storms,
...fromJtwc.filter((storm) => !listed.has(storm.id)),
].slice(0, 32);
signal.throwIfAborted();
cache = { storms, fetchedAt: now() };
return cache;
@@ -365,9 +448,8 @@ export function cycloneProxy({
function describe(value, stale = false) {
return {
schemaVersion: 1,
source: 'NOAA NHC / CPHC',
attribution:
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center',
source: SOURCE,
attribution: ATTRIBUTION,
coverage: COVERAGE,
fetchedAt: value?.fetchedAt ?? null,
stale: stale || !value,
@@ -402,13 +484,16 @@ export function cycloneProxy({
json(200, describe(await acquire(controller.signal)));
} catch (error) {
if (error.status === 429) return json(429, { error: 'cyclone_busy' });
const usable =
cache &&
now() - cache.fetchedAt <= 12 * HOUR &&
cache.storms.every(
(storm) => now() - Date.parse(storm.issuedAt) <= 12 * HOUR,
);
json(200, describe(usable ? cache : null, true));
// Each storm is served while its own advisory is usable.
const usable = cache &&
now() - cache.fetchedAt <= 12 * HOUR && {
...cache,
storms: cache.storms.filter(
(storm) =>
now() - Date.parse(storm.issuedAt) <= cycloneUsableMs(storm),
),
};
json(200, describe(usable || null, true));
}
} finally {
res.removeListener?.('close', close);
-1
View File
@@ -23,7 +23,6 @@ const API_URL =
'attr_IncidentTypeCategory',
'attr_FireDiscoveryDateTime',
'poly_DateCurrent',
'poly_PolygonDateTime',
'attr_FireCause',
'attr_FireBehaviorGeneral',
'attr_TotalIncidentPersonnel',
+459
View File
@@ -0,0 +1,459 @@
import { inflateRawSync } from 'node:zlib';
/**
* Joint Typhoon Warning Center (JTWC) warnings for the cyclone layer: the
* western North Pacific, North Indian Ocean and Southern Hemisphere, where
* NHC and CPHC issue none. Keyless; US government work.
*
* rss/jtwc.rss current warnings, product links in each item
* products/<prefix>.tcw JMV 3.0 warning data (position, forecast, text)
* products/<prefix>.kmz Google Earth overlay: the 34-knot danger swath
*
* JTWC publishes no schema for any of these. Each reader takes only what it
* recognises and throws on a product that lacks it. The danger swath is the
* swath of 34-knot winds widened by forecast track error; it is drawn as its
* own area (`dangerArea`), never as a cone of centre-track uncertainty.
*/
export const JTWC_ORIGIN = 'https://www.metoc.navy.mil';
export const JTWC_RSS_URL = `${JTWC_ORIGIN}/jtwc/rss/jtwc.rss`;
export const JTWC_PRODUCTS_URL = `${JTWC_ORIGIN}/jtwc/products`;
const WARNING_ITEMS = [
'NWPAC-NIO-WARNINGS',
'EPAC-CPAC-WARNINGS',
'SH-WARNINGS',
];
const NO_WARNINGS = 'No Current Tropical Cyclone Warnings';
const PREFIX = /^(?:wp|io|sh|ep|cp)\d{4}$/;
const HOUR = 3600_000;
/**
* A JTWC warning is usable for 13 hours after issuance: some storms are on
* 12-hourly warnings, and the next one posts shortly before its time.
*/
export const JTWC_USABLE_MS = 13 * HOUR;
const KML_MAX_BYTES = 4 * 1024 * 1024;
function invalid(what) {
return new Error(`invalid_jtwc_data: ${what}`);
}
/** Storm product prefixes (`sh0427`) the feed lists, in feed order. */
export function parseJtwcFeed(feed) {
if (typeof feed !== 'string' || !feed.includes('<rss')) throw invalid('feed');
const prefixes = [];
for (const guid of WARNING_ITEMS) {
const item = feed
.split('<item>')
.slice(1)
.map((part) => part.split('</item>')[0])
.find((part) => part.includes(`<guid>${guid}</guid>`));
if (!item) throw invalid(`feed item ${guid}`);
const found = [
...item.matchAll(
/\/jtwc\/products\/([a-z]{2}\d{4})(?:web\.txt|\.tcw|\.kmz)/g,
),
]
.map((match) => match[1])
.filter((prefix) => PREFIX.test(prefix));
if (!found.length && !item.includes(NO_WARNINGS))
throw invalid(`feed item ${guid}`);
for (const prefix of found)
if (!prefixes.includes(prefix)) prefixes.push(prefix);
}
return prefixes;
}
/** `sh0427` is ATCF `sh042027` (the season year). */
export function jtwcStormId(prefix) {
if (!PREFIX.test(prefix)) throw invalid('prefix');
return `${prefix.slice(0, 4)}20${prefix.slice(4)}`;
}
// JTWC's words for a storm, longest first, and their codes.
const KINDS = [
['SUPER TYPHOON', 'STY'],
['SUBTROPICAL STORM', 'SS'],
['SUBTROPICAL DEPRESSION', 'SD'],
['TROPICAL CYCLONE', 'TC'],
['TROPICAL STORM', 'TS'],
['TROPICAL DEPRESSION', 'TD'],
['TYPHOON', 'TY'],
['HURRICANE', 'HU'],
];
/** `115S` / `1642W` (tenths) or `11.6S` (degrees); south and west negative. */
function coordinate(word, tenths) {
const match = /^(\d+(?:\.\d+)?)([NSEW])$/.exec(word || '');
if (!match || (tenths && match[1].includes('.'))) return null;
const value = Number(match[1]) / (tenths ? 10 : 1);
const limit = 'NS'.includes(match[2]) ? 90 : 180;
if (!(value <= limit)) return null;
return 'SW'.includes(match[2]) ? -value : value;
}
function utc(year, month, day, hour, minute = 0) {
const at = Date.UTC(year, month - 1, day, hour, minute);
const date = new Date(at);
return date.getUTCDate() === day && date.getUTCHours() === hour ? at : NaN;
}
/** `ddhhmm` (optionally `Z`-suffixed) as the time nearest `near`. */
function nearest(dtg, near) {
const match = /^(\d\d)(\d\d)(\d\d)Z?[.,]?$/.exec(dtg || '');
if (!match) return NaN;
const base = new Date(near);
let best = NaN;
for (const offset of [-1, 0, 1]) {
const month = new Date(
Date.UTC(base.getUTCFullYear(), base.getUTCMonth() + offset, 1),
);
const at = utc(
month.getUTCFullYear(),
month.getUTCMonth() + 1,
Number(match[1]),
Number(match[2]),
Number(match[3]),
);
if (
Number.isFinite(at) &&
(!Number.isFinite(best) || Math.abs(at - near) < Math.abs(best - near))
)
best = at;
}
return best;
}
const iso = (ms) => new Date(ms).toISOString();
function titleCase(name) {
return name
.toLowerCase()
.replace(
/(^|[\s-])([a-z])/g,
(_, gap, letter) => gap + letter.toUpperCase(),
);
}
/**
* One storm's warning (`.tcw`) as a cyclone-snapshot storm, its geometry
* pending until `withJtwcDangerArea` gives it the warning's danger swath.
* Throws on a warning without its header, hour 0 or subject.
*/
export function parseJtwcWarning(prefix, text) {
const id = jtwcStormId(prefix);
if (typeof text !== 'string') throw invalid('tcw');
const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, ''));
const dtg = lines[0]?.split(/\s+/)[2];
const headerAt = lines.findIndex((line) => /^\d{10}\s/.test(line));
if (headerAt < 0 || !dtg) throw invalid('tcw header');
const header = lines[headerAt].split(/\s+/);
const synopticAt = utc(
Number(header[0].slice(0, 4)),
Number(header[0].slice(4, 6)),
Number(header[0].slice(6, 8)),
Number(header[0].slice(8, 10)),
);
if (!Number.isFinite(synopticAt)) throw invalid('tcw synoptic time');
const number = header[1];
let at = 2;
const nameWords = [];
while (at < header.length && !/^\d+$/.test(header[at]))
nameWords.push(header[at++]);
const numbers = header.slice(at);
const warningMatch = /^0*(\d{1,3})$/.exec(numbers[0] || '');
if (!warningMatch || !number) throw invalid('tcw warning number');
const advisoryNumber = String(Number(warningMatch[1]));
const issuedAt = nearest(dtg, synopticAt);
if (!Number.isFinite(issuedAt)) throw invalid('tcw message time');
const direction = Number(numbers[2]);
const speed = Number(numbers[3]);
const forecast = [];
for (const line of lines.slice(headerAt + 1)) {
const words = line.trim().split(/\s+/);
const tau = /^T(\d{3})$/.exec(words[0]);
if (!tau) break;
const latitude = coordinate(words[1], true);
const longitude = coordinate(words[2], true);
const windKt = Number(words[3]);
if (latitude === null || longitude === null || !/^\d+$/.test(words[3]))
throw invalid('tcw forecast line');
forecast.push({
position: { longitude, latitude },
tauHours: Number(tau[1]),
windKt,
gustKt: null,
});
}
if (forecast[0]?.tauHours !== 0) throw invalid('tcw hour 0');
const subjectAt = lines.findIndex((line) => /^\s*SUBJ/.test(line));
if (subjectAt < 0) throw invalid('tcw subject');
const subject = lines[subjectAt]
.replace(/^\s*SUBJ[:/]?/, '')
.replace(/\/+$/, '')
.trim();
let end = lines.findIndex((line, i) => i > subjectAt && line.trim() === '//');
if (end < 0) end = lines.length;
const body = lines.slice(subjectAt, end);
let tau = null;
for (const line of body) {
const trimmed = line.trim();
const hours = /^(\d+) HRS, VALID AT:$/.exec(trimmed);
if (trimmed.startsWith('WARNING POSITION')) tau = 0;
else if (hours) tau = Number(hours[1]);
else {
const gust = /GUSTS (\d+) KT/.exec(trimmed);
const point = gust && forecast.find((p) => p.tauHours === tau);
if (point && point.gustKt === null) point.gustKt = Number(gust[1]);
}
}
const remarksAt = body.findIndex((line) => /^\s*REMARKS/.test(line));
const remarks = (remarksAt < 0 ? [] : body.slice(remarksAt))
.join(' ')
.replace(/\s+/g, ' ');
const issue = /(\d{6})Z POSITION NEAR (\d+\.\d)([NS]) (\d+\.\d)([EW])/.exec(
remarks,
);
const issueAt = issue ? nearest(issue[1], synopticAt) : NaN;
const pressure = /CENTRAL PRESSURE AT \d{6}Z IS (\d{3,4}) MB/.exec(remarks);
const kind = KINDS.find(([words]) => subject.includes(words));
const first = forecast[0];
const position =
issue && Number.isFinite(issueAt)
? {
longitude: coordinate(`${issue[4]}${issue[5]}`, false),
latitude: coordinate(`${issue[2]}${issue[3]}`, false),
}
: first.position;
if (position.longitude === null || position.latitude === null)
throw invalid('tcw position');
const basin = id.slice(0, 2);
const longitude = position.longitude;
const outlook =
basin === 'io' || (basin === 'sh' && longitude >= 0 && longitude < 135)
? 'abioweb.txt'
: basin === 'wp' || basin === 'sh'
? 'abpwweb.txt'
: null;
const pressureHpa = pressure ? Number(pressure[1]) : null;
const storm = {
id,
agency: 'jtwc',
name: nameWords.length ? titleCase(nameWords.join(' ')) : number,
classification: kind ? kind[1] : 'TC',
basin: basin.toUpperCase(),
position,
positionAt: iso(Number.isFinite(issueAt) ? issueAt : synopticAt),
advisoryNumber,
issuedAt: iso(issuedAt),
windKt: first.windKt <= 300 ? first.windKt : null,
pressureHpa:
pressureHpa !== null && pressureHpa >= 800 && pressureHpa <= 1100
? pressureHpa
: null,
movement: {
directionDegrees:
Number.isInteger(direction) && direction <= 360 ? direction : null,
speedKt: Number.isInteger(speed) && speed <= 200 ? speed : null,
},
advisoryUrl: `${JTWC_PRODUCTS_URL}/${prefix}web.txt`,
outlookUrl: outlook ? `${JTWC_PRODUCTS_URL}/${outlook}` : null,
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
return { storm, forecast };
}
/**
* The storm with its forecast geometry, current only with the danger swath
* of its own warning number (JTWC posts the overlay before the text).
*/
export function withJtwcDangerArea({ storm, forecast }, overlay) {
if (
!overlay ||
overlay.advisoryNumber !== storm.advisoryNumber ||
!overlay.dangerArea ||
forecast.length < 2
)
return storm;
return {
...storm,
geometryStatus: 'current',
geometryAdvisoryNumber: storm.advisoryNumber,
forecastPoints: forecast.map((point) => ({
position: { ...point.position },
tauHours: point.tauHours,
windKt: point.windKt,
gustKt: point.gustKt,
})),
track: {
type: 'LineString',
coordinates: forecast.map((point) => [
point.position.longitude,
point.position.latitude,
]),
},
dangerArea: overlay.dangerArea,
};
}
/** The warning number and 34-knot danger swath of a warning's KML. */
export function parseJtwcKml(kml) {
if (typeof kml !== 'string') throw invalid('kml');
const number = /WARNING NR\s+0*(\d{1,3})\b/.exec(kml);
if (!number) throw invalid('kml warning number');
const polygons = [];
for (const part of kml.split('<Placemark').slice(1)) {
const placemark = part.split('</Placemark>')[0];
const name = /<name>([^<]*)<\/name>/.exec(placemark)?.[1] || '';
if (!/^\s*34 knot Danger Swath/i.test(name)) continue;
for (const polygonPart of placemark.split('<Polygon').slice(1)) {
const polygon = polygonPart.split('</Polygon>')[0];
const rings = [
...polygon.matchAll(/<coordinates>([\s\S]*?)<\/coordinates>/g),
]
.map((match) => ring(match[1]))
.filter(Boolean);
if (rings.length) polygons.push(rings);
}
}
return {
advisoryNumber: String(Number(number[1])),
dangerArea: !polygons.length
? null
: polygons.length === 1
? { type: 'Polygon', coordinates: polygons[0] }
: { type: 'MultiPolygon', coordinates: polygons },
};
}
/**
* `longitude` in -180..180 (180 stays 180). JTWC writes a ring crossing the
* antimeridian with longitudes past ±180 (`181.5`); wrapped, the ring crosses
* 180° as NHC's cones that cross it do.
*/
export function wrapJtwcLongitude(longitude) {
if (Math.abs(longitude) <= 180) return longitude;
const wrapped = ((((longitude + 180) % 360) + 360) % 360) - 180;
// JTWC writes two decimals; this drops the float noise of the wrap.
return Math.round(wrapped * 1e6) / 1e6;
}
function ring(text) {
const points = [];
for (const tuple of text.trim().split(/\s+/)) {
const [lon, lat] = tuple.split(',').map(Number);
if (
!Number.isFinite(lon) ||
!Number.isFinite(lat) ||
Math.abs(lon) > 540 ||
Math.abs(lat) > 90
)
return null;
points.push([wrapJtwcLongitude(lon), lat]);
}
if (!points.length) return null;
const [a, b] = [points[0], points.at(-1)];
if (a[0] !== b[0] || a[1] !== b[1]) points.push([...a]);
return points.length >= 4 ? points : null;
}
/**
* The first `.kml` entry of a KMZ (a zip), from its central directory.
* Stored and deflated entries only.
*/
export function kmlFromKmz(bytes) {
const data = Buffer.from(bytes);
let end = -1;
for (let i = data.length - 22; i >= Math.max(0, data.length - 65_557); i--)
if (data.readUInt32LE(i) === 0x06054b50) {
end = i;
break;
}
if (end < 0) throw invalid('kmz');
const entries = data.readUInt16LE(end + 10);
let at = data.readUInt32LE(end + 16);
for (let n = 0; n < entries; n++) {
if (at + 46 > data.length || data.readUInt32LE(at) !== 0x02014b50)
throw invalid('kmz directory');
const method = data.readUInt16LE(at + 10);
const compressed = data.readUInt32LE(at + 20);
const size = data.readUInt32LE(at + 24);
const nameLength = data.readUInt16LE(at + 28);
const extra = data.readUInt16LE(at + 30);
const comment = data.readUInt16LE(at + 32);
const local = data.readUInt32LE(at + 42);
const name = data.toString('utf8', at + 46, at + 46 + nameLength);
at += 46 + nameLength + extra + comment;
if (!name.toLowerCase().endsWith('.kml')) continue;
if (size > KML_MAX_BYTES || data.readUInt32LE(local) !== 0x04034b50)
throw invalid('kmz entry');
const start =
local +
30 +
data.readUInt16LE(local + 26) +
data.readUInt16LE(local + 28);
const raw = data.subarray(start, start + compressed);
if (method === 0) return raw.toString('utf8');
if (method === 8)
return inflateRawSync(raw, { maxOutputLength: KML_MAX_BYTES }).toString(
'utf8',
);
throw invalid('kmz compression');
}
throw invalid('kmz holds no kml');
}
/**
* Every storm JTWC lists, through `read(url, kind)` (kind `text` or
* `bytes`). A feed that cannot be read throws. One storm never stops the
* others: a warning that cannot be read or parsed leaves that storm out,
* and only when every listed storm's fails does the read throw. An overlay
* that cannot be read leaves its storm's geometry `unavailable`, and one
* JTWC has not posted yet (`read` resolving null), or posted for another
* warning, leaves it `pending`.
*/
export async function readJtwcStorms(read, now = Date.now()) {
const prefixes = parseJtwcFeed(await read(JTWC_RSS_URL, 'text'));
// Each storm's warning and overlay are read at once, every storm alike.
const readStorm = async (prefix) => {
const [text, overlay] = await Promise.all([
read(`${JTWC_PRODUCTS_URL}/${prefix}.tcw`, 'text'),
read(`${JTWC_PRODUCTS_URL}/${prefix}.kmz`, 'bytes')
.then((bytes) =>
bytes === null ? null : parseJtwcKml(kmlFromKmz(bytes)),
)
.catch((error) => {
if (error?.name === 'AbortError') throw error;
return undefined;
}),
]);
if (text === null) throw invalid(`${prefix}.tcw missing`);
const warning = parseJtwcWarning(prefix, text);
const issued = Date.parse(warning.storm.issuedAt);
// A warning past its use, or dated far ahead of this clock, is left out.
if (now - issued > JTWC_USABLE_MS || issued - now > 90 * 60_000)
return null;
// An overlay that could not be read: the geometry is unavailable.
return overlay === undefined
? { ...warning.storm, geometryStatus: 'unavailable' }
: withJtwcDangerArea(warning, overlay);
};
const results = await Promise.allSettled(prefixes.map(readStorm));
const failed = results.filter((result) => result.status === 'rejected');
const aborted = failed.find((result) => result.reason?.name === 'AbortError');
if (aborted) throw aborted.reason;
if (failed.length && failed.length === results.length) throw failed[0].reason;
const storms = [];
for (const result of results) {
const storm = result.status === 'fulfilled' ? result.value : null;
if (storm && !storms.some((held) => held.id === storm.id))
storms.push(storm);
}
return storms;
}
+332
View File
@@ -0,0 +1,332 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { deflateRawSync } from 'node:zlib';
import {
wrapJtwcLongitude,
JTWC_PRODUCTS_URL,
JTWC_RSS_URL,
jtwcStormId,
kmlFromKmz,
parseJtwcFeed,
parseJtwcKml,
parseJtwcWarning,
readJtwcStorms,
withJtwcDangerArea,
} from './jtwc.js';
// Tropical Cyclone 04P (Xavier), warning 15, as JTWC published it on
// 2026-11-21 (past fixes shortened).
const TCW = `WTPS51 PGTW 210300
WARNING ATCG MIL 04P SWP 261121015248
2026112100 04P XAVIER 015 01 245 04 SATL 020
T000 115S 1642W 045 R034 075 NE QD 105 SE QD 090 SW QD 050 NW QD
T012 120S 1652W 045 R034 075 NE QD 105 SE QD 090 SW QD 035 NW QD
T024 125S 1665W 040 R034 070 NE QD 100 SE QD 070 SW QD 020 NW QD
T072 130S 1708W 030
AMP
072HR DISSIPATED AS A SIGNIFICANT TROPICAL CYCLONE OVER WATER
SUBJ: TROPICAL CYCLONE 04P (XAVIER) WARNING NR 015
1. TROPICAL CYCLONE 04P (XAVIER) WARNING NR 015
01 ACTIVE TROPICAL CYCLONE IN SOUTHPAC
---
WARNING POSITION:
210000Z --- NEAR 11.5S 164.2W
MAX SUSTAINED WINDS - 045 KT, GUSTS 055 KT
---
FORECASTS:
12 HRS, VALID AT:
211200Z --- 12.0S 165.2W
MAX SUSTAINED WINDS - 045 KT, GUSTS 055 KT
---
24 HRS, VALID AT:
220000Z --- 12.5S 166.5W
MAX SUSTAINED WINDS - 040 KT, GUSTS 050 KT
---
72 HRS, VALID AT:
240000Z --- 13.0S 170.8W
MAX SUSTAINED WINDS - 030 KT, GUSTS 040 KT
---
REMARKS:
210300Z POSITION NEAR 11.6S 164.5W.
21NOV26. TROPICAL CYCLONE 04P (XAVIER), LOCATED APPROXIMATELY 416
NM EAST-NORTHEAST OF PAGO PAGO, HAS TRACKED WEST-SOUTHWESTWARD AT
04 KNOTS OVER THE PAST SIX HOURS.
MINIMUM CENTRAL PRESSURE AT 210000Z IS 995 MB. MAXIMUM
SIGNIFICANT WAVE HEIGHT AT 210000Z IS 19 FEET. NEXT WARNINGS AT
210900Z, 211500Z, 212100Z AND 220300Z.
//
0426112018 113S1638W 55
0426112100 115S1642W 45
NNNN
`;
const item = (guid, body) =>
`<item><title>${guid}</title><description><![CDATA[${body}]]></description><guid>${guid}</guid></item>`;
const NONE =
"<ul><li><font color='red'>No Current Tropical Cyclone Warnings.</font></li></ul>";
function feed(prefixes = ['sh0427']) {
const links = prefixes
.map(
(prefix) =>
`<li><a href='${JTWC_PRODUCTS_URL}/${prefix}web.txt'>TC Warning Text</a></li><li><a href='${JTWC_PRODUCTS_URL}/${prefix}.tcw'>JMV 3.0 Data</a></li>`,
)
.join('');
return `<?xml version="1.0"?><rss version="2.0"><channel>${item('NWPAC-NIO-WARNINGS', NONE)}${item('EPAC-CPAC-WARNINGS', NONE)}${item('SH-WARNINGS', prefixes.length ? links : NONE)}${item('TROPICAL-ADVISORIES', `<a href="${JTWC_PRODUCTS_URL}/abpwweb.txt">ABPW10</a>`)}</channel></rss>`;
}
const SWATH = [
[-164.02, -9.5],
[-163.0, -12.0],
[-171.0, -14.5],
[-170.0, -11.0],
];
function kml(number = 15) {
return `<kml><Document><Folder>
<Placemark><name>21/00Z (TROPICAL CYCLONE 04P (XAVIER) WARNING NR ${number} - 45 knots)</name>
<Point><coordinates>-164.2,-11.5,0</coordinates></Point></Placemark>
<Placemark><name>RADIUS OF 34 KT WINDS</name><Polygon><outerBoundaryIs><LinearRing><coordinates>-164.2,-10.25,0 -163,-11,0 -164.2,-12.5,0 -164.2,-10.25,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
<Placemark><name>34 knot Danger Swath</name><Polygon><outerBoundaryIs><LinearRing><coordinates>
${SWATH.map(([lon, lat]) => `${lon},${lat},0`).join(' ')}
</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
</Folder></Document></kml>`;
}
/** A zip holding `files` ({name: text}), deflated. */
function zip(files) {
const locals = [],
central = [];
let offset = 0;
for (const [name, text] of Object.entries(files)) {
const data = Buffer.from(text);
const packed = deflateRawSync(data);
const nameBytes = Buffer.from(name);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(8, 8);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(nameBytes.length, 26);
const entry = Buffer.alloc(46);
entry.writeUInt32LE(0x02014b50, 0);
entry.writeUInt16LE(8, 10);
entry.writeUInt32LE(packed.length, 20);
entry.writeUInt32LE(data.length, 24);
entry.writeUInt16LE(nameBytes.length, 28);
entry.writeUInt32LE(offset, 42);
locals.push(local, nameBytes, packed);
central.push(entry, nameBytes);
offset += 30 + nameBytes.length + packed.length;
}
const directory = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(Object.keys(files).length, 8);
end.writeUInt16LE(Object.keys(files).length, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
return new Uint8Array(Buffer.concat([...locals, directory, end]));
}
const NOW = Date.UTC(2026, 10, 21, 3, 20);
test('the feed lists the storms of the warning items and refuses anything else', () => {
assert.deepEqual(parseJtwcFeed(feed()), ['sh0427']);
assert.deepEqual(parseJtwcFeed(feed([])), []);
assert.deepEqual(parseJtwcFeed(feed(['wp3026', 'sh0427', 'wp3026'])), [
'wp3026',
'sh0427',
]);
assert.throws(() => parseJtwcFeed('<html>blocked</html>'));
assert.throws(() =>
parseJtwcFeed(feed().replace('<guid>SH-WARNINGS', '<guid>OTHER')),
);
assert.throws(() => parseJtwcFeed(feed([]).replaceAll(NONE, '<ul></ul>')));
});
test('product prefixes are season-year ATCF ids', () => {
assert.equal(jtwcStormId('sh0427'), 'sh042027');
assert.equal(jtwcStormId('wp3026'), 'wp302026');
assert.throws(() => jtwcStormId('al0126'));
});
test('a warning reads as a pending JTWC storm with its forecast', () => {
const { storm, forecast } = parseJtwcWarning('sh0427', TCW);
assert.deepEqual(
{ ...storm },
{
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
// Where the storm was at issuance, from the remarks.
position: { longitude: -164.5, latitude: -11.6 },
positionAt: '2026-11-21T03:00:00.000Z',
advisoryNumber: '15',
issuedAt: '2026-11-21T03:00:00.000Z',
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
},
);
assert.deepEqual(
forecast.map((point) => [point.tauHours, point.windKt, point.gustKt]),
[
[0, 45, 55],
[12, 45, 55],
[24, 40, 50],
[72, 30, 40],
],
);
assert.deepEqual(forecast[0].position, { longitude: -164.2, latitude: -11.5 });
});
test('classes come from the subject; broken warnings throw', () => {
const typhoon = TCW.replace(
'SUBJ: TROPICAL CYCLONE 04P',
'SUBJ: SUPER TYPHOON 04P',
);
assert.equal(parseJtwcWarning('sh0427', typhoon).storm.classification, 'STY');
for (const broken of [
'',
'<html>Access Denied</html>',
TCW.replace(/^T000.*$/m, ''),
TCW.replace('SUBJ:', 'XXXX:'),
TCW.replace('T000 115S', 'T000 115X'),
])
assert.throws(() => parseJtwcWarning('sh0427', broken), /invalid_jtwc/);
});
test('the danger swath makes the geometry current only for its own warning', () => {
const warning = parseJtwcWarning('sh0427', TCW);
const overlay = parseJtwcKml(kml(15));
assert.equal(overlay.advisoryNumber, '15');
assert.deepEqual(overlay.dangerArea, {
type: 'Polygon',
coordinates: [[...SWATH, SWATH[0]]],
});
const storm = withJtwcDangerArea(warning, overlay);
assert.equal(storm.geometryStatus, 'current');
assert.equal(storm.geometryAdvisoryNumber, '15');
assert.equal(storm.cone, null);
assert.deepEqual(storm.track.coordinates[0], [-164.2, -11.5]);
assert.equal(storm.forecastPoints.length, 4);
assert.equal(
withJtwcDangerArea(warning, parseJtwcKml(kml(14))).geometryStatus,
'pending',
);
assert.equal(withJtwcDangerArea(warning, null).geometryStatus, 'pending');
assert.throws(() => parseJtwcKml('<kml></kml>'));
});
test('the KML is read out of the KMZ', () => {
assert.equal(
kmlFromKmz(zip({ 'images/logo.png': 'png', 'doc.kml': kml() })),
kml(),
);
assert.throws(() => kmlFromKmz(new Uint8Array([1, 2, 3])));
assert.throws(() => kmlFromKmz(zip({ 'logo.png': 'png' })));
});
function reader(answers) {
const calls = [];
const read = async (url, kind) => {
calls.push(url);
const answer = answers[url];
if (answer instanceof Error) throw answer;
if (answer === undefined) return null;
return kind === 'bytes' ? answer : String(answer);
};
return { read, calls };
}
test('every listed storm is read with its overlay; an unreadable overlay leaves its geometry unavailable', async () => {
const products = (prefix, kmz) => ({
[`${JTWC_PRODUCTS_URL}/${prefix}.tcw`]: TCW,
[`${JTWC_PRODUCTS_URL}/${prefix}.kmz`]: kmz,
});
const good = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', zip({ 'doc.kml': kml() })),
});
const [storm] = await readJtwcStorms(good.read, NOW);
assert.equal(storm.geometryStatus, 'current');
assert.deepEqual(good.calls.sort(), [
`${JTWC_PRODUCTS_URL}/sh0427.kmz`,
`${JTWC_PRODUCTS_URL}/sh0427.tcw`,
JTWC_RSS_URL,
]);
const notPosted = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', undefined),
});
assert.equal(
(await readJtwcStorms(notPosted.read, NOW))[0].geometryStatus,
'pending',
);
const broken = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', new Uint8Array([1, 2, 3])),
});
assert.equal(
(await readJtwcStorms(broken.read, NOW))[0].geometryStatus,
'unavailable',
);
// A warning past 13 hours is left out; with every listed warning missing,
// the read fails.
assert.deepEqual(
await readJtwcStorms(good.read, NOW + 13 * 3600_000),
[],
);
const missing = reader({ [JTWC_RSS_URL]: feed() });
await assert.rejects(readJtwcStorms(missing.read, NOW), /invalid_jtwc/);
const down = reader({ [JTWC_RSS_URL]: new Error('down') });
await assert.rejects(readJtwcStorms(down.read, NOW), /down/);
});
test('one storm whose warning cannot be read or parsed never stops the others', async () => {
const { read } = reader({
[JTWC_RSS_URL]: feed(['wp3026', 'sh0427', 'io0126']),
[`${JTWC_PRODUCTS_URL}/wp3026.tcw`]: new Error('HTTP 500'),
[`${JTWC_PRODUCTS_URL}/io0126.tcw`]: '<html>Access Denied</html>',
[`${JTWC_PRODUCTS_URL}/sh0427.tcw`]: TCW,
[`${JTWC_PRODUCTS_URL}/sh0427.kmz`]: zip({ 'doc.kml': kml() }),
});
const storms = await readJtwcStorms(read, NOW);
assert.deepEqual(
storms.map((storm) => [storm.id, storm.geometryStatus]),
[['sh042027', 'current']],
);
});
test('a danger swath crossing the antimeridian is kept, its longitudes wrapped', () => {
const crossing = kml().replace(
/<coordinates>\n[^<]*<\/coordinates>/,
'<coordinates>179.5,-15,0 181,-16,0 180.5,-18,0 179.5,-17,0</coordinates>',
);
assert.deepEqual(parseJtwcKml(crossing).dangerArea, {
type: 'Polygon',
coordinates: [
[
[179.5, -15],
[-179, -16],
[-179.5, -18],
[179.5, -17],
[179.5, -15],
],
],
});
assert.equal(wrapJtwcLongitude(-181.5), 178.5);
assert.equal(wrapJtwcLongitude(180), 180);
assert.equal(wrapJtwcLongitude(-164.2), -164.2);
});
-4
View File
@@ -67,8 +67,6 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
* places live aircraft, vessels, transit and trains; without one each layer
* uses its own motion.
* `perimeterOptions: { inciweb: false }` leaves the Fire Perimeters cards
* without InciWeb links, and the layer never asks InciWeb.
*/
export function createApplicationCatalog({
surface,
@@ -77,7 +75,6 @@ export function createApplicationCatalog({
metadata = APPLICATION_LAYER_METADATA,
vesselOptions,
newsOptions,
perimeterOptions,
resolveAsset,
nepalBoundaryResolver,
streetLevelProviders,
@@ -148,7 +145,6 @@ export function createApplicationCatalog({
createApplicationEarthquakes({ source: sources.earthquakes }),
createApplicationAirQuality({ source: sources['air-quality'] }),
createApplicationFirePerimeters({
...perimeterOptions,
source: sources['fire-perimeters'],
}),
createApplicationGnssIntegrity({
+4 -15
View File
@@ -6,15 +6,8 @@ import {
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
/**
* Wire fire perimeters into the application catalog. `inciweb: false`
* creates no InciWeb sources, so the cards carry no links and InciWeb is
* never asked.
*/
export function createApplicationFirePerimeters({
inciweb = true,
...options
} = {}) {
/** Wire WFIGS fire perimeters into the application catalog. */
export function createApplicationFirePerimeters(options) {
return createFirePerimetersLayer({
overlayHost: {
setEntries: overlays.setOverlayEntries,
@@ -22,12 +15,8 @@ export function createApplicationFirePerimeters({
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
...(inciweb === false
? {}
: {
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
}),
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
picking,
...options,
-51
View File
@@ -1,51 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createApplicationFirePerimeters } from './perimeters.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
const ring = [
[-108.1, 35.2],
[-108.0, 35.2],
[-108.0, 35.3],
[-108.1, 35.2],
];
const source = {
getSnapshot: async () => ({
at: null,
fetchedAt: null,
stale: false,
revision: 'r',
note: null,
fires: [{ id: 'f', name: 'Fixture', anchor: { lon: -108.05, lat: 35.25 } }],
pieces: [{ fireId: 'f', born: null, polygons: [[ring]], outline: [ring] }],
}),
};
for (const inciweb of [true, false]) {
test(`inciweb: ${inciweb} ${inciweb ? 'asks' : 'never asks'} InciWeb`, async (t) => {
const requested = [];
t.mock.method(globalThis, 'fetch', async (url) => {
requested.push(String(url));
return Response.json([]);
});
const viewer = { scene: { pick: () => null } };
bindFakeDraw(viewer);
const input = fakeInput(viewer);
t.after(() => input.destroy());
const layer = createApplicationFirePerimeters({
source,
inciweb,
inputFor: () => input.input,
});
layer.init(viewer);
layer.enable(viewer);
assert.equal(await layer.update(viewer), true);
await new Promise(setImmediate);
assert.deepEqual(
requested.filter((url) => url.includes('inciweb')),
inciweb ? ['/api/fire-perimeters/inciweb/index'] : [],
);
layer.destroy(viewer);
});
}
+3
View File
@@ -17,6 +17,7 @@ import {
import { initGeoFileImport } from '../ui/geoFileImport.js';
import { useDisplayStore } from '../ui/stores/display.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { createContextCardOpener } from '../ui/stores/entityCard.js';
import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
import { createRecentImageryPanel } from '../ui/recentImagery.js';
import { createDataLibrary } from '../library/controller.js';
@@ -349,6 +350,8 @@ export function createApplicationTools({
dataManager,
sceneDirector,
annotations,
// A voice or chat selection opens its card in Context, as a click does.
contextCard: createContextCardOpener(applicationPinia()),
});
defer(() => {
voiceCommands.stop({ removeUi: true });
+20 -6
View File
@@ -1165,7 +1165,10 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
mobileCockpit[1],
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
);
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
assert.match(
css,
/\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/,
);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
@@ -1185,8 +1188,14 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
});
test('the unread Stories announcement waits until Cockpit closes', () => {
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
assert.match(
css,
/body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/,
);
const storiesView = fs.readFileSync(
path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'),
'utf8',
);
assert.match(
storiesView,
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
@@ -1374,12 +1383,17 @@ test('voice Cockpit entry honours a requested contact layer before it enters', (
const retarget = ui.slice(
ui.indexOf(' _retargetCockpitEntryLayer({'),
ui.indexOf(' * Controls cockpit entry/exit and context navigation.'),
ui.indexOf(' controlCockpit(\n'),
);
assert.match(
retarget,
/militaryAwarenessLayer\.navigateNext\(\{\s*targetLayer,\s*aircraftClass,\s*origin: 'voice',\s*\}\)/,
'retargeting reuses filtered navigation with durable voice selection authority',
/layer\.trackById\?\.\(match\.icao24, \{ origin: 'voice' \}\)/,
'retargeting follows the match with durable voice selection authority',
);
assert.doesNotMatch(
retarget,
/militaryAwarenessLayer/,
'retargeting needs nothing from Contacts',
);
assert.match(
retarget,
+42 -12
View File
@@ -33,6 +33,7 @@ import {
} from './aircraftIcons.js';
import { cockpitContactDotImage } from './cockpitContactDot.js';
import { rotorFrame, rotorTurns } from './rotorFrames.js';
import { registerAircraftViews, withAircraftView } from './aircraftViews.js';
import { aircraftRecedeSpec } from './aircraftRecession.js';
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
@@ -436,6 +437,8 @@ function fixedDelay(ms) {
* Where a host-supplied placement draws a live contact at a wall time,
* written into `out` (`placeAircraftAt`), or null when it does not place
* it; none without a placement.
* @param {(url: string) => string} [options.resolveAsset] The layer's asset
* URL resolver, for the aircraft view sheet's image.
*/
export function createAircraftIcons({
state,
@@ -453,10 +456,14 @@ export function createAircraftIcons({
afterSettle = () => {},
onForget = () => {},
placeAt = null,
resolveAsset = (url) => url,
}) {
const { focusPassIsNeeded } = services.focus;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** Whether the renderer draws icons along their course from the aircraft
* view sheet (`aircraftViews.js`), set when the draw set is made. */
let views = false;
/**
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
* frame each was last drawn at, and the frame it was last judged at
@@ -544,9 +551,9 @@ export function createAircraftIcons({
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
});
const capabilities = rendererOf(viewer)?.capabilities ?? null;
views = registerAircraftViews(drawOf(viewer), capabilities, resolveAsset);
state._icons = createContactIcons(set, { capabilities });
return set.id;
}
@@ -555,6 +562,7 @@ export function createAircraftIcons({
state._icons?.dispose();
state._icons = null;
liveSet = null;
views = false;
rotors.clear();
planFrom.clear();
easeEnds.clear();
@@ -962,19 +970,26 @@ export function createAircraftIcons({
* How a contact's icon is drawn outside Cockpit: its image (and the sharper
* one it switches to up close), size, scale and scale by distance. The
* tracked contact's own icon is drawn with this too, so selecting a contact
* changes its colour and nothing else.
* changes its colour and nothing else. Drawn along its course
* (`alongCourse`) on a renderer that draws view sheets, a kind with
* rendered views draws from the aircraft view sheet, with no near image
* (`aircraftViews.js`); otherwise it is the flat glyph.
* @param {string} icao24
* @param {object} [info] Its record.
* @returns {{image: string, imageLod: {near: string, switchPx: number},
* @param {number} [frame] A helicopter's rotor frame.
* @param {{alongCourse?: boolean}} [options]
* @returns {{image: string|{views: string, first: number},
* imageLod: {near: string, switchPx: number}|undefined,
* size: [number, number], scale: number, scaleByDistance: object}}
*/
function _fleetLook(
icao24,
info = state.records.data.get(icao24),
frame = _rotorFrameOf(icao24, info, Date.now()),
{ alongCourse = false } = {},
) {
const rendering = parts.rendering;
return {
const look = {
image: aircraftIcon(
rendering._iconKind(icao24, info?.klass),
FLEET_ICON_PX,
@@ -992,6 +1007,17 @@ export function createAircraftIcons({
scale: rendering._fleetBillboardScale(icao24),
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
};
return withAircraftView(look, {
views,
kind: rendering._iconKind(icao24, info?.klass),
frame,
rotationMode: alongCourse ? 'course' : undefined,
});
}
/** Whether contacts drawn along their course draw from the view sheet. */
function _drawsViews() {
return views;
}
/**
@@ -1051,6 +1077,7 @@ export function createAircraftIcons({
id,
state.records.data.get(id),
frame,
{ alongCourse: icons.item(id)?.rotationMode === 'course' },
);
icons.update(id, { image, imageLod });
}
@@ -1064,6 +1091,11 @@ export function createAircraftIcons({
const rendering = parts.rendering;
const info = state.records.data.get(icao24);
const tracked = icao24 === state._trackedIcao;
// A helicopter's rotor frame, chosen once for its look and its rotor.
const heliFrame = _rotorFrameOf(icao24, info, Date.now());
// A ground station's mast stands upright; every other glyph turns
// along its course.
const station = info?.klass === 'station';
const cockpitDot =
state._cockpitContactMode &&
!tracked &&
@@ -1079,21 +1111,18 @@ export function createAircraftIcons({
rotationMode: 'screen',
}
: {
..._fleetLook(icao24, info),
..._fleetLook(icao24, info, heliFrame, { alongCourse: !station }),
color: rgba(rendering._fleetBillboardColor(icao24, info)),
rotationMode: 'course',
};
// A ground station's mast stands upright.
if (!cockpitDot && info?.klass === 'station') {
if (!cockpitDot && station) {
look.rotationMode = 'screen';
look.rotation = 0;
}
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
icons.update(icao24, look);
// An airborne helicopter drawn as its glyph turns its rotor.
const frame = cockpitDot
? undefined
: _rotorFrameOf(icao24, info, Date.now());
const frame = cockpitDot ? undefined : heliFrame;
if (frame === undefined || !rotorTurns(_rotorState(info))) {
// A tracked helicopter that lands shows the still frame at once.
if (rotors.delete(icao24) && tracked)
@@ -1176,6 +1205,7 @@ export function createAircraftIcons({
_focusIcons,
_applyIconPresentation,
_fleetLook,
_drawsViews,
_turnRotors,
_rotorsTurning,
_addIcon,
+180
View File
@@ -481,3 +481,183 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/**
* An icon layer on a renderer that does (or does not) draw view sheets,
* over contacts `records` (by id), all held at one place.
*/
function viewsFixture(
records,
{ viewSheets = true, kinds = {}, resolveAsset } = {},
) {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer, {
capabilities: new Set(viewSheets ? ['viewSheets'] : []),
});
const state = {
_viewer: viewer,
now: () => Date.now(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (id, klass) => kinds[id] ?? klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1.25,
_cockpitContactColor: () => [1, 0, 0, 1],
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
resolveAsset,
});
icons._createIcons(viewer);
const here = fromDegrees(0, 30, 300);
for (const id of records.keys()) {
state._icons.put(
{ id, pos: here, motion: { kind: 'hold', courseDeg: 0 }, size: [20, 20] },
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons, registered: draw.viewSheets, here, unbind };
}
test('with view sheets, every aircraft class draws from the sheet along its course, with no near image', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const records = new Map([
['p1', { klass: 'airliner' }],
['p2', { klass: 'glider' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, icons, registered, unbind } = viewsFixture(records);
t.after(unbind);
assert.deepEqual(registered, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftViewRef('airliner'));
assert.equal(p1.imageLod, undefined);
assert.equal(p1.rotationMode, 'course');
// Everything else is as the flat glyph draws it.
assert.deepEqual(p1.size, [20, 20]);
assert.equal(p1.scale, 1.25);
assert.deepEqual(p1.color, [1, 1, 1, 1]);
assert.equal(p1.scaleByDistance.nearValue, 3);
assert.equal(state._icons.item('p2').image, aircraftViewRef('glider'));
assert.equal(
state._icons.item('h1').image,
aircraftViewRef('helicopter', ROTOR_STILL_FRAME),
);
// The plain fleet look (the tracked icon's sizing, a screen-rotated
// caller) stays the flat glyph.
assert.equal(
icons._fleetLook('p1').image,
aircraftIcon('airliner', FLEET_ICON_PX),
);
assert.equal(
icons._fleetLook('p1', undefined, undefined, { alongCourse: true }).image,
aircraftViewRef('airliner'),
);
assert.equal(icons._drawsViews(), true);
icons._disposeIcons();
assert.equal(icons._drawsViews(), false);
});
test('without view sheets the icons are the flat glyphs with their near image, as before', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['p1', { klass: 'airliner' }]]);
const { state, icons, registered, unbind } = viewsFixture(records, {
viewSheets: false,
});
t.after(unbind);
assert.deepEqual(registered, [], 'no sheet is registered');
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftIcon('airliner', FLEET_ICON_PX));
assert.equal(p1.imageLod.near, aircraftIcon('airliner', 192));
assert.equal(p1.rotationMode, 'course');
assert.equal(icons._drawsViews(), false);
});
test('with view sheets, the TR-3B, airport vehicles and ground stations stay flat', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['x1', { klass: 'airliner' }],
['v1', { klass: 'vehicle' }],
['s1', { klass: 'station' }],
]);
const { state, unbind } = viewsFixture(records, {
kinds: { x1: 'tr3b' },
});
t.after(unbind);
assert.equal(
state._icons.item('x1').image,
aircraftIcon('tr3b', FLEET_ICON_PX),
);
assert.ok(state._icons.item('x1').imageLod);
assert.equal(
state._icons.item('v1').image,
aircraftIcon('vehicle', FLEET_ICON_PX),
);
const mast = state._icons.item('s1');
assert.equal(mast.image, aircraftIcon('station', FLEET_ICON_PX));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('with view sheets, an airborne helicopter turns its rotor through the sheet’s three blocks', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
const { state, icons, unbind } = viewsFixture(records);
t.after(unbind);
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now());
const item = state._icons.item('h1');
assert.equal(item.imageLod, undefined);
seen.add(item.image);
}
assert.deepEqual(
new Set(seen),
new Set([0, 1, 2].map((frame) => aircraftViewRef('helicopter', frame))),
);
});
test('the layer registers the view sheet at its own asset URL', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const { registered, unbind } = viewsFixture(
new Map([['p1', { klass: 'airliner' }]]),
{ resolveAsset: (url) => `/gev/${url.replace(/^\//, '')}` },
);
t.after(unbind);
assert.equal(registered.length, 1);
assert.equal(registered[0][0], AIRCRAFT_VIEWS.id);
assert.equal(registered[0][1].image, '/gev/sprites/aircraft-views.webp');
});
test('a view carries the contact’s flat glyph as its fallback', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['p1', { klass: 'turboprop' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, unbind } = viewsFixture(records);
t.after(unbind);
assert.equal(
state._icons.item('p1').image.fallback,
aircraftIcon('turboprop', FLEET_ICON_PX),
);
assert.equal(
state._icons.item('h1').image.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
+138
View File
@@ -0,0 +1,138 @@
/**
* @module data/aircraftViews
* @description Which block of the aircraft view sheet (`viewSheet.js`) a
* contact's icon draws from. Each aircraft class is rendered there from a
* sphere of camera angles; a renderer with the `viewSheets` capability lays
* the icon flat on the earth along its course and draws the view that
* matches where the eye is, so an oblique contact looks solid instead of
* like a paper cut-out. Only an icon drawn along its course
* (`rotationMode: 'course'`) can do this: a screen-rotated or upright icon
* keeps its flat glyph. Kinds with no rendered views (the TR-3B triangle,
* airport vehicles, ground stations) keep their flat glyph as well.
*/
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import {
aircraftIcon,
FLEET_ICON_PX,
ROTOR_FRAMES,
ROTOR_STILL_FRAME,
} from './aircraftIcons.js';
/** The renderer capability that draws view sheets. */
export const VIEW_SHEETS_CAPABILITY = 'viewSheets';
/** Kinds drawn from the sheet with one block each (helicopters have three). */
const STILL_KINDS = new Set([
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
]);
/** One frozen image ref per block, so equal refs are the same object. */
const refs = new Map();
/**
* The ref of the block at `first`, with the flat glyph of `kind` (and its
* rotor `frame`) as its fallback: what the renderer draws until the sheet
* has loaded, and for good if it cannot load.
*/
function refAt(first, kind, frame) {
let ref = refs.get(first);
if (!ref) {
ref = Object.freeze({
views: AIRCRAFT_VIEWS.id,
first,
fallback: aircraftIcon(kind, FLEET_ICON_PX, frame),
});
refs.set(first, ref);
}
return ref;
}
/**
* The view image of an icon kind: `{views, first, fallback}`, the sheet's
* id, the first cell of the kind's block and its flat glyph (drawn while
* the sheet loads, or if it fails), or null for a kind with no views.
* @param {string} kind An icon kind (`rendering._iconKind`).
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame otherwise, as `aircraftIcon` takes it).
* @returns {{views: string, first: number, fallback: string}|null}
*/
export function aircraftViewRef(kind, frame) {
const subjects = AIRCRAFT_VIEWS.subjects;
if (kind === 'helicopter') {
const f =
Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME;
const first = subjects[`helicopter${f}`];
return Number.isInteger(first) ? refAt(first, kind, f) : null;
}
if (!STILL_KINDS.has(kind)) return null;
const first = subjects[kind];
return Number.isInteger(first) ? refAt(first, kind) : null;
}
/** Whether an icon image is a view-sheet ref. */
export function isAircraftViewRef(image) {
return Boolean(image) && typeof image === 'object' && 'views' in image;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the aircraft view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerAircraftViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.(VIEW_SHEETS_CAPABILITY)) return false;
if (!registered.has(drawPort)) {
const sheet = AIRCRAFT_VIEWS.sheet;
drawPort.views(AIRCRAFT_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
/**
* An icon's look drawn from the view sheet where it can be: with views on,
* the item drawn along its course and the kind rendered, the image is the
* view ref and there is no near image (`imageLod: undefined`, so an update
* clears it); otherwise the look as given, the very same object.
* @template {{image: unknown, imageLod?: unknown}} T
* @param {T} look
* @param {object} options
* @param {boolean} options.views Whether the renderer draws views
* (`registerAircraftViews`).
* @param {string} options.kind The icon kind.
* @param {number} [options.frame] A helicopter's rotor frame.
* @param {string} [options.rotationMode] How the item is rotated.
* @returns {T}
*/
export function withAircraftView(look, { views, kind, frame, rotationMode }) {
if (!views || rotationMode !== 'course') return look;
const ref = aircraftViewRef(kind, frame);
if (!ref) return look;
return { ...look, image: ref, imageLod: undefined };
}
+175
View File
@@ -0,0 +1,175 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
aircraftViewRef,
isAircraftViewRef,
registerAircraftViews,
VIEW_SHEETS_CAPABILITY,
withAircraftView,
} from './aircraftViews.js';
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './rotorFrames.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
const STILL_KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
];
test('every aircraft class draws its own block of the view sheet', () => {
for (const kind of STILL_KINDS)
assert.deepEqual(
aircraftViewRef(kind),
{
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects[kind],
fallback: aircraftIcon(kind, FLEET_ICON_PX),
},
kind,
);
const firsts = STILL_KINDS.map((kind) => aircraftViewRef(kind).first);
assert.equal(
new Set(firsts).size,
STILL_KINDS.length,
'no two share a block',
);
assert.equal(
aircraftViewRef('airliner'),
aircraftViewRef('airliner'),
'one ref per block, so an unchanged image writes nothing',
);
assert.ok(Object.isFrozen(aircraftViewRef('airliner')));
});
test('a helicopter draws the block of its rotor frame, the still frame by default', () => {
assert.equal(ROTOR_FRAMES, 3);
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
const ref = aircraftViewRef('helicopter', frame);
assert.equal(
ref.first,
AIRCRAFT_VIEWS.subjects[`helicopter${frame}`],
`frame ${frame}`,
);
assert.equal(
ref.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, frame),
`its fallback is the glyph of rotor frame ${frame}`,
);
}
assert.equal(
aircraftViewRef('helicopter').fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const still = AIRCRAFT_VIEWS.subjects[`helicopter${ROTOR_STILL_FRAME}`];
for (const frame of [undefined, -1, 3, 1.5, NaN])
assert.equal(aircraftViewRef('helicopter', frame).first, still, `${frame}`);
});
test('the TR-3B, airport vehicles, ground stations and unknown kinds have no views', () => {
for (const kind of [
'tr3b',
'tr3bHot',
'vehicle',
'station',
'jet',
'',
undefined,
])
assert.equal(aircraftViewRef(kind), null, String(kind));
assert.equal(
aircraftViewRef('airliner', 1).first,
0,
'a frame means nothing to a fixed wing',
);
});
test('a view ref is told apart from flat images', () => {
assert.equal(isAircraftViewRef(aircraftViewRef('glider')), true);
for (const image of [
'data:image/svg+xml;base64,AAA',
null,
undefined,
{ atlas: 'a', slot: 's' },
])
assert.equal(isAircraftViewRef(image), false, String(image));
});
test('the sheet is registered once per draw port, only with the capability', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
assert.equal(VIEW_SHEETS_CAPABILITY, 'viewSheets');
assert.equal(registerAircraftViews(port, new Set()), false);
assert.equal(registerAircraftViews(port, null), false);
assert.equal(calls.length, 0, 'nothing registered without the capability');
assert.equal(registerAircraftViews(port, caps), true);
assert.equal(registerAircraftViews(port, caps), true);
assert.deepEqual(calls, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const other = { views: (id) => calls.push([id]) };
assert.equal(registerAircraftViews(other, caps), true);
assert.equal(calls.length, 2, 'a second port registers its own');
assert.equal(
registerAircraftViews({}, caps),
false,
'a port without views()',
);
assert.equal(registerAircraftViews(null, caps), false);
});
test('a look takes the view only when views are on and it is drawn along its course', () => {
const look = {
image: 'flat',
imageLod: { near: 'near', switchPx: 30 },
size: [20, 20],
scale: 1.5,
};
const on = { views: true, kind: 'airliner', rotationMode: 'course' };
const viewed = withAircraftView(look, on);
assert.deepEqual(viewed, {
image: aircraftViewRef('airliner'),
imageLod: undefined,
size: [20, 20],
scale: 1.5,
});
assert.ok('imageLod' in viewed, 'imageLod is cleared, so an update drops it');
assert.equal(look.image, 'flat', 'the look given is left as it was');
assert.equal(withAircraftView(look, { ...on, views: false }), look);
assert.equal(withAircraftView(look, { ...on, rotationMode: 'screen' }), look);
assert.equal(
withAircraftView(look, { ...on, rotationMode: undefined }),
look,
);
assert.equal(withAircraftView(look, { ...on, kind: 'tr3b' }), look);
assert.equal(withAircraftView(look, { ...on, kind: 'station' }), look);
assert.equal(
withAircraftView(look, { ...on, kind: 'helicopter', frame: 2 }).image,
aircraftViewRef('helicopter', 2),
);
});
test('the sheet is registered with its image resolved as the layer resolves its assets', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
registerAircraftViews(port, caps, (url) => `https://cdn.example/app${url}`);
assert.equal(calls.length, 1);
const [id, sheet] = calls[0];
assert.equal(id, AIRCRAFT_VIEWS.id);
assert.equal(
sheet.image,
'https://cdn.example/app/sprites/aircraft-views.webp',
);
assert.deepEqual(
{ ...sheet, image: AIRCRAFT_VIEWS.sheet.image },
{ ...AIRCRAFT_VIEWS.sheet },
'the layout as it is',
);
assert.equal(AIRCRAFT_VIEWS.sheet.image, '/sprites/aircraft-views.webp');
});
+161 -2
View File
@@ -74,7 +74,12 @@ function collections(adv = '10') {
}
function install(options = {}, preview = false) {
let handler;
const plugin = cycloneProxy({ now: () => NOW, ...options });
// JTWC has its own tests below; these cover NHC alone.
const plugin = cycloneProxy({
now: () => NOW,
readJtwc: async () => [],
...options,
});
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: {
use(path, callback) {
@@ -297,7 +302,7 @@ test('dev and preview serve only fixed bounded NOAA queries, caching a complete
const snapshot = body(await request());
assert.equal(snapshot.unavailable, false);
assert.equal(snapshot.stale, false);
assert.match(snapshot.coverage, /not worldwide/);
assert.match(snapshot.coverage, /JTWC: western North Pacific/);
assert.equal(snapshot.storms[0].geometryStatus, 'current');
assert.equal(snapshot.fetchedAt, NOW);
assert.equal(calls.length, 4);
@@ -491,3 +496,157 @@ test('shared refresh caps waiting consumers and rejects redirects without exposi
});
assert.equal(body(await redirected.request()).unavailable, true);
});
function jtwcStorm(overrides = {}) {
return {
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
position: { longitude: -164.5, latitude: -11.6 },
positionAt: TIME,
advisoryNumber: '15',
issuedAt: TIME,
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
...overrides,
};
}
test('JTWC storms join NHC’s, and NHC’s advisory wins for a storm both list', async () => {
const crossing = jtwcStorm({
id: 'ep152026',
basin: 'EP',
name: 'JTWC copy',
});
const { request } = install({
fetchImpl: fetcher(),
readJtwc: async () => [jtwcStorm(), crossing],
});
const snapshot = body(await request());
assert.deepEqual(
snapshot.storms.map((storm) => [storm.id, storm.agency, storm.name]),
[
['ep152026', 'nhc', 'Fifteen-E'],
['sh042027', 'jtwc', 'Xavier'],
],
);
assert.equal(snapshot.stale, false);
assert.match(snapshot.source, /JTWC/);
assert.match(snapshot.attribution, /Joint Typhoon Warning Center/);
});
test('JTWC reads go through the bounded fetch with no redirects', async () => {
const calls = [];
const { request } = install({
fetchImpl: async (url, options) => {
calls.push({ url, options });
if (url.includes('jtwc.rss'))
return new Response(
'<rss><item><guid>NWPAC-NIO-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>EPAC-CPAC-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>SH-WARNINGS</guid>No Current Tropical Cyclone Warnings</item></rss>',
);
return fetcher()(url, options);
},
readJtwc: undefined,
});
const snapshot = body(await request());
assert.equal(snapshot.stale, false);
const jtwc = calls.filter(({ url }) => url.includes('metoc.navy.mil'));
assert.deepEqual(
jtwc.map(({ url }) => url),
['https://www.metoc.navy.mil/jtwc/rss/jtwc.rss'],
);
assert.equal(jtwc[0].options.redirect, 'error');
});
test('a failed JTWC read keeps its last storms and leaves NHC’s answer fresh', async () => {
let fail = false;
let clock = NOW;
const { request } = install({
fetchImpl: fetcher(),
now: () => clock,
readJtwc: async () => {
if (fail) throw new Error('jtwc down');
return [jtwcStorm()];
},
});
assert.equal(body(await request()).storms.length, 2);
fail = true;
clock += 6 * 60_000;
const kept = body(await request());
assert.equal(kept.stale, false);
assert.equal(kept.reason, null);
assert.deepEqual(
kept.storms.map((storm) => storm.id),
['ep152026', 'sh042027'],
);
// Past their use, both advisories leave the cached answer.
clock = Date.parse(TIME) + 13 * 3600_000 + 60_000;
const later = body(await request());
assert.deepEqual(
later.storms.map((storm) => storm.id),
[],
);
});
test('a cached answer drops each storm whose own advisory is past use, not all of them', async () => {
let up = true;
let clock = NOW;
const { request } = install({
fetchImpl: async (url, options) => {
if (!up) throw new Error('down');
return fetcher()(url, options);
},
now: () => clock,
readJtwc: async () => [
jtwcStorm({ issuedAt: new Date(NOW - 30 * 60_000).toISOString() }),
],
});
assert.equal(body(await request()).storms.length, 2);
up = false;
// 12 h 10 min after the NHC advisory: NHC's is past use, JTWC's is not.
clock = Date.parse(TIME) + 12 * 3600_000 + 10 * 60_000;
const cached = body(await request());
assert.equal(cached.stale, true);
assert.deepEqual(
cached.storms.map((storm) => storm.id),
['sh042027'],
);
});
test('a JTWC that hangs or answers 500 leaves NHC’s answer unchanged', async (t) => {
const nhcOnly = body(await install({ fetchImpl: fetcher() }).request());
assert.equal(nhcOnly.stale, false);
const jtwcCalls = [];
for (const mode of ['500', 'hang']) {
const { request } = install({
readJtwc: undefined,
jtwcTimeoutMs: 20,
fetchImpl: async (url, options) => {
if (!String(url).includes('metoc.navy.mil'))
return fetcher()(url, options);
jtwcCalls.push(mode);
if (mode === '500') return new Response('down', { status: 500 });
// Hangs until its own deadline aborts it.
return new Promise((_, reject) =>
options.signal.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
),
);
},
});
const answer = body(await request());
assert.deepEqual(answer, nhcOnly, `JTWC ${mode}`);
}
assert.deepEqual(jtwcCalls, ['500', 'hang']);
});
+1 -1
View File
@@ -563,7 +563,7 @@ export const DATA_CREDITS = [
},
{
key: 'weather-cyclones',
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific. Forecast center uncertainty, not storm size.',
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific; <a href="https://www.metoc.navy.mil/jtwc/jtwc.html" target="_blank" rel="noopener">Joint Typhoon Warning Center</a> · western North Pacific, North Indian Ocean, Southern Hemisphere. The NHC cone is forecast center uncertainty, not storm size.',
},
{
key: 'weather-lightning',
+2 -2
View File
@@ -42,8 +42,8 @@ export const MAX_ICON_SLOTS = 176;
export const MIN_ICON_SLOTS = 64;
/**
* Vertex uniform vectors the icon shader keeps for everything else: its own
* and the renderer's (about 34), with room for drivers that keep constants
* in uniforms.
* and the renderer's (about 45, the view sheet's layout among them), with
* room for drivers that keep constants in uniforms.
*/
const OTHER_VERTEX_UNIFORMS = 80;
+6
View File
@@ -100,6 +100,12 @@ export const ICON_RECEDES = 4;
* −31 m before its floor warms) otherwise reads as beyond the limb.
*/
export const ICON_CULL_LIFT = 8;
/**
* The row's image is a subject of the set's view sheet
* ({@link module:viewSheet}): its far image is the subject's first cell, and
* the renderer draws the frame that shows it from the eye.
*/
export const ICON_VIEWS = 16;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/**
+29
View File
@@ -14,6 +14,35 @@ export const AWARENESS_RELATIONSHIP = Object.freeze({
UNKNOWN: 'UNKNOWN',
});
/**
* Whether an aircraft matches a spoken class filter ("helicopter", "tanker"),
* on its class or type fields. No filter matches everything; an aircraft
* with no class or type matches no filter.
* @param {object} item Aircraft summary (`getNearby` row or cohort item).
* @param {string|null} aircraftClass Requested class.
* @returns {boolean}
*/
export function aircraftClassMatches(item, aircraftClass) {
const normalize = (value) =>
String(value || '')
.trim()
.toLowerCase();
const requested = normalize(aircraftClass);
if (!requested) return true;
return [
item?.aircraftClass,
item?.klass,
item?.type,
item?.typeCode,
item?.typeName,
]
.map(normalize)
.filter(Boolean)
.some(
(candidate) => candidate === requested || candidate.includes(requested),
);
}
/**
* Search an expanding area synchronously, doubling the radius after each miss.
* The maximum covers the farthest possible Earth-surface chord while keeping
+20 -5
View File
@@ -15,8 +15,14 @@
* pick names the set and the contact's id, as the fleet icons' do.
* `visible` hides the icon while it stays shown (Cockpit flies the
* aircraft from its own seat).
*
* Given a view-sheet image (`aircraftViews.js`) and a course reader, it is
* drawn along that course instead (`rotationMode: 'course'`), as the fleet
* icons are, so the renderer draws the view of the aircraft that matches
* the eye and tracking a contact does not flatten it.
*/
import { findDraw, findFrame } from '../render/rendererOf.js';
import { isAircraftViewRef } from './aircraftViews.js';
/** Uniquifier for the sets' ids. */
let instances = 0;
@@ -105,18 +111,21 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
function draw() {
if (!shown || !set) return;
const pos = shown.position();
const alongCourse =
typeof shown.course === 'function' && isAircraftViewRef(shown.image);
const item = {
id: shown.id,
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
show: Boolean(pos) && visible,
image: shown.image,
...(shown.imageLod ? { imageLod: shown.imageLod } : {}),
...(shown.imageLod && !alongCourse ? { imageLod: shown.imageLod } : {}),
size: [shown.sprite.width, shown.sprite.height],
scale: shown.sprite.scale,
scaleByDistance: shown.sprite.scaleByDistance,
color: shown.color(),
rotationMode: 'screen',
rotation: pos ? shown.rotation() : 0,
...(alongCourse
? { rotationMode: 'course', course: pos ? shown.course() : 0 }
: { rotationMode: 'screen', rotation: pos ? shown.rotation() : 0 }),
disableDepthTest: Number.POSITIVE_INFINITY,
};
if (
@@ -132,7 +141,9 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
written.size[0] === item.size[0] &&
written.size[1] === item.size[1] &&
written.scale === item.scale &&
written.rotationMode === item.rotationMode &&
written.rotation === item.rotation &&
written.course === item.course &&
sameColor(written.color, item.color)
)
return;
@@ -146,13 +157,17 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
* next one on.
* @param {object} target
* @param {string} target.id The contact's id.
* @param {string} target.image
* @param {string|{views: string, first: number}} target.image A flat
* glyph, or a view-sheet image (drawn along `course`).
* @param {{near: string, switchPx: number}} [target.imageLod] The
* sharper image it switches to once drawn larger than `switchPx`.
* sharper image a flat glyph switches to once drawn larger than
* `switchPx`.
* @param {{width: number, height: number, scale: number,
* scaleByDistance: object}} target.sprite Read each frame.
* @param {() => object|null} target.position ECEF this frame; none hides it.
* @param {() => number} target.rotation Screen radians, counter-clockwise.
* @param {() => number} [target.course] Degrees clockwise from north;
* required with a view-sheet image, which only draws along a course.
* @param {() => object} target.color The tint this frame.
*/
show(target) {
+49
View File
@@ -199,3 +199,52 @@ test('the tracked icon keeps its contact\'s colour; only the alpha changes', ()
assert.ok(Object.isFrozen(stale));
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
});
test('given a view-sheet image and a course, the tracked icon is drawn along its course with no near image', async () => {
const { aircraftViewRef } = await import('./aircraftViews.js');
const { viewer, draw, tick } = harness();
const icon = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'flights',
});
let course = 45;
let rotations = 0;
icon.show({
id: 'abc123',
image: aircraftViewRef('airliner'),
imageLod: { near: 'near', switchPx: 30 },
sprite: SPRITE,
position: () => ({ x: 1, y: 2, z: 3 }),
rotation: () => {
rotations++;
return 0.5;
},
course: () => course,
color: () => [0, 1, 1, 1],
});
const set = draw.find('flights-tracked-icon:');
tick();
const item = set.items.get('abc123');
assert.equal(item.image, aircraftViewRef('airliner'));
assert.equal('imageLod' in item, false);
assert.equal(item.rotationMode, 'course');
assert.equal(item.course, 45);
assert.equal('rotation' in item, false);
assert.equal(rotations, 0, 'no screen rotation is projected');
assert.deepEqual(item.size, [28, 28]);
const writes = set.writes;
tick();
assert.equal(set.writes, writes, 'an unchanged frame writes nothing');
course = 50;
tick();
assert.equal(set.items.get('abc123').course, 50);
// A flat image (a TR-3B conversion, a ground station) turns on screen again.
icon.setImage('data:image/svg+xml;base64,AAA', { near: 'near', switchPx: 30 });
tick();
const flat = set.items.get('abc123');
assert.equal(flat.rotationMode, 'screen');
assert.equal(flat.rotation, 0.5);
assert.deepEqual(flat.imageLod, { near: 'near', switchPx: 30 });
assert.equal('course' in flat, false);
icon.dispose();
});
+53 -2
View File
@@ -59,9 +59,9 @@ const VESSEL_KIND_RULES = [
['fishing', /fishing|trawler/i],
[
'military',
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i,
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search\W+(?:and\W+|&\W*)?rescue/i,
],
['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i],
['tug', /tug|tow|pilot|tender|supply|service|anti\W?pollution/i],
['sailing', /sail/i],
['pleasure', /pleasure|yacht/i],
];
@@ -116,6 +116,57 @@ export function vesselKind(type) {
return kind;
}
/**
* Hull shapes drawn within a kind, where an AIS ship type has a hull of its
* own: a dredger (AIS 33, otherwise `other`), and the small workboats that
* are neither tugs nor patrol craft, drawn as a pilot boat (AIS 50 pilot,
* 51 search and rescue, 53 port tender, 54 anti-pollution). In order: the
* first that matches.
*/
const VESSEL_SHAPE_RULES = [
['dredger', /dredg/i],
[
'pilot',
/pilot|\bsar\b|search\W+(?:and\W+|&\W*)?rescue|port\W?tender|anti\W?pollution/i,
],
];
/** Every hull shape {@link vesselShape} names: the kinds, then the rest. */
export const VESSEL_SHAPES = Object.freeze([
'cargo',
'tanker',
'passenger',
'highspeed',
'fishing',
'tug',
'sailing',
'pleasure',
'military',
'other',
...VESSEL_SHAPE_RULES.map(([shape]) => shape),
]);
const SHAPE_MEMO = new Map();
/**
* The hull a vessel is shown as from the eye's angle (the vessel view
* sheet, `vesselViews.js`): its own where its AIS type has one, else its
* kind's ({@link vesselKind}). Its colour is always its kind's.
* @param {string} type Raw AIS type.
* @returns {string} One of `VESSEL_SHAPES`.
*/
export function vesselShape(type) {
const text = normalizeVesselType(type);
let shape = SHAPE_MEMO.get(text);
if (shape !== undefined) return shape;
shape =
VESSEL_SHAPE_RULES.find(([, pattern]) => pattern.test(text))?.[0] ??
vesselKind(type);
if (SHAPE_MEMO.size >= KIND_MEMO_MAX) SHAPE_MEMO.clear();
SHAPE_MEMO.set(text, shape);
return shape;
}
/**
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
+74
View File
@@ -0,0 +1,74 @@
/**
* @module data/vesselViews
* @description Which block of the vessel view sheet (`viewSheet.js`) a
* vessel's icon draws from. Each hull shape (`vesselShape`, vesselTypes.js)
* is rendered there from a sphere of camera angles, from straight above
* down to the horizon; a renderer with the `viewSheets` capability lays the icon
* flat on the water along its course and draws the view that matches where
* the eye is, so a ship seen at an oblique angle looks solid instead of
* like a flat hull. An aid to navigation keeps its upright buoy.
*/
import { VESSEL_VIEWS } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import { VESSEL_KINDS } from './vesselTypes.js';
/** One frozen image ref per shape and kind, so equal refs are the same. */
const refs = new Map();
/**
* The view image of a vessel: `{views, first, fallback}`, the sheet's id,
* the first cell of its hull shape's block and its kind's flat hull sprite
* (drawn while the sheet loads, or if it fails). A shape the sheet does not
* hold draws its kind's block, and a kind it does not hold `other`'s.
* @param {string} shape One of `VESSEL_SHAPES` (`vesselShape`).
* @param {string} [kind] One of `VESSEL_KINDS` (`vesselKind`); the shape
* itself by default.
* @returns {{views: string, first: number, fallback: string}}
*/
export function vesselViewRef(shape, kind = shape) {
const held = (name) => Number.isInteger(VESSEL_VIEWS.subjects[name]);
const flat = VESSEL_KINDS.includes(kind) ? kind : 'other';
const subject = held(shape) ? shape : held(flat) ? flat : 'other';
const key = `${subject}|${flat}`;
let ref = refs.get(key);
if (!ref) {
ref = Object.freeze({
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[subject],
fallback: vesselSprite(flat),
});
refs.set(key, ref);
}
return ref;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the vessel view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerVesselViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.('viewSheets')) return false;
if (!registered.has(drawPort)) {
const sheet = VESSEL_VIEWS.sheet;
drawPort.views(VESSEL_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { registerVesselViews, vesselViewRef } from './vesselViews.js';
import { VESSEL_VIEWS, viewLayout } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import {
VESSEL_KINDS,
VESSEL_SHAPES,
vesselKind,
vesselShape,
} from './vesselTypes.js';
test('VESSEL_VIEWS holds a block for every hull shape, each on the sheet', () => {
const layout = viewLayout(VESSEL_VIEWS.sheet);
assert.equal(layout.frames, VESSEL_VIEWS.frames);
// To the horizon and no further: a ship is never seen from below.
assert.equal(
(VESSEL_VIEWS.sheet.rings.length - 1) * VESSEL_VIEWS.sheet.ringStepDeg,
90,
);
// Every shape, in order, a block each: the ten kinds, then the rest.
assert.deepEqual(Object.keys(VESSEL_VIEWS.subjects), [...VESSEL_SHAPES]);
assert.deepEqual(
VESSEL_SHAPES.slice(0, VESSEL_KINDS.length).toSorted(),
[...VESSEL_KINDS].sort(),
);
VESSEL_SHAPES.forEach((shape, i) =>
assert.equal(VESSEL_VIEWS.subjects[shape], i * VESSEL_VIEWS.frames, shape),
);
assert.ok(
VESSEL_SHAPES.length * VESSEL_VIEWS.frames <=
VESSEL_VIEWS.sheet.columns * VESSEL_VIEWS.sheet.rows,
);
});
test('every AIS ship type, 0 to 99, draws a shape the sheet holds, in its kind’s colour', () => {
// ITU-R M.1371: the families by their tens, and the types with a hull of
// their own.
const shapeOf = (code) => vesselShape(String(code));
const kindOf = (code) => vesselKind(String(code));
for (let code = 0; code < 100; code++) {
assert.ok(Number.isInteger(VESSEL_VIEWS.subjects[shapeOf(code)]), code);
assert.ok(VESSEL_KINDS.includes(kindOf(code)), code);
}
const drawn = (codes, shape, kind = shape) =>
codes.forEach((code) =>
assert.deepEqual([shapeOf(code), kindOf(code)], [shape, kind], code),
);
const tens = (ten) => Array.from({ length: 10 }, (_, i) => ten * 10 + i);
drawn(tens(7), 'cargo');
drawn(tens(8), 'tanker');
drawn(tens(6), 'passenger');
drawn(tens(4), 'highspeed');
drawn([30], 'fishing');
drawn([31, 32, 52], 'tug');
drawn([36], 'sailing');
drawn([37], 'pleasure');
drawn([35, 55], 'military');
drawn([33], 'dredger', 'other');
// Pilot, port tender and anti-pollution craft are service boats (the
// tug's colour); search and rescue is a patrol colour. One small hull.
drawn([50, 53, 54], 'pilot', 'tug');
drawn([51], 'pilot', 'military');
// Wing-in-ground craft, diving and medical vessels, the reserved and
// spare codes and "other": the plain hull.
drawn(
[0, 1, 19, ...tens(2), 34, 38, 39, 56, 57, 58, 59, ...tens(9)],
'other',
);
// A feed that names the type in words draws the same shapes.
assert.equal(vesselShape('Dredger'), 'dredger');
assert.equal(vesselShape('Pilot Vessel'), 'pilot');
assert.equal(vesselShape('Search and Rescue'), 'pilot');
// However the words are joined, the hull and the colour are the code's.
for (const text of ['Search & Rescue', 'Search-and-rescue', 'SAR'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'military'],
text,
);
for (const text of ['Anti Pollution', 'Anti-pollution', 'Port Tender'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'tug'],
text,
);
assert.equal(vesselShape('Tug'), 'tug');
assert.equal(vesselShape('Container Ship'), 'cargo');
assert.equal(vesselShape(''), 'other');
});
test('a vessel draws its shape’s block of the sheet, with its kind’s flat hull to fall back on', () => {
for (const kind of VESSEL_KINDS) {
const ref = vesselViewRef(kind);
assert.deepEqual(ref, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[kind],
fallback: vesselSprite(kind),
});
assert.ok(Object.isFrozen(ref));
// One object a shape and kind: an unchanged icon is seen as unchanged.
assert.equal(vesselViewRef(kind), ref);
}
// A shape within a kind: its own block, its kind's flat hull.
assert.deepEqual(vesselViewRef('pilot', 'tug'), {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
assert.notEqual(
vesselViewRef('pilot', 'tug'),
vesselViewRef('pilot', 'military'),
);
assert.equal(
vesselViewRef('dredger', 'other').first,
VESSEL_VIEWS.subjects.dredger,
);
// A shape the sheet does not hold: its kind's block, then `other`'s.
assert.equal(
vesselViewRef('hovercraft', 'highspeed'),
vesselViewRef('highspeed'),
);
assert.equal(vesselViewRef('submarine'), vesselViewRef('other'));
assert.equal(vesselViewRef(undefined), vesselViewRef('other'));
});
test('the sheet is registered once a port, at the layer’s asset URL, on a renderer that draws views', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const views = new Set(['viewSheets']);
const resolve = (url) => `/gev${url}`;
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(calls.length, 1);
assert.equal(calls[0][0], VESSEL_VIEWS.id);
assert.deepEqual(calls[0][1], {
...VESSEL_VIEWS.sheet,
image: '/gev/sprites/vessel-views.webp',
});
// No capability, no port, or a port without `views`: flat hulls.
assert.equal(registerVesselViews(port, new Set(), resolve), false);
assert.equal(registerVesselViews(port, null), false);
assert.equal(registerVesselViews(null, views), false);
assert.equal(registerVesselViews({}, views), false);
});
+295
View File
@@ -0,0 +1,295 @@
/**
* @module viewSheet
* @description A view sheet: one image of small sprites showing a subject
* (an aircraft class) from a sphere of directions, and the maths that picks
* the sprite for where the eye is. Plain JavaScript and GLSL: no DOM, no
* engine. `scripts/bake-view-sheet.py` bakes the aircraft and
* vessel sheets to their layouts here; a renderer with the `viewSheets`
* capability draws them.
*
* **Frames.** A subject lies flat on the earth: up is the ground's normal,
* forward its course. `d` is the direction from the subject to the eye in
* the subject's own axes `[forward, right, up]`. A sheet holds each subject
* as a block of consecutive cells, row-major: rings of frames `ringStepDeg`
* apart, from straight above (ring 0) downward, ring `k` holding `rings[k]`
* frames from the eye dead ahead, round the right side, to dead astern. The
* left side is the right-side frame mirrored, so a sheet's subjects and
* their light are symmetric about their centre plane.
*
* **Roll.** A frame's image up is {@link frameUp}: forward, turned by the
* smallest rotation that takes up onto the frame's direction. Straight
* above, the nose points up the image; the roll then changes smoothly all
* the way round and below. It has no meaning only from straight below, so a
* sheet's last ring stays short of that.
*
* **Between frames.** The frame nearest the eye's direction is drawn
* ({@link viewFrame}), as a card standing where its subject is, square to
* the frame's own direction: seen from a little to one side it is tilted
* (foreshortened and turned) as the subject itself would be, until the next
* frame is the nearer. Frames are not blended.
*/
/** Rings a sheet may hold (the shader's uniform array); even. */
export const VIEW_RINGS_MAX = 18;
/** The aircraft classes' view sheet (`public/sprites/aircraft-views.json`). */
export const AIRCRAFT_VIEWS = Object.freeze({
id: 'aircraft-views',
sheet: Object.freeze({
image: '/sprites/aircraft-views.webp',
cellPx: 64,
columns: 64,
rows: 57,
ringStepDeg: 7.5,
rings: Object.freeze([
1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22,
]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 302,
/** Each subject's first cell. */
subjects: Object.freeze({
airliner: 0,
widebody: 302,
quadjet: 604,
turboprop: 906,
light: 1208,
glider: 1510,
fastjet: 1812,
bizjet: 2114,
uav: 2416,
helicopter0: 2718,
helicopter1: 3020,
helicopter2: 3322,
}),
});
/**
* The vessel hull shapes' view sheet (`public/sprites/vessel-views.json`):
* from straight above down to the horizon, a ship never being seen from
* below.
*/
export const VESSEL_VIEWS = Object.freeze({
id: 'vessel-views',
sheet: Object.freeze({
image: '/sprites/vessel-views.webp',
cellPx: 64,
columns: 64,
rows: 39,
ringStepDeg: 7.5,
rings: Object.freeze([1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 208,
/**
* Each hull shape's first cell (`vesselShape`, vesselTypes.js): the ten
* hull kinds, then the shapes drawn within a kind.
*/
subjects: Object.freeze({
cargo: 0,
tanker: 208,
passenger: 416,
highspeed: 624,
fishing: 832,
tug: 1040,
sailing: 1248,
pleasure: 1456,
military: 1664,
other: 1872,
dredger: 2080,
pilot: 2288,
}),
});
/**
* Check a sheet's layout, and return it with each ring's first frame.
* @param {{image: string, cellPx: number, columns: number, rows: number,
* ringStepDeg: number, rings: readonly number[], grey?: boolean}} sheet
* @returns {{columns: number, rows: number, ringStepRad: number,
* rings: number[], firsts: number[], frames: number}}
*/
export function viewLayout(sheet) {
const whole = (n) => Number.isInteger(n) && n > 0;
if (!sheet || typeof sheet.image !== 'string' || !sheet.image)
throw new TypeError('a view sheet needs its image URL');
if (!whole(sheet.cellPx) || !whole(sheet.columns) || !whole(sheet.rows))
throw new TypeError(
'a view sheet needs whole cellPx, columns and rows above 0',
);
const { rings, ringStepDeg } = sheet;
if (
!Array.isArray(rings) ||
rings.length < 1 ||
rings.length > VIEW_RINGS_MAX ||
!rings.every(whole)
)
throw new TypeError(
`a view sheet needs 1 to ${VIEW_RINGS_MAX} rings of whole frame counts`,
);
if (rings[0] !== 1)
throw new TypeError("a view sheet's first ring is the one frame above");
if (
!(ringStepDeg > 0) ||
!Number.isFinite(ringStepDeg) ||
(rings.length - 1) * ringStepDeg >= 180
)
throw new TypeError("a view sheet's rings stop short of straight below");
const firsts = [];
let frames = 0;
for (const count of rings) {
firsts.push(frames);
frames += count;
}
return {
columns: sheet.columns,
rows: sheet.rows,
ringStepRad: (ringStepDeg * Math.PI) / 180,
rings: [...rings],
firsts,
frames,
};
}
/**
* The frame that shows a subject from `d`.
* @param {ReturnType<typeof viewLayout>} layout
* @param {readonly [number, number, number]} d Toward the eye, as
* `[forward, right, up]`; any length above 0.
* @returns {{frame: number, ring: number, index: number, mirrored: boolean}}
* `frame` counts from the subject's first cell; `mirrored` draws it flipped
* left to right (the eye on the left side).
*/
export function viewFrame(layout, d) {
const length = Math.hypot(d[0], d[1], d[2]);
const up = length > 0 ? Math.min(1, Math.max(-1, d[2] / length)) : 1;
const ring = Math.min(
layout.rings.length - 1,
Math.floor(Math.acos(up) / layout.ringStepRad + 0.5),
);
const span = layout.rings[ring] - 1;
const side = Math.abs(d[1]);
const bearing = side + Math.abs(d[0]) > 0 ? Math.atan2(side, d[0]) : 0;
const index = span > 0 ? Math.floor((bearing / Math.PI) * span + 0.5) : 0;
return {
frame: layout.firsts[ring] + index,
ring,
index,
mirrored: d[1] < 0,
};
}
/**
* The direction a frame shows its subject from: a unit `[forward, right,
* up]`, on the right side (or the left, mirrored).
*/
export function frameDirection(layout, ring, index, mirrored = false) {
const off = ring * layout.ringStepRad;
const span = layout.rings[ring] - 1;
const turn = span > 0 ? (index / span) * Math.PI : 0;
return [
Math.sin(off) * Math.cos(turn),
Math.sin(off) * Math.sin(turn) * (mirrored ? -1 : 1),
Math.cos(off),
];
}
/**
* A frame's image up, for the unit direction `d` it shows its subject from:
* forward, turned as up turns onto `d`. A unit `[forward, right, up]`,
* perpendicular to `d`.
*/
export function frameUp(d) {
const k = 1 / Math.max(1 + d[2], 1e-6);
return [1 - d[0] * d[0] * k, -d[0] * d[1] * k, -d[0]];
}
/**
* A sheet's layout as the shader's uniforms: `grid`, and `rings` as one
* vector for each two rings (`[frames, first, frames, first]`).
*/
export function viewUniforms(layout) {
const rings = [];
for (let k = 0; k < VIEW_RINGS_MAX; k += 2)
rings.push([
layout.rings[k] ?? 1,
layout.firsts[k] ?? 0,
layout.rings[k + 1] ?? 1,
layout.firsts[k + 1] ?? 0,
]);
return {
grid: [
layout.columns,
layout.rows,
layout.ringStepRad,
layout.rings.length,
],
rings,
};
}
/**
* {@link viewFrame}, {@link frameDirection} and {@link frameUp} in GLSL, over `u_viewGrid` (columns, rows, ring step in radians, rings) and
* `u_viewRings` (each ring's frames and first frame, two rings a vector).
*/
export const VIEW_SHEET_GLSL = /* glsl */ `
uniform vec4 u_viewGrid;
uniform vec4 u_viewRings[${VIEW_RINGS_MAX / 2}];
// A ring's frames and its first frame, from the subject's first cell.
vec2 viewRing(float ring) {
vec4 pair = u_viewRings[int(ring * 0.5)];
return ring - 2.0 * floor(ring * 0.5) < 0.5 ? pair.xy : pair.zw;
}
// The frame that shows a subject from d (unit, toward the eye, as forward,
// right, up): its ring, its index in the ring, and 1 when it is drawn
// mirrored (the eye on the left side).
vec3 viewNearest(vec3 d) {
float ring = clamp(
floor(acos(clamp(d.z, -1.0, 1.0)) / u_viewGrid.z + 0.5),
0.0, u_viewGrid.w - 1.0);
float span = viewRing(ring).x - 1.0;
float side = abs(d.y);
float bearing = side + abs(d.x) > 0.0 ? atan(side, d.x) : 0.0;
return vec3(
ring,
span > 0.0 ? floor(bearing / 3.141592653589793 * span + 0.5) : 0.0,
d.y < 0.0 ? 1.0 : 0.0);
}
// The direction a frame shows its subject from (toward the eye, as forward,
// right, up; flip 1 for the left side) and the frame's image up.
void viewFrameAxes(float ring, float index, float flip, out vec3 toEye, out vec3 up) {
float span = viewRing(ring).x - 1.0;
float off = ring * u_viewGrid.z;
float turn = span > 0.0 ? index / span * 3.141592653589793 : 0.0;
toEye = vec3(
sin(off) * cos(turn),
sin(off) * sin(turn) * (1.0 - 2.0 * flip),
cos(off));
float k = 1.0 / max(1.0 + toEye.z, 1.0e-6);
up = vec3(1.0 - toEye.x * toEye.x * k, -toEye.x * toEye.y * k, -toEye.x);
}
`;
/**
* Reading a view sheet's cells in a fragment shader: `viewCell(cell, uv,
* lod)` is the colour of a cell at `uv` (0..1 across it, v down) and that
* level of detail, nothing outside it, from `u_views` over `u_viewGrid`.
*/
export const VIEW_SHEET_FRAGMENT_GLSL = /* glsl */ `
uniform sampler2D u_views;
uniform vec4 u_viewGrid;
vec4 viewCell(float cell, vec2 uv, float lod) {
float at = floor(cell + 0.5);
float row = floor((at + 0.5) / u_viewGrid.x);
float column = at - row * u_viewGrid.x;
vec2 inside = step(vec2(0.0), uv) * step(uv, vec2(1.0));
vec4 color = textureLod(
u_views, (vec2(column, row) + clamp(uv, 0.0, 1.0)) / u_viewGrid.xy, lod);
return color * (inside.x * inside.y);
}
`;
+429
View File
@@ -0,0 +1,429 @@
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import {
AIRCRAFT_VIEWS,
VESSEL_VIEWS,
frameDirection,
frameUp,
viewFrame,
viewLayout,
viewUniforms,
VIEW_RINGS_MAX,
} from './viewSheet.js';
const layout = viewLayout(AIRCRAFT_VIEWS.sheet);
const RAD = Math.PI / 180;
const HORIZON = 12; // the ring at 90° from straight above
/** The pinned layout: rings 7.5° apart, 302 frames a subject. */
const RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22];
const FIRSTS = [
0, 1, 5, 12, 22, 35, 51, 69, 89, 111, 134, 158, 183, 208, 233, 257, 280,
];
/** A unit `[forward, right, up]` `offDeg` from straight above, at `bearingDeg`
* from dead ahead toward the right side. */
function direction(offDeg, bearingDeg) {
const off = offDeg * RAD;
const bearing = bearingDeg * RAD;
return [
Math.sin(off) * Math.cos(bearing),
Math.sin(off) * Math.sin(bearing),
Math.cos(off),
];
}
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const mirror = (v) => [v[0], -v[1], v[2]];
const near = (a, b, eps = 1e-9) =>
a.every((value, i) => Math.abs(value - b[i]) < eps);
/** The smallest rotation taking up onto `d`, applied to forward (Rodrigues). */
function rotatedForward(d) {
const up = [0, 0, 1];
const forward = [1, 0, 0];
const axis = cross(up, d);
const sin = Math.hypot(...axis);
const cos = dot(up, d);
if (sin < 1e-12) return forward;
const k = axis.map((value) => value / sin);
const kxv = cross(k, forward);
const kv = dot(k, forward);
return forward.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
}
test('viewLayout gives the aircraft sheet each ring’s first frame', () => {
assert.deepEqual(layout.rings, RINGS);
assert.deepEqual(layout.firsts, FIRSTS);
assert.equal(layout.frames, 302);
assert.equal(layout.columns, 64);
assert.equal(layout.rows, 57);
assert.equal(layout.ringStepRad, 7.5 * RAD);
assert.notEqual(layout.rings, AIRCRAFT_VIEWS.sheet.rings, 'a copy');
});
test('viewLayout refuses a sheet it cannot draw', () => {
const sheet = AIRCRAFT_VIEWS.sheet;
const bad = [
null,
{ ...sheet, image: '' },
{ ...sheet, image: undefined },
{ ...sheet, cellPx: 63.5 },
{ ...sheet, columns: 0 },
{ ...sheet, rows: -32 },
{ ...sheet, rings: [] },
{ ...sheet, rings: 'many' },
{ ...sheet, rings: Array(VIEW_RINGS_MAX + 1).fill(1) },
{ ...sheet, rings: [3, 5] },
{ ...sheet, rings: [1, 2.5] },
{ ...sheet, rings: [1, 0] },
{ ...sheet, ringStepDeg: 0 },
{ ...sheet, ringStepDeg: -15 },
{ ...sheet, ringStepDeg: Number.NaN },
{ ...sheet, ringStepDeg: Infinity },
// A ring straight below, or past it.
{ ...sheet, rings: [1, 4, 4, 1], ringStepDeg: 60 },
{ ...sheet, rings: Array(13).fill(1), ringStepDeg: 15 },
];
for (const sheetGiven of bad)
assert.throws(
() => viewLayout(sheetGiven),
TypeError,
JSON.stringify(sheetGiven),
);
// Short of straight below, and the most rings there may be, are drawn.
assert.equal(viewLayout({ ...sheet, rings: Array(12).fill(1) }).frames, 12);
assert.equal(
viewLayout({
...sheet,
rings: Array(VIEW_RINGS_MAX).fill(1),
ringStepDeg: 10,
}).rings.length,
VIEW_RINGS_MAX,
);
});
test('straight above is frame 0, whatever the course', () => {
assert.deepEqual(viewFrame(layout, [0, 0, 1]), {
frame: 0,
ring: 0,
index: 0,
mirrored: false,
});
assert.equal(viewFrame(layout, [0, 0, 42]).frame, 0, 'any length');
assert.equal(viewFrame(layout, direction(3.7, 135)).frame, 0);
assert.equal(viewFrame(layout, [0, 0, 0]).frame, 0, 'no direction: above');
});
test('on the horizon, dead ahead, abeam and astern are the first, middle and last frames of ring 12', () => {
const first = layout.firsts[HORIZON];
const ahead = viewFrame(layout, [1, 0, 0]);
assert.deepEqual(ahead, {
frame: first,
ring: 12,
index: 0,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [0, 1, 0]), {
frame: first + 12,
ring: 12,
index: 12,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [-1, 0, 0]), {
frame: first + 24,
ring: 12,
index: 24,
mirrored: false,
});
});
test('the left side draws the right side’s frame mirrored', () => {
for (const [off, bearing] of [
[30, 40],
[90, 90],
[105, 170],
[60, 1],
]) {
const right = viewFrame(layout, direction(off, bearing));
const left = viewFrame(layout, mirror(direction(off, bearing)));
assert.equal(left.frame, right.frame, `${off}/${bearing}`);
assert.equal(right.mirrored, false);
assert.equal(left.mirrored, true);
}
// Exactly on the centre plane it is not mirrored.
assert.equal(viewFrame(layout, [1, 0, 0]).mirrored, false);
assert.equal(viewFrame(layout, [1, -0, 0]).mirrored, false);
});
test('below the last ring the eye takes the last ring', () => {
const last = layout.rings.length - 1;
for (const off of [120, 126, 135, 170, 180]) {
const view = viewFrame(layout, direction(off, 90));
assert.equal(view.ring, last, `${off}°`);
}
assert.equal(viewFrame(layout, [0, 0, -1]).frame, layout.firsts[last]);
});
test('frames round to the nearest, between rings and between bearings', () => {
// Rings are 7.5° apart: 3.75° from straight above is between ring 0 and 1.
assert.equal(viewFrame(layout, direction(3.7, 0)).ring, 0);
assert.equal(viewFrame(layout, direction(3.8, 0)).ring, 1);
assert.equal(viewFrame(layout, direction(86.2, 0)).ring, 11);
assert.equal(viewFrame(layout, direction(86.3, 0)).ring, 12);
// The horizon ring's 25 frames are 7.5° of bearing apart.
assert.equal(viewFrame(layout, direction(90, 3.7)).index, 0);
assert.equal(viewFrame(layout, direction(90, 3.8)).index, 1);
assert.equal(viewFrame(layout, direction(90, 176.2)).index, 23);
assert.equal(viewFrame(layout, direction(90, 176.3)).index, 24);
// Ring 1's 4 frames are 60° apart.
assert.equal(viewFrame(layout, direction(7.5, 29.9)).index, 0);
assert.equal(viewFrame(layout, direction(7.5, 30.1)).index, 1);
});
test('frameDirection is where viewFrame finds each frame of the sheet', () => {
let frames = 0;
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-12, 'unit');
const view = viewFrame(layout, d);
assert.equal(view.ring, ring, `${ring}/${index}`);
assert.equal(view.index, index, `${ring}/${index}`);
assert.equal(view.frame, layout.firsts[ring] + index);
// A frame on the centre plane is its own mirror image: either way
// draws it.
if (Math.abs(d[1]) > 1e-12) assert.equal(view.mirrored, mirrored);
}
frames++;
}
assert.equal(frames, AIRCRAFT_VIEWS.frames);
});
test('frameUp is a unit vector across the view, forward from straight above, and turns as the smallest rotation does', () => {
assert.ok(near(frameUp([0, 0, 1]), [1, 0, 0]), 'nose up the image');
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++)
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
const up = frameUp(d);
const at = `${ring}/${index}${mirrored ? ' mirrored' : ''}`;
assert.ok(Math.abs(Math.hypot(...up) - 1) < 1e-9, `unit at ${at}`);
assert.ok(Math.abs(dot(up, d)) < 1e-9, `across the view at ${at}`);
assert.ok(
near(up, rotatedForward(d)),
`the smallest rotation at ${at}`,
);
// Mirroring the eye mirrors the image's up.
assert.ok(near(frameUp(mirror(d)), mirror(up)), `mirrored at ${at}`);
}
// On the horizon, abeam: the nose still points up the image.
assert.ok(near(frameUp([0, 1, 0]), [1, 0, 0]));
// Dead ahead on the horizon: the image's up is straight down the aircraft.
assert.ok(near(frameUp([1, 0, 0]), [0, 0, -1]));
});
test('viewUniforms packs the layout as the shader reads it', () => {
const { grid, rings } = viewUniforms(layout);
assert.deepEqual(grid, [64, 57, 7.5 * RAD, 17]);
// Two rings a vector: each ring's frames and its first frame.
assert.equal(rings.length, VIEW_RINGS_MAX / 2);
const pairs = [];
for (let k = 0; k < RINGS.length; k += 2)
pairs.push([RINGS[k], FIRSTS[k], RINGS[k + 1] ?? 1, FIRSTS[k + 1] ?? 0]);
assert.deepEqual(rings.slice(0, pairs.length), pairs);
for (const pair of rings.slice(pairs.length))
assert.deepEqual(pair, [1, 0, 1, 0], 'padding');
});
test('AIRCRAFT_VIEWS is consistent: a block a subject, every block on the sheet', () => {
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(
frames,
sheet.rings.reduce((a, b) => a + b, 0),
);
assert.equal(frames, 302);
assert.equal(sheet.cellPx * sheet.columns, 4096);
assert.equal(sheet.cellPx * sheet.rows, 3648);
assert.equal(sheet.grey, true, 'kept as grey and alpha');
const firsts = Object.values(subjects);
firsts.forEach((first, i) => {
assert.equal(first, i * frames, 'in order, one block after another');
assert.equal(first % frames, 0);
assert.ok(first + frames <= sheet.columns * sheet.rows, 'on the sheet');
});
assert.ok(Object.isFrozen(AIRCRAFT_VIEWS));
assert.ok(Object.isFrozen(sheet));
assert.ok(Object.isFrozen(sheet.rings));
assert.ok(Object.isFrozen(subjects));
});
const BAKE = new URL('../../scripts/bake-view-sheet.py', import.meta.url);
/** The sheets the bake script bakes: its config name, the layout it must
* match, the files it ships and the size the layout pins. */
const SHEETS = [
{
config: 'AIRCRAFT',
views: AIRCRAFT_VIEWS,
name: 'aircraft-views',
frames: 302,
size: [4096, 3648],
},
{
config: 'VESSELS',
views: VESSEL_VIEWS,
name: 'vessel-views',
frames: 208,
size: [4096, 2496],
},
];
/** A sheet's entry in the bake script: `NAME = { ... }`. */
function bakeConfig(script, config) {
const block = new RegExp(`^${config} = \\{([\\s\\S]*?)^\\}`, 'm').exec(
script,
);
assert.ok(block, `${config} in the bake script`);
const field = (key) => {
const match = new RegExp(`^\\s*"${key}": (.+),$`, 'm').exec(block[1]);
assert.ok(match, `${config}.${key} in the bake script`);
return JSON.parse(match[1]);
};
const names = [...block[1].matchAll(/^\s*\("(\w+)", "([\w/.]+)"/gm)];
return {
field,
names: names.map((m) => m[1]),
models: names.map((m) => m[2]),
};
}
for (const { config, views, name, frames, size } of SHEETS) {
test(`${views.id} is pinned: ${frames} frames a subject, ${size.join(' × ')} px`, () => {
const { sheet } = views;
assert.equal(views.frames, frames);
assert.equal(viewLayout(sheet).frames, frames);
assert.equal(sheet.cellPx * sheet.columns, size[0]);
assert.equal(sheet.cellPx * sheet.rows, size[1]);
assert.equal(sheet.image, `/sprites/${name}.webp`);
assert.equal(sheet.grey, true);
});
test(`the bake script lays ${views.id} out as the layout says`, () => {
const { field, names } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(field('name'), name);
assert.equal(field('ring_step_deg'), sheet.ringStepDeg);
assert.deepEqual(field('rings'), [...sheet.rings]);
assert.equal(field('columns'), sheet.columns);
assert.deepEqual(
names,
Object.keys(subjects),
'the same subjects in order',
);
// The script's rows: as many as its subjects' blocks take.
assert.equal(
Math.ceil((names.length * frames) / sheet.columns),
sheet.rows,
);
});
const manifestUrl = new URL(
`../../public/sprites/${name}.json`,
import.meta.url,
);
test(`the baked manifest matches ${views.id}`, () => {
// Shipped with the app: a missing manifest fails, it does not skip.
assert.ok(existsSync(manifestUrl), `public/sprites/${name}.json`);
const manifest = JSON.parse(readFileSync(manifestUrl, 'utf8'));
const { models } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(manifest.cellPx, sheet.cellPx);
assert.equal(manifest.columns, sheet.columns);
assert.equal(manifest.rows, sheet.rows);
assert.equal(manifest.ringStepDeg, sheet.ringStepDeg);
assert.deepEqual(manifest.rings, [...sheet.rings]);
assert.equal(manifest.grey, true);
assert.equal(manifest.image, `${name}.webp`);
assert.deepEqual(Object.keys(manifest.subjects), Object.keys(subjects));
Object.entries(subjects).forEach(([subject, first], i) => {
assert.equal(manifest.subjects[subject].first, first, subject);
assert.equal(manifest.subjects[subject].model, models[i], subject);
assert.ok(manifest.subjects[subject].radiusM > 0, `${subject} baked`);
});
});
const sheetUrl = new URL(
`../../public/sprites/${name}.webp`,
import.meta.url,
);
test(`the shipped ${name}.webp is the size the layout says, grey, and clear at every cell’s edge`, async () => {
assert.ok(existsSync(sheetUrl), `public/sprites/${name}.webp`);
const { default: sharp } = await import('sharp');
const { sheet, subjects } = views;
const { data, info } = await sharp(fileURLToPath(sheetUrl))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
assert.equal(info.width, sheet.columns * sheet.cellPx);
assert.equal(info.height, sheet.rows * sheet.cellPx);
const at = (x, y) => (y * info.width + x) * 4;
// Grey: the renderer reads the red channel as the grey.
for (let i = 0; i < data.length; i += 4)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2])
assert.fail(`not grey at pixel ${i / 4}`);
// Each used cell keeps its outer 2 px transparent (the mipmaps), and
// has something in it.
const used = Object.keys(subjects).length * frames;
const c = sheet.cellPx;
for (let n = 0; n < used; n++) {
const left = (n % sheet.columns) * c;
const top = Math.floor(n / sheet.columns) * c;
let drawn = 0;
for (let y = 0; y < c; y++)
for (let x = 0; x < c; x++) {
const alpha = data[at(left + x, top + y) + 3];
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) drawn += alpha;
else if (alpha !== 0)
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
}
assert.ok(drawn > 0, `cell ${n} is empty`);
}
});
}
test('in the bake’s axes (nose −X, starboard +Y, up +Z) a frame has the same up and direction', () => {
// The bake turns forward by Blender's rotation_difference(UP, d), in its
// own axes, which are mirrored from [forward, right, up]: the smallest
// rotation is the same rotation in either.
const toBake = (v) => [-v[0], v[1], v[2]];
const minimal = (from, to, v) => {
const axis = cross(from, to);
const sin = Math.hypot(...axis);
const cos = dot(from, to);
if (sin < 1e-12) return v;
const k = axis.map((value) => value / sin);
const kxv = cross(k, v);
const kv = dot(k, v);
return v.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
};
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
const d = frameDirection(layout, ring, index);
const bakeUp = minimal([0, 0, 1], toBake(d), toBake([1, 0, 0]));
assert.ok(near(toBake(frameUp(d)), bakeUp), `${ring}/${index}`);
}
});
/** A blend's weight by frame (a frame listed twice counts once, summed). */
+2 -3
View File
@@ -1110,11 +1110,10 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
// Pistes extend the generated layer enums and alias hint; voice geometry
// adds the analyst area scopes and the osm-places layer.
// control_cockpit states the own-layer entry rule (Contacts not required).
// Fire Perimeters queries add lastGrowthTime.
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
assert.equal(
crypto.createHash('sha256').update(block).digest('hex'),
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
);
const instructions = fs.readFileSync(
+18 -13
View File
@@ -1521,7 +1521,6 @@
"FOV {value}° (DATASHEET)": "FOV {value}° (ورقة البيانات)",
"SPEC FOV {span}° (CAPABILITY)": "FOV حسب المواصفات {span}° (القدرة)",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · المواصفات: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "الأطلسي وشرق/وسط شمال المحيط الهادئ؛ ليست تغطية عالمية للأعاصير.",
"Cyclone advisories unavailable": "نشرات الأعاصير غير متاحة",
"Cyclone data unavailable": "بيانات الأعاصير غير متاحة",
"Potential tropical cyclone": "إعصار مداري محتمل",
@@ -1549,17 +1548,12 @@
"Maximum sustained wind: {wind}": "أقصى سرعة للرياح المستمرة: {wind}",
"Pressure: {pressure}": "الضغط: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · النشرة رقم {number} · صدرت {time}",
"No active NHC/CPHC systems": "لا توجد أنظمة مدارية نشطة لدى NHC/CPHC",
"Advisories unavailable": "النشرات غير متاحة",
"Cyclones · NHC / CPHC": "الأعاصير · NHC / CPHC",
"Atlantic · E/C Pacific": "الأطلسي · شرق/وسط الهادئ",
"{storms} · {name} selected": "{storms} · المحدد: {name}",
"Official advisory ↗": "النشرة الرسمية ↗",
"Active NHC and CPHC cyclone advisories": "نشرات الأعاصير النشطة من NHC وCPHC",
"Wind unavailable": "الرياح غير متاحة",
"Advisory center / forecast track": "المركز حسب النشرة / المسار المتوقع",
"Center-track uncertainty cone": "مخروط عدم اليقين لمسار المركز",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "حدّد عاصفة على الخريطة، أو اخترها من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مساحة فارغة من الخريطة لإلغاء التحديد. سياق نشرات NOAA NHC/CPHC. يصف المخروط عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا كامل منطقة الخطر. تشير تسميات نقاط التوقع إلى مدة التوقع بالساعات كما يوردها المصدر، لا إلى أوقات محسوبة من وقت صدور النشرة. تتبع الأشكال الهندسية السطح؛ والارتفاع لا يمثل ارتفاع الظواهر الجوية. راجع النشرة الرسمية.",
"DRIVE": "قيادة",
"Drive": "بالسيارة",
"WALK": "مشي",
@@ -1851,6 +1845,11 @@
"Unnamed incident": "حادث بلا اسم",
"Open {title} on InciWeb": "فتح {title} على InciWeb",
"Perimeter source unavailable": "مصدر محيطات الحرائق غير متاح",
"Not contained or unknown": "بلا احتواء أو غير معروف",
"Under 50% contained": "الاحتواء: أقل من 50%",
"50–99% contained": "الاحتواء: 50–99%",
"Fully contained": "احتواء كامل",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "يبيّن اللون نسبة الاحتواء المُبلَّغ عنها. المحيطات مبسّطة إلى نحو 100 م.",
"Malformed perimeter snapshot": "لقطة المحيطات مشوّهة",
"radio tag|All": "الكل",
"Directory refresh degraded; showing the previous station catalog.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
@@ -4845,11 +4844,17 @@
"Connecting to telemetry…": "جارٍ الاتصال بالقياسات…",
"{seconds} s": "{seconds} ث",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط.",
"last growth {age} ago": "آخر توسّع قبل {age}",
"New in 6 hours": "جديد خلال آخر 6 ساعات",
"6–24 hours": "6–24 ساعة",
"1–3 days": "1–3 أيام",
"Older or unknown": "أقدم أو غير معروف",
"Colour shows how long ago each area was mapped.": "يبيّن اللون منذ متى رُسمت كل منطقة.",
"Perimeters are simplified to about 100 m.": "المحيطات مبسّطة إلى نحو 100 م."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: المحيط الأطلسي وشرق ووسط شمال المحيط الهادئ. JTWC: غرب شمال المحيط الهادئ وشمال المحيط الهندي ونصف الكرة الجنوبي.",
"34-knot wind danger area": "منطقة خطر رياح 34 عقدة",
"Track and 34-knot wind danger area match this warning": "المسار ومنطقة خطر رياح 34 عقدة مطابقان لهذا التحذير",
"Track/danger area awaiting warning {number}": "المسار/منطقة الخطر بانتظار التحذير رقم {number}",
"Track/danger area unavailable": "المسار/منطقة الخطر غير متاحين",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "تحذير JTWC: التحذير الرسمي هو تحذير المركز الإقليمي. رياح JTWC متوسطات دقيقة واحدة.",
"No active tropical cyclone warnings": "لا توجد تحذيرات نشطة من الأعاصير المدارية",
"Cyclones · NHC / CPHC · JTWC": "الأعاصير · NHC / CPHC · JTWC",
"All tropical basins": "كل الأحواض المدارية",
"JTWC warning ↗": "تحذير JTWC ↗",
"Active cyclone advisories and warnings": "نشرات وتحذيرات الأعاصير النشطة",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "اختر عاصفة على الخريطة، أو اختر عاصفة من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مكان فارغ من الخريطة لإلغاء التحديد. نشرات NOAA NHC/CPHC وتحذيرات JTWC. يصف مخروط NHC عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا منطقة الخطر كاملة. منطقة خطر رياح 34 عقدة لدى JTWC هي حيث قد تصل رياح بسرعة 34 عقدة، موسّعةً بخطأ توقع المسار؛ وهي ليست مخروطًا. تسميات نقاط التوقع هي ساعات المهلة لدى المصدر، لا أوقات محسوبة من وقت الإصدار. تتبع الأشكال سطح الأرض؛ والارتفاع ليس ارتفاعًا جويًا. ارجع إلى النشرة الرسمية أو إلى مركز الإنذار الإقليمي.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · التحذير {number} · صدر {time}"
}
+18 -13
View File
@@ -1436,7 +1436,6 @@
"FOV {value}° (DATASHEET)": "FOV {value}° (DATENBLATT)",
"SPEC FOV {span}° (CAPABILITY)": "SPEZ. FOV {span}° (BEREICH)",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPEZ.: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantik und östlicher/zentraler Nordpazifik; keine weltweite Abdeckung von Wirbelstürmen.",
"Cyclone advisories unavailable": "Wirbelsturm-Lageberichte nicht verfügbar",
"Cyclone data unavailable": "Wirbelsturmdaten nicht verfügbar",
"Potential tropical cyclone": "Potenzieller tropischer Wirbelsturm",
@@ -1460,17 +1459,12 @@
"Maximum sustained wind: {wind}": "Maximaler Dauerwind: {wind}",
"Pressure: {pressure}": "Luftdruck: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Lagebericht {number} · ausgegeben {time}",
"No active NHC/CPHC systems": "Keine aktiven NHC/CPHC-Systeme",
"Advisories unavailable": "Lageberichte nicht verfügbar",
"Cyclones · NHC / CPHC": "Wirbelstürme · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlantik · östl./zentr. Pazifik",
"{storms} · {name} selected": "{storms} · {name} ausgewählt",
"Official advisory ↗": "Offizieller Lagebericht ↗",
"Active NHC and CPHC cyclone advisories": "Aktive Wirbelsturm-Lageberichte von NHC und CPHC",
"Wind unavailable": "Wind nicht verfügbar",
"Advisory center / forecast track": "Zentrum laut Lagebericht / Vorhersagebahn",
"Center-track uncertainty cone": "Unsicherheitskegel der Zentrumsbahn",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Einen Sturm auf der Karte auswählen oder in der Liste wählen, um ihn auszuwählen und die Kamera dorthin zu bewegen. Auf eine leere Kartenstelle klicken, um die Auswahl aufzuheben. Kontext aus Lageberichten von NOAA NHC/CPHC. Der Kegel beschreibt die Unsicherheit der vorhergesagten Zentrumsbahn, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Die Beschriftungen der Vorhersagepunkte sind Vorlaufstunden der Quelle, keine aus dem Ausgabezeitpunkt berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Darstellungshöhe hat keine meteorologische Bedeutung. Den offiziellen Lagebericht beachten.",
"DRIVE": "AUTO",
"Drive": "Auto",
"WALK": "ZU FUSS",
@@ -1733,6 +1727,11 @@
"Unnamed incident": "Unbenannter Einsatz",
"Open {title} on InciWeb": "{title} auf InciWeb öffnen",
"Perimeter source unavailable": "Quelle der Brandgrenzen nicht verfügbar",
"Not contained or unknown": "Nicht eingedämmt oder unbekannt",
"Under 50% contained": "Unter 50 % eingedämmt",
"50–99% contained": "50–99 % eingedämmt",
"Fully contained": "Vollständig eingedämmt",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Die Farbe zeigt die gemeldete Eindämmung. Brandgrenzen sind auf etwa 100 m vereinfacht.",
"Malformed perimeter snapshot": "Fehlerhafter Brandgrenzen-Snapshot",
"radio tag|All": "Alle",
"Directory refresh degraded; showing the previous station catalog.": "Verzeichnisaktualisierung eingeschränkt; der vorherige Senderkatalog wird gezeigt.",
@@ -4421,11 +4420,17 @@
"Connecting to telemetry…": "Verbindung zur Telemetrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung.",
"last growth {age} ago": "zuletzt gewachsen vor {age}",
"New in 6 hours": "Neu in den letzten 6 Stunden",
"6–24 hours": "6–24 Stunden",
"1–3 days": "1–3 Tage",
"Older or unknown": "Älter oder unbekannt",
"Colour shows how long ago each area was mapped.": "Die Farbe zeigt, wie lange die Kartierung jeder Fläche her ist.",
"Perimeters are simplified to about 100 m.": "Brandgrenzen sind auf etwa 100 m vereinfacht."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlantik und östlicher/zentraler Nordpazifik. JTWC: westlicher Nordpazifik, nördlicher Indischer Ozean und Südhalbkugel.",
"34-knot wind danger area": "Gefahrenbereich für 34-Knoten-Wind",
"Track and 34-knot wind danger area match this warning": "Zugbahn und 34-Knoten-Gefahrenbereich passen zu dieser Warnung",
"Track/danger area awaiting warning {number}": "Zugbahn/Gefahrenbereich warten auf Warnung {number}",
"Track/danger area unavailable": "Zugbahn/Gefahrenbereich nicht verfügbar",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC-Warnung: Maßgeblich ist die Warnung des regionalen Zentrums. JTWC-Winde sind 1-Minuten-Mittel.",
"No active tropical cyclone warnings": "Keine aktiven Warnungen vor tropischen Wirbelstürmen",
"Cyclones · NHC / CPHC · JTWC": "Wirbelstürme · NHC / CPHC · JTWC",
"All tropical basins": "Alle tropischen Becken",
"JTWC warning ↗": "JTWC-Warnung ↗",
"Active cyclone advisories and warnings": "Aktive Wirbelsturm-Lageberichte und -Warnungen",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Wähle einen Sturm auf der Karte oder in der Liste, um ihn auszuwählen und die Kamera hinzubewegen. Ein Klick auf eine leere Kartenstelle hebt die Auswahl auf. Lageberichte von NOAA NHC/CPHC und Warnungen des JTWC. Der NHC-Kegel beschreibt die Unsicherheit der vorhergesagten Zugbahn des Zentrums, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Der 34-Knoten-Gefahrenbereich des JTWC ist das Gebiet, das Winde von 34 Knoten erreichen können, erweitert um den Fehler der Zugbahnvorhersage; er ist kein Kegel. Die Beschriftungen der Vorhersagepunkte sind die Vorlaufstunden der Quelle, keine aus der Ausgabe berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Höhe ist keine Wetterhöhe. Maßgeblich sind der offizielle Lagebericht oder das regionale Warnzentrum.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Warnung {number} · ausgegeben {time}"
}
+18 -13
View File
@@ -1342,7 +1342,6 @@
"None on screen — nearby cameras are outside the view": "Ninguna en pantalla — las cámaras cercanas están fuera de la vista",
"ALPR camera": "Cámara ALPR",
"OpenStreetMap · community mapped": "OpenStreetMap · mapeado por la comunidad",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlántico y Pacífico Norte oriental/central; no es una cobertura mundial de ciclones.",
"Potential tropical cyclone": "Posible ciclón tropical",
"Post-tropical cyclone": "Ciclón postropical",
"Hurricane": "Huracán",
@@ -1365,17 +1364,12 @@
"Maximum sustained wind: {wind}": "Viento máximo sostenido: {wind}",
"Pressure: {pressure}": "Presión: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
"No active NHC/CPHC systems": "Sin sistemas activos del NHC/CPHC",
"Advisories unavailable": "Avisos no disponibles",
"Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlántico · Pacífico E/C",
"{storms} · {name} selected": "{storms} · {name} seleccionado",
"Official advisory ↗": "Aviso oficial ↗",
"Active NHC and CPHC cyclone advisories": "Avisos de ciclones activos del NHC y el CPHC",
"Wind unavailable": "Viento no disponible",
"Advisory center / forecast track": "Centro del ciclón según el aviso / trayectoria pronosticada",
"Center-track uncertainty cone": "Cono de incertidumbre de la trayectoria del centro",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecciona un ciclón en el mapa, o elige uno en la lista para seleccionarlo y mover la cámara. Haz clic en un espacio vacío del mapa para borrar la selección. Contexto de avisos NOAA NHC/CPHC. El cono describe la incertidumbre de la trayectoria pronosticada del centro, no el tamaño del ciclón ni toda el área de peligro. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas a partir de la emisión del aviso. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial.",
"Directions": "Indicaciones",
"{mode} — reroute for {modeLower}": "{mode} — recalcular la ruta {modeLower}",
"CLICK MAP": "CLIC EN EL MAPA",
@@ -1417,6 +1411,11 @@
"Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
"Routing unavailable": "Rutas no disponibles",
"Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
"Not contained or unknown": "Sin contener o desconocido",
"Under 50% contained": "Contenido por debajo del 50%",
"50–99% contained": "Contenido al 50–99%",
"Fully contained": "Totalmente contenido",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
"MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
"DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
@@ -4527,11 +4526,17 @@
"Connecting to telemetry…": "Conectando con la telemetría…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración.",
"last growth {age} ago": "último crecimiento hace {age}",
"New in 6 hours": "Nuevo en las últimas 6 horas",
"6–24 hours": "6–24 horas",
"1–3 days": "1–3 días",
"Older or unknown": "Más antiguo o desconocido",
"Colour shows how long ago each area was mapped.": "El color indica hace cuánto se cartografió cada zona.",
"Perimeters are simplified to about 100 m.": "Los perímetros se simplifican a unos 100 m."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlántico y Pacífico Norte oriental/central. JTWC: Pacífico Norte occidental, océano Índico Norte y hemisferio sur.",
"34-knot wind danger area": "Zona de peligro de vientos de 34 nudos",
"Track and 34-knot wind danger area match this warning": "La trayectoria y la zona de peligro de 34 nudos coinciden con este aviso",
"Track/danger area awaiting warning {number}": "Trayectoria/zona de peligro a la espera del aviso {number}",
"Track/danger area unavailable": "Trayectoria/zona de peligro no disponibles",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Aviso del JTWC: el aviso oficial es el del centro regional. Los vientos del JTWC son promedios de 1 minuto.",
"No active tropical cyclone warnings": "Sin avisos activos de ciclones tropicales",
"Cyclones · NHC / CPHC · JTWC": "Ciclones · NHC / CPHC · JTWC",
"All tropical basins": "Todas las cuencas tropicales",
"JTWC warning ↗": "Aviso del JTWC ↗",
"Active cyclone advisories and warnings": "Avisos activos de ciclones",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecciona una tormenta en el mapa o elige una en la lista para seleccionarla y mover la cámara. Haz clic en una zona vacía del mapa para quitar la selección. Avisos de NOAA NHC/CPHC y del JTWC. El cono del NHC describe la incertidumbre de la trayectoria prevista del centro, no el tamaño de la tormenta ni toda la zona de peligro. La zona de peligro de 34 nudos del JTWC es donde pueden llegar vientos de 34 nudos, ampliada por el error de la trayectoria prevista; no es un cono. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas desde la emisión. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial o el centro de avisos regional.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
}
+18 -13
View File
@@ -644,7 +644,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "CONTEXTE {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · CARACT. : CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantique et Pacifique Nord oriental/central ; pas une couverture mondiale des cyclones.",
"Cyclone advisories unavailable": "Bulletins cycloniques indisponibles",
"Cyclone data unavailable": "Données cycloniques indisponibles",
"Potential tropical cyclone": "Cyclone tropical potentiel",
@@ -669,17 +668,12 @@
"Maximum sustained wind: {wind}": "Vent maximal soutenu : {wind}",
"Pressure: {pressure}": "Pression : {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bulletin {number} · émis le {time}",
"No active NHC/CPHC systems": "Aucun système actif NHC/CPHC",
"Advisories unavailable": "Bulletins indisponibles",
"Cyclones · NHC / CPHC": "Cyclones · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlantique · Pacifique E/C",
"{storms} · {name} selected": "{storms} · {name} sélectionné",
"Official advisory ↗": "Bulletin officiel ↗",
"Active NHC and CPHC cyclone advisories": "Bulletins cycloniques actifs du NHC et du CPHC",
"Wind unavailable": "Vent indisponible",
"Advisory center / forecast track": "Centre selon le bulletin / trajectoire prévue",
"Center-track uncertainty cone": "Cône d'incertitude de la trajectoire du centre",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Sélectionnez un cyclone sur la carte, ou choisissez-en un dans la liste pour le sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Contexte des bulletins NOAA NHC/CPHC. Le cône décrit l'incertitude de la trajectoire prévue du centre, pas la taille du cyclone ni toute la zone de danger. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l'émission du bulletin. La géométrie suit la surface ; la hauteur n'est pas une altitude météorologique. Consultez le bulletin officiel.",
"DRIVE": "VOITURE",
"Drive": "En voiture",
"WALK": "À PIED",
@@ -1076,6 +1070,11 @@
"Unnamed incident": "Incident sans nom",
"Open {title} on InciWeb": "Ouvrir {title} sur InciWeb",
"Perimeter source unavailable": "Source des périmètres indisponible",
"Not contained or unknown": "Non circonscrit ou inconnu",
"Under 50% contained": "Circonscrit à moins de 50 %",
"50–99% contained": "Circonscrit à 50–99 %",
"Fully contained": "Entièrement circonscrit",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "La couleur indique la part du périmètre déclarée circonscrite. Les périmètres sont simplifiés à environ 100 m.",
"Malformed perimeter snapshot": "Instantané des périmètres mal formé",
"radio tag|All": "Toutes",
"News": "Actualités",
@@ -4527,11 +4526,17 @@
"Connecting to telemetry…": "Connexion à la télémétrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration.",
"last growth {age} ago": "dernière progression il y a {age}",
"New in 6 hours": "Nouveau, moins de 6 heures",
"6–24 hours": "6–24 heures",
"1–3 days": "1–3 jours",
"Older or unknown": "Plus ancien ou inconnu",
"Colour shows how long ago each area was mapped.": "La couleur indique depuis combien de temps chaque zone a été cartographiée.",
"Perimeters are simplified to about 100 m.": "Les périmètres sont simplifiés à environ 100 m."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC : Atlantique et Pacifique Nord oriental/central. JTWC : Pacifique Nord occidental, nord de l’océan Indien et hémisphère Sud.",
"34-knot wind danger area": "Zone de danger des vents de 34 nœuds",
"Track and 34-knot wind danger area match this warning": "La trajectoire et la zone de danger de 34 nœuds correspondent à cet avertissement",
"Track/danger area awaiting warning {number}": "Trajectoire/zone de danger en attente de l’avertissement {number}",
"Track/danger area unavailable": "Trajectoire/zone de danger indisponibles",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Avertissement du JTWC : l’avertissement officiel est celui du centre régional. Les vents du JTWC sont des moyennes sur 1 minute.",
"No active tropical cyclone warnings": "Aucun avertissement de cyclone tropical en cours",
"Cyclones · NHC / CPHC · JTWC": "Cyclones · NHC / CPHC · JTWC",
"All tropical basins": "Tous les bassins tropicaux",
"JTWC warning ↗": "Avertissement du JTWC ↗",
"Active cyclone advisories and warnings": "Bulletins et avertissements cycloniques en cours",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Sélectionnez une tempête sur la carte, ou choisissez-en une dans la liste pour la sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Bulletins NOAA NHC/CPHC et avertissements du JTWC. Le cône du NHC décrit l’incertitude de la trajectoire prévue du centre, pas la taille de la tempête ni toute la zone de danger. La zone de danger de 34 nœuds du JTWC est l’endroit que peuvent atteindre des vents de 34 nœuds, élargi de l’erreur de prévision de trajectoire ; ce n’est pas un cône. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l’émission. La géométrie suit la surface ; la hauteur n’est pas une altitude météorologique. Consultez le bulletin officiel ou le centre d’avertissement régional.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avertissement {number} · émis {time}"
}
+18 -13
View File
@@ -532,7 +532,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "הקשר {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · מפרט: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "האטלנטי והפסיפיק הצפוני המזרחי/מרכזי; אין כיסוי ציקלונים עולמי.",
"Cyclone advisories unavailable": "עדכוני ציקלונים אינם זמינים",
"Cyclone data unavailable": "נתוני ציקלונים אינם זמינים",
"Potential tropical cyclone": "ציקלון טרופי פוטנציאלי",
@@ -557,17 +556,12 @@
"Maximum sustained wind: {wind}": "רוח מתמשכת מרבית: {wind}",
"Pressure: {pressure}": "לחץ: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · עדכון {number} · פורסם {time}",
"No active NHC/CPHC systems": "אין מערכות NHC/CPHC פעילות",
"Advisories unavailable": "עדכונים אינם זמינים",
"Cyclones · NHC / CPHC": "ציקלונים · NHC / CPHC",
"Atlantic · E/C Pacific": "האטלנטי · מזרח ומרכז הפסיפיק",
"{storms} · {name} selected": "{storms} · {name} נבחר",
"Official advisory ↗": "עדכון רשמי ↗",
"Active NHC and CPHC cyclone advisories": "עדכוני ציקלונים פעילים של NHC ו-CPHC",
"Wind unavailable": "רוח אינה זמינה",
"Advisory center / forecast track": "מרכז הסערה לפי העדכון / מסלול התחזית",
"Center-track uncertainty cone": "חרוט אי-הוודאות של מסלול המרכז",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "בחר סערה במפה, או בחר סערה ברשימה כדי לבחור אותה ולהזיז את המצלמה. לחץ בשטח ריק במפה כדי לבטל את הבחירה. הקשר עדכונים של NOAA NHC/CPHC. החרוט מתאר אי-ודאות של מסלול המרכז בתחזית, לא את גודל הסערה ולא את מלוא אזור הסכנה. תוויות נקודות התחזית הן שעות חיזוי של המקור, לא זמנים שחושבו מפרסום העדכון. הגאומטריה נצמדת לפני הקרקע; הגובה אינו גובה מטאורולוגי. עיין בעדכון הרשמי.",
"Malformed cyclone snapshot": "תמונת מצב של ציקלון פגומה",
"Cyclone request timed out": "בקשת הציקלון חרגה מהזמן הקצוב",
"DRIVE": "נסיעה",
@@ -925,6 +919,11 @@
"Unnamed incident": "אירוע ללא שם",
"Open {title} on InciWeb": "פתיחת {title} ב-InciWeb",
"Perimeter source unavailable": "מקור ההיקף אינו זמין",
"Not contained or unknown": "ללא הכלה או לא ידוע",
"Under 50% contained": "הכלה מתחת ל-50%",
"50–99% contained": "הכלה 50–99%",
"Fully contained": "הכלה מלאה",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "הצבע מציג את ההכלה שדווחה. ההיקפים מפושטים לכ-100 מ׳.",
"Malformed perimeter snapshot": "תמונת מצב היקף פגומה",
"radio tag|All": "הכול",
"News": "חדשות",
@@ -4527,11 +4526,17 @@
"Connecting to telemetry…": "מתחבר לטלמטריה…",
"{seconds} s": "{seconds} שנ׳",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד.",
"last growth {age} ago": "התפשטות אחרונה לפני {age}",
"New in 6 hours": "חדש ב-6 השעות האחרונות",
"6–24 hours": "6–24 שעות",
"1–3 days": "1–3 ימים",
"Older or unknown": "ישן יותר או לא ידוע",
"Colour shows how long ago each area was mapped.": "הצבע מציג לפני כמה זמן מופה כל אזור.",
"Perimeters are simplified to about 100 m.": "ההיקפים מפושטים לכ-100 מ׳."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: האוקיינוס האטלנטי ומזרח ומרכז צפון האוקיינוס השקט. JTWC: מערב צפון האוקיינוס השקט, צפון האוקיינוס ההודי וחצי הכדור הדרומי.",
"34-knot wind danger area": "אזור סכנה של רוחות 34 קשר",
"Track and 34-knot wind danger area match this warning": "המסלול ואזור הסכנה של 34 קשר תואמים לאזהרה הזו",
"Track/danger area awaiting warning {number}": "מסלול/אזור סכנה ממתינים לאזהרה {number}",
"Track/danger area unavailable": "מסלול/אזור סכנה אינם זמינים",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "אזהרת JTWC: האזהרה הרשמית היא של המרכז האזורי. רוחות JTWC הן ממוצעים של דקה אחת.",
"No active tropical cyclone warnings": "אין אזהרות פעילות מפני ציקלונים טרופיים",
"Cyclones · NHC / CPHC · JTWC": "ציקלונים · NHC / CPHC · JTWC",
"All tropical basins": "כל האגנים הטרופיים",
"JTWC warning ↗": "אזהרת JTWC ↗",
"Active cyclone advisories and warnings": "עדכוני ציקלונים ואזהרות פעילים",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "בחרו סופה במפה, או בחרו סופה ברשימה כדי לסמן אותה ולהזיז אליה את המצלמה. לחיצה על מקום ריק במפה מבטלת את הבחירה. עדכוני NOAA NHC/CPHC ואזהרות JTWC. החרוט של NHC מתאר את אי-הוודאות במסלול החזוי של המרכז, לא את גודל הסופה ולא את כל אזור הסכנה. אזור הסכנה של 34 קשר של JTWC הוא המקום שאליו עשויות להגיע רוחות של 34 קשר, מורחב בשגיאת תחזית המסלול; הוא אינו חרוט. התוויות של נקודות התחזית הן שעות התחזית של המקור, לא זמנים שחושבו ממועד הפרסום. הצורות עוקבות אחר פני השטח; הגובה אינו גובה מטאורולוגי. עיינו בעדכון הרשמי או במרכז ההתרעות האזורי.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · אזהרה {number} · פורסמה {time}"
}
+18 -13
View File
@@ -644,7 +644,6 @@
"SRC {value}": "FONTE {value}",
"{value} CONTEXT": "CONTESTO {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPECIFICHE: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantico e Pacifico settentrionale orientale/centrale; non è una copertura mondiale dei cicloni.",
"Cyclone advisories unavailable": "Bollettini sui cicloni non disponibili",
"Cyclone data unavailable": "Dati sui cicloni non disponibili",
"Potential tropical cyclone": "Potenziale ciclone tropicale",
@@ -669,17 +668,12 @@
"Maximum sustained wind: {wind}": "Vento massimo sostenuto: {wind}",
"Pressure: {pressure}": "Pressione: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bollettino {number} · emesso {time}",
"No active NHC/CPHC systems": "Nessun sistema NHC/CPHC attivo",
"Advisories unavailable": "Bollettini non disponibili",
"Cyclones · NHC / CPHC": "Cicloni · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlantico · Pacifico E/C",
"{storms} · {name} selected": "{storms} · selezione: {name}",
"Official advisory ↗": "Bollettino ufficiale ↗",
"Active NHC and CPHC cyclone advisories": "Bollettini attivi sui cicloni di NHC e CPHC",
"Wind unavailable": "Vento non disponibile",
"Advisory center / forecast track": "Centro del ciclone da bollettino / traccia prevista",
"Center-track uncertainty cone": "Cono di incertezza della traccia del centro",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Seleziona una tempesta sulla mappa, o scegline una nell'elenco per selezionarla e spostare la camera. Fai clic su un punto vuoto della mappa per annullare la selezione. Contesto dai bollettini NOAA NHC/CPHC. Il cono descrive l'incertezza sulla traccia prevista del centro, non le dimensioni della tempesta né l'intera area di pericolo. Le etichette dei punti di previsione indicano le scadenze di previsione in ore fornite dalla fonte, non orari calcolati dall'emissione del bollettino. La geometria segue la superficie; l'altezza non è la quota meteorologica. Consulta il bollettino ufficiale.",
"DRIVE": "AUTO",
"Drive": "In auto",
"WALK": "A PIEDI",
@@ -1076,6 +1070,11 @@
"Unnamed incident": "Incendio senza nome",
"Open {title} on InciWeb": "Apri {title} su InciWeb",
"Perimeter source unavailable": "Fonte dei perimetri non disponibile",
"Not contained or unknown": "Non contenuto o dato non disponibile",
"Under 50% contained": "Contenuto a meno del 50%",
"50–99% contained": "Contenuto al 50–99%",
"Fully contained": "Completamente contenuto",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Il colore indica il contenimento riportato. I perimetri sono semplificati a circa 100 m.",
"Malformed perimeter snapshot": "Snapshot dei perimetri non valido",
"radio tag|All": "Tutti",
"News": "Notizie",
@@ -4527,11 +4526,17 @@
"Connecting to telemetry…": "Connessione alla telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo.",
"last growth {age} ago": "ultima espansione {age} fa",
"New in 6 hours": "Nuovo nelle ultime 6 ore",
"6–24 hours": "6–24 ore",
"1–3 days": "1–3 giorni",
"Older or unknown": "Più vecchio o sconosciuto",
"Colour shows how long ago each area was mapped.": "Il colore indica da quanto tempo ogni area è stata mappata.",
"Perimeters are simplified to about 100 m.": "I perimetri sono semplificati a circa 100 m."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlantico e Pacifico settentrionale orientale/centrale. JTWC: Pacifico settentrionale occidentale, Oceano Indiano settentrionale ed emisfero australe.",
"34-knot wind danger area": "Area di pericolo per venti a 34 nodi",
"Track and 34-knot wind danger area match this warning": "Traccia e area di pericolo a 34 nodi corrispondono a questo avviso",
"Track/danger area awaiting warning {number}": "Traccia/area di pericolo in attesa dell’avviso {number}",
"Track/danger area unavailable": "Traccia/area di pericolo non disponibili",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Avviso JTWC: l’avviso ufficiale è quello del centro regionale. I venti JTWC sono medie su 1 minuto.",
"No active tropical cyclone warnings": "Nessun avviso attivo di ciclone tropicale",
"Cyclones · NHC / CPHC · JTWC": "Cicloni · NHC / CPHC · JTWC",
"All tropical basins": "Tutti i bacini tropicali",
"JTWC warning ↗": "Avviso JTWC ↗",
"Active cyclone advisories and warnings": "Bollettini e avvisi attivi sui cicloni",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Seleziona una tempesta sulla mappa o sceglila nell’elenco per selezionarla e spostare la telecamera. Fai clic su un punto vuoto della mappa per annullare la selezione. Bollettini NOAA NHC/CPHC e avvisi JTWC. Il cono NHC descrive l’incertezza della traccia prevista del centro, non le dimensioni della tempesta né l’intera area di pericolo. L’area di pericolo a 34 nodi del JTWC è dove possono arrivare venti a 34 nodi, ampliata dall’errore di previsione della traccia; non è un cono. Le etichette dei punti di previsione sono ore di anticipo della fonte, non orari calcolati dall’emissione. La geometria segue la superficie; l’altezza non è quota meteorologica. Consulta il bollettino ufficiale o il centro di allerta regionale.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avviso {number} · emesso {time}"
}
+18 -13
View File
@@ -616,7 +616,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "{value}コンテキスト",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 仕様:CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "大西洋と北太平洋東部・中部のみです。全世界のサイクロンを網羅するものではありません。",
"Cyclone advisories unavailable": "サイクロン情報を取得できません",
"Cyclone data unavailable": "サイクロンデータを取得できません",
"Potential tropical cyclone": "サイクロン化のおそれがある擾乱",
@@ -639,17 +638,12 @@
"Maximum sustained wind: {wind}": "最大持続風速:{wind}",
"Pressure: {pressure}": "気圧:{pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第{number}報 · {time}発表",
"No active NHC/CPHC systems": "NHC/CPHCが監視中のサイクロンはありません",
"Advisories unavailable": "サイクロン情報を取得できません",
"Cyclones · NHC / CPHC": "サイクロン · NHC / CPHC",
"Atlantic · E/C Pacific": "大西洋 · 東部/中部太平洋",
"{storms} · {name} selected": "{storms} · {name}を選択中",
"Official advisory ↗": "公式情報 ↗",
"Active NHC and CPHC cyclone advisories": "発生中のNHCおよびCPHCサイクロン情報",
"Wind unavailable": "風のデータを取得できません",
"Advisory center / forecast track": "発表時の中心 / 予報進路",
"Center-track uncertainty cone": "中心進路の予報円",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "地図上でサイクロンを選択するか、リストから選ぶと、そのサイクロンが選択されてカメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報に基づく表示です。予報円は予報される中心進路の不確かさを示すもので、サイクロンの大きさや危険範囲全体ではありません。予報点のラベルはソースの予報時間で、発表時刻から計算した時刻ではありません。図形は地表に沿って表示され、高さは気象上の高度ではありません。公式情報を確認してください。",
"DRIVE": "車",
"Drive": "車",
"WALK": "徒歩",
@@ -1030,6 +1024,11 @@
"Unnamed incident": "名称未設定の火災",
"Open {title} on InciWeb": "InciWebで{title}を開く",
"Perimeter source unavailable": "延焼範囲のソースを利用できません",
"Not contained or unknown": "封じ込め率0%または不明",
"Under 50% contained": "封じ込め率50%未満",
"50–99% contained": "封じ込め率50–99%",
"Fully contained": "封じ込め率100%",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "色は報告された封じ込め率を示します。延焼範囲の輪郭は約100 mの精度で簡略化されています。",
"Malformed perimeter snapshot": "延焼範囲スナップショットの形式が不正です",
"radio tag|All": "すべて",
"News": "ニュース",
@@ -4315,11 +4314,17 @@
"Connecting to telemetry…": "テレメトリに接続中…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。",
"last growth {age} ago": "{age}前に最終拡大",
"New in 6 hours": "6時間以内の新規",
"6–24 hours": "6–24時間",
"1–3 days": "1–3日",
"Older or unknown": "それ以前または不明",
"Colour shows how long ago each area was mapped.": "色は各範囲が地図化されてからの経過時間を示します。",
"Perimeters are simplified to about 100 m.": "延焼範囲の輪郭は約100 mの精度で簡略化されています。"
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋、北太平洋東部・中部。JTWC:北西太平洋、北インド洋、南半球。",
"34-knot wind danger area": "34ノット風の危険域",
"Track and 34-knot wind danger area match this warning": "進路と34ノット風の危険域はこの警報と一致しています",
"Track/danger area awaiting warning {number}": "進路/危険域は第{number}号警報待ち",
"Track/danger area unavailable": "進路/危険域は利用できません",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC警報:公式の警報は地域センターの警報です。JTWCの風速は1分間平均です。",
"No active tropical cyclone warnings": "発表中の熱帯低気圧警報はありません",
"Cyclones · NHC / CPHC · JTWC": "サイクロン · NHC / CPHC · JTWC",
"All tropical basins": "すべての熱帯海域",
"JTWC warning ↗": "JTWC警報 ↗",
"Active cyclone advisories and warnings": "発表中のサイクロン情報と警報",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "地図上の嵐を選ぶか、リストから嵐を選ぶと選択され、カメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報とJTWCの警報です。NHCの予報円は中心の予報進路の不確かさを表すもので、嵐の大きさや危険域全体ではありません。JTWCの34ノット風の危険域は、34ノットの風が及ぶおそれのある範囲を進路予報の誤差分だけ広げたもので、予報円ではありません。予報点のラベルは情報源の予報時間で、発表時刻から計算した時刻ではありません。形状は地表に沿って描かれ、高さは気象上の高度ではありません。公式の情報または地域の警報センターを確認してください。",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第{number}号警報 · {time} 発表"
}
+18 -13
View File
@@ -644,7 +644,6 @@
"SRC {value}": "FONTE {value}",
"{value} CONTEXT": "CONTEXTO {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ESPECIFICAÇÕES: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlântico e Pacífico Norte oriental/central; não é uma cobertura mundial de ciclones.",
"Cyclone advisories unavailable": "Boletins de ciclones indisponíveis",
"Cyclone data unavailable": "Dados de ciclones indisponíveis",
"Potential tropical cyclone": "Potencial ciclone tropical",
@@ -669,17 +668,12 @@
"Maximum sustained wind: {wind}": "Vento máximo sustentado: {wind}",
"Pressure: {pressure}": "Pressão: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Boletim {number} · emitido em {time}",
"No active NHC/CPHC systems": "Nenhum sistema ativo do NHC/CPHC",
"Advisories unavailable": "Boletins indisponíveis",
"Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlântico · Pacífico Leste/Central",
"{storms} · {name} selected": "{storms} · {name} selecionado",
"Official advisory ↗": "Boletim oficial ↗",
"Active NHC and CPHC cyclone advisories": "Boletins de ciclones ativos do NHC e do CPHC",
"Wind unavailable": "Vento indisponível",
"Advisory center / forecast track": "Centro do ciclone no boletim / trajetória prevista",
"Center-track uncertainty cone": "Cone de incerteza da trajetória do centro",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecione um ciclone no mapa ou escolha um na lista para selecioná-lo e mover a câmera. Clique em um espaço vazio do mapa para limpar a seleção. Contexto dos boletins NOAA NHC/CPHC. O cone descreve a incerteza da trajetória prevista do centro, não o tamanho do ciclone nem toda a área de risco. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão do boletim. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial.",
"DRIVE": "CARRO",
"Drive": "De carro",
"WALK": "A PÉ",
@@ -1074,6 +1068,11 @@
"Unnamed incident": "Sem nome",
"Open {title} on InciWeb": "Abrir {title} no InciWeb",
"Perimeter source unavailable": "Fonte de perímetros indisponível",
"Not contained or unknown": "Não contido ou desconhecido",
"Under 50% contained": "Menos de 50% contido",
"50–99% contained": "50–99% contido",
"Fully contained": "Totalmente contido",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "A cor indica a contenção informada. Os perímetros são simplificados para cerca de 100 m.",
"Malformed perimeter snapshot": "Snapshot de perímetros malformado",
"radio tag|All": "Todas",
"News": "Notícias",
@@ -4527,11 +4526,17 @@
"Connecting to telemetry…": "A ligar à telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa.",
"last growth {age} ago": "último crescimento há {age}",
"New in 6 hours": "Novo nas últimas 6 horas",
"6–24 hours": "6–24 horas",
"1–3 days": "1–3 dias",
"Older or unknown": "Mais antigo ou desconhecido",
"Colour shows how long ago each area was mapped.": "A cor indica há quanto tempo cada área foi mapeada.",
"Perimeters are simplified to about 100 m.": "Os perímetros são simplificados para cerca de 100 m."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlântico e Pacífico Norte oriental/central. JTWC: Pacífico Norte ocidental, Oceano Índico Norte e Hemisfério Sul.",
"34-knot wind danger area": "Área de perigo de ventos de 34 nós",
"Track and 34-knot wind danger area match this warning": "A trajetória e a área de perigo de 34 nós correspondem a este aviso",
"Track/danger area awaiting warning {number}": "Trajetória/área de perigo aguardando o aviso {number}",
"Track/danger area unavailable": "Trajetória/área de perigo indisponíveis",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Aviso do JTWC: o aviso oficial é o do centro regional. Os ventos do JTWC são médias de 1 minuto.",
"No active tropical cyclone warnings": "Nenhum aviso ativo de ciclone tropical",
"Cyclones · NHC / CPHC · JTWC": "Ciclones · NHC / CPHC · JTWC",
"All tropical basins": "Todas as bacias tropicais",
"JTWC warning ↗": "Aviso do JTWC ↗",
"Active cyclone advisories and warnings": "Boletins e avisos de ciclones ativos",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecione uma tempestade no mapa ou escolha uma na lista para selecioná-la e mover a câmera. Clique em uma área vazia do mapa para limpar a seleção. Boletins da NOAA NHC/CPHC e avisos do JTWC. O cone do NHC descreve a incerteza da trajetória prevista do centro, não o tamanho da tempestade nem toda a área de perigo. A área de perigo de 34 nós do JTWC é onde ventos de 34 nós podem chegar, ampliada pelo erro da previsão de trajetória; não é um cone. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial ou o centro de alertas regional.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
}
+18 -13
View File
@@ -1369,7 +1369,6 @@
"None on screen — nearby cameras are outside the view": "На экране нет — ближайшие камеры вне поля зрения",
"ALPR camera": "Камера ALPR",
"OpenStreetMap · community mapped": "OpenStreetMap · данные сообщества",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика и восточная/центральная часть северного Тихого океана; покрытие циклонов не глобальное.",
"Potential tropical cyclone": "Потенциальный тропический циклон",
"Post-tropical cyclone": "Посттропический циклон",
"Hurricane": "Ураган",
@@ -1393,17 +1392,12 @@
"Maximum sustained wind: {wind}": "Макс. устойчивый ветер: {wind}",
"Pressure: {pressure}": "Давление: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Сводка № {number} · выпущена {time}",
"No active NHC/CPHC systems": "Нет активных систем NHC/CPHC",
"Advisories unavailable": "Сводки недоступны",
"Cyclones · NHC / CPHC": "Циклоны · NHC / CPHC",
"Atlantic · E/C Pacific": "Атлантика · вост./центр. Тихий океан",
"{storms} · {name} selected": "{storms} · выбран {name}",
"Official advisory ↗": "Официальная сводка ↗",
"Active NHC and CPHC cyclone advisories": "Действующие сводки NHC и CPHC о циклонах",
"Wind unavailable": "Ветер: нет данных",
"Advisory center / forecast track": "Центр циклона по сводке / прогнозный трек",
"Center-track uncertainty cone": "Конус неопределённости трека центра",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить к нему камеру. Щёлкните по пустому месту карты, чтобы снять выделение. Контекст сводок NOAA NHC/CPHC. Конус описывает неопределённость прогнозного трека центра, а не размер шторма или всю зону опасности. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска сводки. Геометрия следует поверхности; высота не отражает высоту погодных явлений. Сверяйтесь с официальной сводкой.",
"Directions": "Маршруты",
"{mode} — reroute for {modeLower}": "{mode} — перестроить маршрут: {modeLower}",
"CLICK MAP": "ЩЁЛКНИТЕ ПО КАРТЕ",
@@ -1445,6 +1439,11 @@
"Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
"Routing unavailable": "Построение маршрута недоступно",
"Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
"Not contained or unknown": "Не локализован или неизвестно",
"Under 50% contained": "Локализован менее чем на 50%",
"50–99% contained": "Локализован на 50–99%",
"Fully contained": "Полностью локализован",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
"MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
"DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
@@ -4633,11 +4632,17 @@
"Connecting to telemetry…": "Подключение к телеметрии…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации.",
"last growth {age} ago": "последний рост {age} назад",
"New in 6 hours": "Новое за 6 часов",
"6–24 hours": "6–24 часа",
"1–3 days": "1–3 дня",
"Older or unknown": "Старше или неизвестно",
"Colour shows how long ago each area was mapped.": "Цвет показывает, как давно нанесён каждый участок.",
"Perimeters are simplified to about 100 m.": "Контуры упрощены примерно до 100 м."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Атлантика и восточная/центральная часть северного Тихого океана. JTWC: западная часть северного Тихого океана, северная часть Индийского океана и Южное полушарие.",
"34-knot wind danger area": "Опасная зона ветра 34 узла",
"Track and 34-knot wind danger area match this warning": "Трек и опасная зона ветра 34 узла соответствуют этому предупреждению",
"Track/danger area awaiting warning {number}": "Трек и опасная зона появятся с предупреждением № {number}",
"Track/danger area unavailable": "Трек и опасная зона недоступны",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Предупреждение JTWC: официальным является предупреждение регионального центра. Ветер JTWC — средний за 1 минуту.",
"No active tropical cyclone warnings": "Нет действующих предупреждений о тропических циклонах",
"Cyclones · NHC / CPHC · JTWC": "Циклоны · NHC / CPHC · JTWC",
"All tropical basins": "Все тропические бассейны",
"JTWC warning ↗": "Предупреждение JTWC ↗",
"Active cyclone advisories and warnings": "Действующие сводки и предупреждения о циклонах",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить камеру. Щелчок по пустому месту карты снимает выделение. Сводки NOAA NHC/CPHC и предупреждения JTWC. Конус NHC показывает неопределённость прогнозного трека центра, а не размер шторма или всю опасную зону. Опасная зона ветра 34 узла JTWC — это область, куда может дойти ветер 34 узла, расширенная на ошибку прогноза трека; это не конус. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска. Геометрия следует поверхности; высота не является метеорологической высотой. Сверяйтесь с официальной сводкой или региональным центром предупреждений.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Предупреждение № {number} · выпущено {time}"
}
+18 -13
View File
@@ -1352,7 +1352,6 @@
"FOV {value}° (DATASHEET)": "FOV {value}° (DATABLAD)",
"SPEC FOV {span}° (CAPABILITY)": "SPEC. FOV {span}° (FÖRMÅGA)",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPEC.: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlanten och östra/centrala norra Stilla havet; ingen global täckning av cykloner.",
"Cyclone advisories unavailable": "Cyklonbulletiner otillgängliga",
"Cyclone data unavailable": "Cyklondata otillgängliga",
"Potential tropical cyclone": "Potentiell tropisk cyklon",
@@ -1376,17 +1375,12 @@
"Maximum sustained wind: {wind}": "Högsta medelvind: {wind}",
"Pressure: {pressure}": "Lufttryck: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bulletin {number} · utfärdad {time}",
"No active NHC/CPHC systems": "Inga aktiva NHC/CPHC-system",
"Advisories unavailable": "Bulletiner otillgängliga",
"Cyclones · NHC / CPHC": "Cykloner · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlanten · östra/centrala Stilla havet",
"{storms} · {name} selected": "{storms} · {name} vald",
"Official advisory ↗": "Officiell bulletin ↗",
"Active NHC and CPHC cyclone advisories": "Aktiva cyklonbulletiner från NHC och CPHC",
"Wind unavailable": "Vind otillgänglig",
"Advisory center / forecast track": "Centrum enligt bulletin / prognosbana",
"Center-track uncertainty cone": "Osäkerhetskon för centrumbanan",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran dit. Klicka på en tom yta på kartan för att avmarkera. Underlag: bulletiner från NOAA NHC/CPHC. Konen beskriver osäkerheten i den prognostiserade centrumbanan, inte stormens storlek eller hela riskområdet. Etiketterna vid prognospunkterna är källans prognostimmar, inte tider beräknade från bulletinens utfärdande. Geometrin följer ytan; höjden motsvarar ingen höjd i atmosfären. Läs den officiella bulletinen.",
"DRIVE": "BIL",
"Drive": "Bil",
"WALK": "GÅNG",
@@ -1649,6 +1643,11 @@
"Unnamed incident": "Namnlös händelse",
"Open {title} on InciWeb": "Öppna {title} på InciWeb",
"Perimeter source unavailable": "Källa för brandgränser otillgänglig",
"Not contained or unknown": "Inte under kontroll eller okänt",
"Under 50% contained": "Mindre än 50 % under kontroll",
"50–99% contained": "50–99 % under kontroll",
"Fully contained": "Helt under kontroll",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Färgen visar rapporterad kontrollgrad. Brandgränserna är förenklade till cirka 100 m.",
"Malformed perimeter snapshot": "Felformaterad ögonblicksbild av brandgränser",
"radio tag|All": "Alla",
"Directory refresh degraded; showing the previous station catalog.": "Uppdateringen av katalogen är begränsad; visar den tidigare stationskatalogen.",
@@ -4421,11 +4420,17 @@
"Connecting to telemetry…": "Ansluter till telemetri…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration.",
"last growth {age} ago": "senaste tillväxt för {age} sedan",
"New in 6 hours": "Nytt de senaste 6 timmarna",
"6–24 hours": "6–24 timmar",
"1–3 days": "1–3 dagar",
"Older or unknown": "Äldre eller okänt",
"Colour shows how long ago each area was mapped.": "Färgen visar hur länge sedan varje område kartlades.",
"Perimeters are simplified to about 100 m.": "Brandgränserna är förenklade till cirka 100 m."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlanten och östra/centrala norra Stilla havet. JTWC: västra norra Stilla havet, norra Indiska oceanen och södra halvklotet.",
"34-knot wind danger area": "Riskområde för vind på 34 knop",
"Track and 34-knot wind danger area match this warning": "Bana och riskområde för 34 knop stämmer med denna varning",
"Track/danger area awaiting warning {number}": "Bana/riskområde väntar på varning {number}",
"Track/danger area unavailable": "Bana/riskområde inte tillgängliga",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC-varning: den regionala centralens varning är den officiella. JTWC:s vindar är 1-minutsmedelvärden.",
"No active tropical cyclone warnings": "Inga aktiva varningar för tropiska cykloner",
"Cyclones · NHC / CPHC · JTWC": "Cykloner · NHC / CPHC · JTWC",
"All tropical basins": "Alla tropiska bassänger",
"JTWC warning ↗": "JTWC-varning ↗",
"Active cyclone advisories and warnings": "Aktiva cyklonbulletiner och varningar",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran. Klicka på en tom plats på kartan för att rensa markeringen. Bulletiner från NOAA NHC/CPHC och varningar från JTWC. NHC:s kon beskriver osäkerheten i centrums prognosbana, inte stormens storlek eller hela riskområdet. JTWC:s riskområde för 34 knop är där vindar på 34 knop kan nå, vidgat med felet i banprognosen; det är ingen kon. Etiketterna på prognospunkterna är källans prognostimmar, inte tider räknade från utgivningen. Geometrin följer ytan; höjden är inte väderhöjd. Läs den officiella bulletinen eller den regionala varningscentralen.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Varning {number} · utfärdad {time}"
}
+18 -13
View File
@@ -658,7 +658,6 @@
"SRC {value}": "ДЖЕР. {value}",
"{value} CONTEXT": "КОНТЕКСТ: {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ХАРАКТЕРИСТИКИ: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика та східна/центральна частина північного Тихого океану; покриття циклонів не глобальне.",
"Cyclone advisories unavailable": "Зведення про циклони недоступні",
"Cyclone data unavailable": "Дані про циклони недоступні",
"Potential tropical cyclone": "Потенційний тропічний циклон",
@@ -684,17 +683,12 @@
"Maximum sustained wind: {wind}": "Макс. середня швидкість вітру: {wind}",
"Pressure: {pressure}": "Тиск: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Зведення № {number} · випущено {time}",
"No active NHC/CPHC systems": "Немає активних систем NHC/CPHC",
"Advisories unavailable": "Зведення недоступні",
"Cyclones · NHC / CPHC": "Циклони · NHC / CPHC",
"Atlantic · E/C Pacific": "Атлантика · сх./центр. Тихий океан",
"{storms} · {name} selected": "{storms} · вибрано {name}",
"Official advisory ↗": "Офіційне зведення ↗",
"Active NHC and CPHC cyclone advisories": "Чинні зведення NHC і CPHC про циклони",
"Wind unavailable": "Вітер: немає даних",
"Advisory center / forecast track": "Центр циклону за зведенням / прогнозний трек",
"Center-track uncertainty cone": "Конус невизначеності треку центру",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Виберіть шторм на карті або в списку, щоб виділити його й перемістити до нього камеру. Клацніть на порожньому місці карти, щоб зняти виділення. Контекст зведень NOAA NHC/CPHC. Конус описує невизначеність прогнозного треку центру, а не розмір шторму чи всю зону небезпеки. Підписи прогнозних точок показують завчасність прогнозу в годинах за даними джерела, а не час, розрахований від випуску зведення. Геометрія повторює поверхню; висота не відображає висоту погодних явищ. Звіряйтеся з офіційним зведенням.",
"DRIVE": "АВТО",
"Drive": "Автомобілем",
"WALK": "ПІШКИ",
@@ -1098,6 +1092,11 @@
"Unnamed incident": "Без назви",
"Open {title} on InciWeb": "Відкрити {title} в InciWeb",
"Perimeter source unavailable": "Джерело контурів пожеж недоступне",
"Not contained or unknown": "Не локалізовано або невідомо",
"Under 50% contained": "Локалізовано менш ніж на 50%",
"50–99% contained": "Локалізовано на 50–99%",
"Fully contained": "Повністю локалізовано",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Колір показує заявлений ступінь локалізації. Контури спрощено приблизно до 100 м.",
"Malformed perimeter snapshot": "Некоректний знімок контурів пожеж",
"radio tag|All": "Усі",
"News": "Новини",
@@ -4633,11 +4632,17 @@
"Connecting to telemetry…": "Підключення до телеметрії…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації.",
"last growth {age} ago": "останнє зростання {age} тому",
"New in 6 hours": "Нове за 6 годин",
"6–24 hours": "6–24 години",
"1–3 days": "1–3 дні",
"Older or unknown": "Старше або невідомо",
"Colour shows how long ago each area was mapped.": "Колір показує, як давно нанесено кожну ділянку.",
"Perimeters are simplified to about 100 m.": "Контури спрощено приблизно до 100 м."
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Атлантика та східна/центральна частина північного Тихого океану. JTWC: західна частина північного Тихого океану, північна частина Індійського океану та Південна півкуля.",
"34-knot wind danger area": "Небезпечна зона вітру 34 вузли",
"Track and 34-knot wind danger area match this warning": "Трек і небезпечна зона вітру 34 вузли відповідають цьому попередженню",
"Track/danger area awaiting warning {number}": "Очікуються трек і небезпечна зона для попередження № {number}",
"Track/danger area unavailable": "Трек і небезпечна зона недоступні",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Попередження JTWC: офіційним є попередження регіонального центру. Вітер JTWC — середній за 1 хвилину.",
"No active tropical cyclone warnings": "Немає чинних попереджень про тропічні циклони",
"Cyclones · NHC / CPHC · JTWC": "Циклони · NHC / CPHC · JTWC",
"All tropical basins": "Усі тропічні басейни",
"JTWC warning ↗": "Попередження JTWC ↗",
"Active cyclone advisories and warnings": "Чинні зведення та попередження про циклони",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Виберіть шторм на карті або у списку, щоб виділити його й перемістити камеру. Клацання по порожньому місцю карти знімає виділення. Зведення NOAA NHC/CPHC та попередження JTWC. Конус NHC показує невизначеність прогнозного треку центру, а не розмір шторму чи всю небезпечну зону. Небезпечна зона вітру 34 вузли JTWC — це область, куди може дійти вітер 34 вузли, розширена на похибку прогнозу треку; це не конус. Підписи прогнозних точок — завчасність джерела в годинах, а не час, обчислений від випуску. Геометрія повторює поверхню; висота не є метеорологічною висотою. Звіряйтеся з офіційним зведенням або регіональним центром попереджень.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Попередження № {number} · випущено {time}"
}
+18 -13
View File
@@ -615,7 +615,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "{value} 态势",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 规格:CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "仅覆盖大西洋及北太平洋东部和中部,并非全球气旋覆盖。",
"Cyclone advisories unavailable": "气旋公告不可用",
"Cyclone data unavailable": "气旋数据不可用",
"Potential tropical cyclone": "潜在热带气旋",
@@ -638,17 +637,12 @@
"Maximum sustained wind: {wind}": "最大持续风速:{wind}",
"Pressure: {pressure}": "气压:{pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第 {number} 号公告 · 发布于 {time}",
"No active NHC/CPHC systems": "当前没有活跃的 NHC/CPHC 气旋",
"Advisories unavailable": "公告不可用",
"Cyclones · NHC / CPHC": "气旋 · NHC / CPHC",
"Atlantic · E/C Pacific": "大西洋 · 东/中太平洋",
"{storms} · {name} selected": "{storms} · 已选择 {name}",
"Official advisory ↗": "官方公告 ↗",
"Active NHC and CPHC cyclone advisories": "活跃的 NHC 与 CPHC 气旋公告",
"Wind unavailable": "风场数据不可用",
"Advisory center / forecast track": "公告中的气旋中心 / 预报路径",
"Center-track uncertainty cone": "中心路径预报不确定范围",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "在地图上点选气旋,或在列表中点选气旋,即可选中并移动相机。点击空白地图区域可清除选择。内容来自 NOAA NHC/CPHC 公告。该区域表示气旋中心路径预报的不确定范围,不代表气旋大小或全部灾害影响范围。预报点标注的是数据源的预报时效(小时),不是按公告发布时刻推算的时间。几何图形贴地显示;显示高度并非气象高度。请以官方公告为准。",
"DRIVE": "驾车",
"Drive": "驾车",
"WALK": "步行",
@@ -1010,6 +1004,11 @@
"Unnamed incident": "未命名火情",
"Open {title} on InciWeb": "在 InciWeb 上打开 {title}",
"Perimeter source unavailable": "周界数据源不可用",
"Not contained or unknown": "未控制或未知",
"Under 50% contained": "控制低于 50%",
"50–99% contained": "控制 50–99%",
"Fully contained": "已全部控制",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "颜色表示报告的控制比例。周界简化至约 100 m。",
"Malformed perimeter snapshot": "周界快照格式错误",
"radio tag|All": "全部",
"News": "新闻",
@@ -4315,11 +4314,17 @@
"Connecting to telemetry…": "正在连接遥测…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。",
"last growth {age} ago": "最近一次扩展于 {age}前",
"New in 6 hours": "6 小时内新增",
"6–24 hours": "6–24 小时",
"1–3 days": "1–3 天",
"Older or unknown": "更早或未知",
"Colour shows how long ago each area was mapped.": "颜色表示各区域测绘至今的时间。",
"Perimeters are simplified to about 100 m.": "周界简化至约 100 m。"
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋及北太平洋东部/中部。JTWC:北太平洋西部、北印度洋及南半球。",
"34-knot wind danger area": "34 节风危险区",
"Track and 34-knot wind danger area match this warning": "路径和 34 节风危险区与本期警报一致",
"Track/danger area awaiting warning {number}": "路径/危险区等待第 {number} 号警报",
"Track/danger area unavailable": "路径/危险区不可用",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC 警报:以区域中心的警报为准。JTWC 风速为 1 分钟平均值。",
"No active tropical cyclone warnings": "当前没有生效的热带气旋警报",
"Cyclones · NHC / CPHC · JTWC": "气旋 · NHC / CPHC · JTWC",
"All tropical basins": "所有热带海域",
"JTWC warning ↗": "JTWC 警报 ↗",
"Active cyclone advisories and warnings": "生效的气旋公告和警报",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地图上选择风暴,或在列表中选择风暴以选中它并移动镜头。点击地图空白处可取消选择。NOAA NHC/CPHC 公告和 JTWC 警报。NHC 的预报不确定范围表示中心预报路径的不确定性,而不是风暴大小或整个危险区域。JTWC 的 34 节风危险区是 34 节风可能到达的范围,并按路径预报误差加宽;它不是预报不确定范围。预报点标签是数据源的预报时效(小时),不是根据发布时间计算的时刻。几何形状贴合地表;高度不是气象高度。请以官方公告或区域警报中心为准。",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 号警报 · 发布于 {time}"
}
+18 -13
View File
@@ -615,7 +615,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "{value} 態勢",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 規格:CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "僅覆蓋大西洋及北太平洋東部和中部,並非全球氣旋覆蓋。",
"Cyclone advisories unavailable": "氣旋公告不可用",
"Cyclone data unavailable": "氣旋數據不可用",
"Potential tropical cyclone": "潛在熱帶氣旋",
@@ -638,17 +637,12 @@
"Maximum sustained wind: {wind}": "最大持續風速:{wind}",
"Pressure: {pressure}": "氣壓:{pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第 {number} 號公告 · 發布於 {time}",
"No active NHC/CPHC systems": "當前沒有活躍的 NHC/CPHC 氣旋",
"Advisories unavailable": "公告不可用",
"Cyclones · NHC / CPHC": "氣旋 · NHC / CPHC",
"Atlantic · E/C Pacific": "大西洋 · 東/中太平洋",
"{storms} · {name} selected": "{storms} · 已選擇 {name}",
"Official advisory ↗": "官方公告 ↗",
"Active NHC and CPHC cyclone advisories": "活躍的 NHC 與 CPHC 氣旋公告",
"Wind unavailable": "風場數據不可用",
"Advisory center / forecast track": "公告中的氣旋中心 / 預報路徑",
"Center-track uncertainty cone": "中心路徑預報不確定範圍",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "在地圖上點選氣旋,或在列表中點選氣旋,即可選中並移動相機。點擊空白地圖區域可清除選擇。內容來自 NOAA NHC/CPHC 公告。該區域表示氣旋中心路徑預報的不確定範圍,不代表氣旋大小或全部災害影響範圍。預報點標註的是數據源的預報時效(小時),不是按公告發布時刻推算的時間。幾何圖形貼地顯示;顯示高度並非氣象高度。請以官方公告為準。",
"DRIVE": "駕車",
"Drive": "駕車",
"WALK": "步行",
@@ -1010,6 +1004,11 @@
"Unnamed incident": "未命名火情",
"Open {title} on InciWeb": "在 InciWeb 上打開 {title}",
"Perimeter source unavailable": "周界數據源不可用",
"Not contained or unknown": "未控制或未知",
"Under 50% contained": "控制低於 50%",
"50–99% contained": "控制 50–99%",
"Fully contained": "已全部控制",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "顏色表示報告的控制比例。周界簡化至約 100 m。",
"Malformed perimeter snapshot": "周界快照格式錯誤",
"radio tag|All": "全部",
"News": "新聞",
@@ -4315,11 +4314,17 @@
"Connecting to telemetry…": "正在連接遙測…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。",
"last growth {age} ago": "最近一次擴展於 {age}前",
"New in 6 hours": "6 小時內新增",
"6–24 hours": "6–24 小時",
"1–3 days": "1–3 天",
"Older or unknown": "更早或未知",
"Colour shows how long ago each area was mapped.": "顏色表示各區域測繪至今的時間。",
"Perimeters are simplified to about 100 m.": "周界簡化至約 100 m。"
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋及北太平洋東部/中部。JTWC:北太平洋西部、北印度洋及南半球。",
"34-knot wind danger area": "34 節風危險區",
"Track and 34-knot wind danger area match this warning": "路徑和 34 節風危險區與本期警報一致",
"Track/danger area awaiting warning {number}": "路徑/危險區等待第 {number} 號警報",
"Track/danger area unavailable": "路徑/危險區不可用",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC 警報:以區域中心的警報為準。JTWC 風速為 1 分鐘平均值。",
"No active tropical cyclone warnings": "當前沒有生效的熱帶氣旋警報",
"Cyclones · NHC / CPHC · JTWC": "氣旋 · NHC / CPHC · JTWC",
"All tropical basins": "所有熱帶海域",
"JTWC warning ↗": "JTWC 警報 ↗",
"Active cyclone advisories and warnings": "生效的氣旋公告和警報",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地圖上選擇風暴,或在列表中選擇風暴以選中它並移動鏡頭。點擊地圖空白處可取消選擇。NOAA NHC/CPHC 公告和 JTWC 警報。NHC 的預報不確定範圍表示中心預報路徑的不確定性,而不是風暴大小或整個危險區域。JTWC 的 34 節風危險區是 34 節風可能到達的範圍,並按路徑預報誤差加寬;它不是預報不確定範圍。預報點標籤是數據源的預報時效(小時),不是根據發布時間計算的時刻。幾何形狀貼合地表;高度不是氣象高度。請以官方公告或區域警報中心為準。",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 號警報 · 發布於 {time}"
}
+1 -1
View File
@@ -541,7 +541,7 @@
"Conversation",
"Country",
"Cyan",
"Cyclones · NHC / CPHC",
"Cyclones · NHC / CPHC · JTWC",
"DENSE",
"DEST ---°",
"DEST {bearing}",
+2 -24
View File
@@ -4,6 +4,7 @@ import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
findByDoublingRadius,
AWARENESS_RADIUS_M,
aircraftClassMatches,
} from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_EXAMPLES,
@@ -52,29 +53,7 @@ export function createNavigation({
return layerId === 'flights' || layerId === 'military';
}
function normalizeAircraftClass(value) {
return String(value || '')
.trim()
.toLowerCase();
}
function aircraftClassMatchesFilter(item, aircraftClass) {
const requested = normalizeAircraftClass(aircraftClass);
if (!requested) return true;
const candidates = [
item?.aircraftClass,
item?.klass,
item?.type,
item?.typeCode,
item?.typeName,
]
.map((value) => normalizeAircraftClass(value))
.filter(Boolean);
if (!candidates.length) return false;
return candidates.some(
(candidate) => candidate === requested || candidate.includes(requested),
);
}
const aircraftClassMatchesFilter = aircraftClassMatches;
function selectNavigationTargets(
sourceCohorts,
@@ -265,7 +244,6 @@ export function createNavigation({
summarizeAwarenessCohortForNavigation,
resetNavigationVisitedCycle,
isFlightLayer,
normalizeAircraftClass,
aircraftClassMatchesFilter,
selectNavigationTargets,
alternativeFlightAvailable,
+24
View File
@@ -1,3 +1,4 @@
import { findCamera } from '../../render/rendererOf.js';
import {
FRAME_SIGNATURE_W,
FRAME_SIGNATURE_H,
@@ -41,6 +42,11 @@ export function fitToProjection(sourceW, sourceH) {
};
}
const PLANE_POINTS = ['mount', 'tl', 'tr', 'br', 'bl'];
const _scratchPoints = [];
// Keep the occluding surface below common negative geoid undulations.
const HORIZON_MARGIN_M = 200;
export function createFrames({ state: layerState, services, parts, source }) {
/**
* FNV-1a over the RGB channels of a downsampled frame. Pure (takes the raw
@@ -236,6 +242,22 @@ export function createFrames({ state: layerState, services, parts, source }) {
ctx.fillText(status.slice(0, 58), 46, h - 42);
}
/**
* Whether a camera's monitor plane may be on screen; what cannot be judged counts as visible.
* @param {Object} record - Camera record.
* @returns {boolean}
*/
function projectionInView(record) {
const camera = findCamera(layerState._viewer);
if (typeof camera?.visiblePoints !== 'function') return true;
const placed = record.frustumPositions;
if (!placed) return true;
const points = _scratchPoints;
points.length = 0;
for (const key of PLANE_POINTS) points.push(placed[key]);
return camera.visiblePoints(points, HORIZON_MARGIN_M) !== false;
}
/**
* Triggers a new frame fetch for an image-mode projection if the refresh
* interval has elapsed. Active cameras refresh more frequently than idle ones.
@@ -269,6 +291,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
// bypass a provider's explicit minimum between image requests.
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
if (!force && sinceLastRefresh < refreshMs) return;
// Skip before stamping lastImageRefreshAt, so the first tick back in view fetches.
if (!force && !projectionInView(record)) return;
runtime.lastImageRefreshAt = now;
const frameUrl = frameUrlFor(record.camera, refreshMs);
+108
View File
@@ -3,6 +3,7 @@
// 1920x1080 projection canvas, instead of being stretched to fill it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { createFrames, fitToProjection } from './frames.js';
import {
FRAME_SIGNATURE_W,
@@ -170,3 +171,110 @@ test('a failed pixel signature redraws rather than assuming equal content', () =
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
const MOUNT = { x: 0, y: 0, z: 0 };
function planeRecord() {
return {
camera: { id: 'plane' },
position: MOUNT,
frustumPositions: {
mount: MOUNT,
capCenter: { x: 1, y: 0, z: 0 },
tl: { x: 1, y: -1, z: 1 },
tr: { x: 1, y: 1, z: 1 },
br: { x: 1, y: 1, z: -1 },
bl: { x: 1, y: -1, z: -1 },
},
projection: {
mode: 'image',
image: {},
imageLoading: false,
imageReady: false,
lastImageRefreshAt: 0,
},
};
}
function framesFor(viewer) {
const state = {
_viewer: viewer,
_healthById: new Map(),
_activeCameraId: 'plane',
};
return createFrames({
state,
services: {},
parts: {
model: {
safeNumber: (value, fallback) =>
Number.isFinite(Number(value)) ? Number(value) : fallback,
},
},
source: { getFrameUrl: () => '/api/cctv/frame?id=plane' },
});
}
function framesWithCamera(t, camera) {
const host = {};
t.after(bindRenderer(host, { camera }));
return framesFor(host);
}
test('a plane the renderer may show fetches its picture', (t) => {
const visiblePoints = t.mock.fn(() => true);
const frames = framesWithCamera(t, { visiblePoints });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(
record.projection.image.src,
/^\/api\/cctv\/frame\?id=plane&projTs=/,
);
assert.equal(record.projection.imageLoading, true);
assert.equal(visiblePoints.mock.callCount(), 1);
const [points, margin] = visiblePoints.mock.calls[0].arguments;
const { mount, tl, tr, br, bl } = record.frustumPositions;
assert.deepEqual(points, [mount, tl, tr, br, bl]);
assert.equal(points[0], mount);
assert.equal(margin, 200);
});
test('a plane the renderer cannot show is not fetched, but a forced refresh is', (t) => {
const frames = framesWithCamera(t, { visiblePoints: () => false });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
assert.equal(record.projection.lastImageRefreshAt, 0);
frames.refreshProjectionImage(record, true);
assert.match(record.projection.image.src, /projTs=/);
});
test('a skipped refresh does not use up the interval', (t) => {
let visible = false;
const frames = framesWithCamera(t, { visiblePoints: () => visible });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
visible = true;
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
});
test('what cannot be judged counts as visible', (t) => {
for (const frames of [
framesWithCamera(t, { visiblePoints: () => null }),
framesWithCamera(t, { pose: () => ({}) }),
framesFor(null),
]) {
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
}
const noGeometry = planeRecord();
delete noGeometry.frustumPositions;
const visiblePoints = t.mock.fn(() => false);
framesWithCamera(t, { visiblePoints }).refreshProjectionImage(noGeometry);
assert.equal(visiblePoints.mock.callCount(), 0);
assert.match(noGeometry.projection.image.src, /projTs=/);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { setLocale, t } from '../../i18n/index.js';
// The exact string the server sends (COVERAGE in server/providers/cyclones.js).
const SERVER_COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
const time = '2026-09-16T03:00:00.000Z';
const storm = {
id: 'ep152026',
+71 -30
View File
@@ -32,8 +32,14 @@ const utc = (value) =>
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${isolate(value.slice(11, 16))}\u00a0UTC`
: t('Unavailable');
const COVERAGE = msg(
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.',
);
// The layer's sources, and each storm's.
const SOURCE = 'NOAA NHC / CPHC · JTWC';
const AGENCY_SOURCES = Object.freeze({ nhc: 'NOAA NHC / CPHC', jtwc: 'JTWC' });
const sourceOf = (storm) => AGENCY_SOURCES[storm?.agency] || AGENCY_SOURCES.nhc;
const isJtwc = (storm) => storm?.agency === 'jtwc';
const DANGER_AREA = msg('34-knot wind danger area');
// The server sends the same English coverage (server/providers/cyclones.js);
// data stays English and is translated here, where it is shown.
const coverageText = (coverage) =>
@@ -44,7 +50,9 @@ const SERVER_REASONS = new Set([msg('Cyclone data unavailable')]);
const errorText = (error) =>
error && (SERVER_REASONS.has(error) ? t(error) : translateKnown(error));
// NHC's Tropical Cyclone Status JSON reference: PTC is post-tropical, PC is a
// potential tropical cyclone, and subtropical systems are STS and STD.
// potential tropical cyclone, and subtropical systems are STS and STD. JTWC
// warns of typhoons (TY), super typhoons (STY), tropical cyclones (TC) and
// subtropical storms and depressions (SS, SD).
const CLASSIFICATION_NAMES = Object.freeze({
PC: msg('Potential tropical cyclone'),
PTC: msg('Post-tropical cyclone'),
@@ -53,6 +61,11 @@ const CLASSIFICATION_NAMES = Object.freeze({
TD: msg('Tropical depression'),
STS: msg('Subtropical storm'),
STD: msg('Subtropical depression'),
TY: msg('Typhoon'),
STY: msg('Super typhoon'),
TC: msg('Tropical cyclone'),
SS: msg('Subtropical storm'),
SD: msg('Subtropical depression'),
});
const classificationName = (code) =>
Object.hasOwn(CLASSIFICATION_NAMES, code)
@@ -123,7 +136,7 @@ export function createCyclonesLayer({
id: contextId,
layerId: 'weather-cyclones',
layerName: 'Cyclone advisories',
source: 'NOAA NHC / CPHC',
source: sourceOf(storm),
label: storm.name,
latitude: storm.position.latitude,
longitude: storm.position.longitude,
@@ -137,6 +150,7 @@ export function createCyclonesLayer({
? CLASSIFICATION_NAMES[storm.classification]
: undefined,
basin: storm.basin,
agency: storm.agency,
advisoryNumber: storm.advisoryNumber,
issuedAt: storm.issuedAt,
positionAt: storm.positionAt,
@@ -146,7 +160,7 @@ export function createCyclonesLayer({
movementDirectionDegrees: storm.movement?.directionDegrees,
movementSpeedKt: storm.movement?.speedKt,
advisoryUrl: storm.advisoryUrl,
// Only while the proxy serves its cache because NHC is unreachable.
// Only while the proxy serves its cache because a source is unreachable.
staleCacheFetchedAt:
snapshot.stale && Number.isFinite(snapshot.fetchedAt)
? new Date(snapshot.fetchedAt).toISOString()
@@ -205,7 +219,7 @@ export function createCyclonesLayer({
id: 'weather-cyclones',
name: 'Cyclone advisories',
icon: '◉',
source: 'NOAA NHC / CPHC',
source: SOURCE,
updateInterval: 300_000,
init(nextViewer) {
viewer = nextViewer;
@@ -361,13 +375,28 @@ export function createCyclonesLayer({
snapshot && !snapshot.unavailable && snapshot.storms.length === 0;
const geometry =
storm &&
(coherentCycloneGeometry(storm)
? t('Track and cone match this advisory')
: storm.geometryStatus === 'pending'
? t('Track/cone awaiting advisory {number}', {
number: storm.advisoryNumber,
})
: t('Track/cone unavailable'));
(isJtwc(storm)
? coherentCycloneGeometry(storm)
? t('Track and 34-knot wind danger area match this warning')
: storm.geometryStatus === 'pending'
? t('Track/danger area awaiting warning {number}', {
number: storm.advisoryNumber,
})
: t('Track/danger area unavailable')
: coherentCycloneGeometry(storm)
? t('Track and cone match this advisory')
: storm.geometryStatus === 'pending'
? t('Track/cone awaiting advisory {number}', {
number: storm.advisoryNumber,
})
: t('Track/cone unavailable'));
// JTWC is not the regional warning centre for any basin.
const note =
storm && isJtwc(storm)
? t(
'JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.',
)
: '';
const status =
errorText(error) ||
(snapshot?.stale
@@ -388,14 +417,21 @@ export function createCyclonesLayer({
: '';
const intensity = storm ? intensityText(storm) : '';
const detail = storm
? t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
? isJtwc(storm)
? t('{name} · {classification} · Warning {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
: t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
: empty
? t('No active NHC/CPHC systems')
? t('No active tropical cyclone warnings')
: stormCount
? activeStorms
: loading
@@ -404,8 +440,8 @@ export function createCyclonesLayer({
const controls = {
readout: true,
summary: {
label: t('Cyclones · NHC / CPHC'),
coverage: t('Atlantic · E/C Pacific'),
label: t('Cyclones · NHC / CPHC · JTWC'),
coverage: t('All tropical basins'),
compact: stormCount
? storm
? t('{storms} · {name} selected', {
@@ -418,7 +454,9 @@ export function createCyclonesLayer({
? [
{
id: 'advisory',
label: t('Official advisory ↗'),
label: isJtwc(storm)
? t('JTWC warning ↗')
: t('Official advisory ↗'),
href: storm.advisoryUrl,
},
]
@@ -436,6 +474,7 @@ export function createCyclonesLayer({
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
{ id: 'note', text: note, muted: true },
].filter((line) => line.text)
: [],
detail,
@@ -443,7 +482,7 @@ export function createCyclonesLayer({
units: 'kt',
},
list: {
ariaLabel: t('Active NHC and CPHC cyclone advisories'),
ariaLabel: t('Active cyclone advisories and warnings'),
items: (snapshot?.storms || []).map((item, index) => ({
id: item.id,
ordinal: index + 1,
@@ -461,17 +500,19 @@ export function createCyclonesLayer({
label: t('Advisory center / forecast track'),
color: '#7fe6ed',
},
{
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
isJtwc(storm)
? { label: t(DANGER_AREA), color: '#ffb15c44' }
: {
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
]
: [],
info: storm
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}${note ? '\n' + note : ''}\n${coverageText(snapshot.coverage)}`
: `${detail}${status ? '\n' + status : ''}\n${coverageText(snapshot?.coverage)}`,
infoTitle: t(
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.',
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.',
),
};
return controls;
@@ -518,7 +559,7 @@ export function createCyclonesLayer({
loading,
error,
stale: Boolean(snapshot?.stale),
source: 'NOAA NHC / CPHC',
source: storm ? sourceOf(storm) : SOURCE,
advisoryAt: storm?.issuedAt || null,
empty: Boolean(
snapshot && !snapshot.unavailable && !snapshot.storms.length,
+66 -3
View File
@@ -861,7 +861,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
const controls = h.layer.getRowControls();
assert.equal(controls.readout, true);
assert.deepEqual(controls.chips, []);
assert.equal(controls.summary.coverage, 'Atlantic · E/C Pacific');
assert.equal(controls.summary.coverage, 'All tropical basins');
assert.equal(controls.summary.actions[0].href, storm().advisoryUrl);
assert.equal(controls.summary.lines.length, 3);
assert.deepEqual(controls.summary.settings, []);
@@ -870,7 +870,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
]);
assert.match(controls.summary.compact, /2 active storms · .* selected/);
assert.equal(controls.summary.sections, undefined);
assert.match(controls.list.ariaLabel, /NHC/);
assert.match(controls.list.ariaLabel, /cyclone advisories and warnings/);
assert.equal(controls.list.items.length, 2);
assert.equal(controls.list.items[0].active, true);
assert.match(controls.info, /awaiting advisory 10/);
@@ -912,7 +912,10 @@ test('empty successful coverage, unavailable source and stale advisory are diffe
h.layer.enable();
await h.layer.update();
assert.equal(h.layer.getStats().empty, true);
assert.match(h.layer.getRowControls().summary.detail, /No active NHC\/CPHC/);
assert.match(
h.layer.getRowControls().summary.detail,
/No active tropical cyclone warnings/,
);
next = { ...snapshot(), stale: true };
await h.layer.update();
assert.match(h.layer.getRowControls().summary.status, /stale/);
@@ -987,3 +990,63 @@ test('external cancellation and acquisition failure cannot install or retain unl
assert.ok(h.cleared > 0);
h.layer.destroy();
});
test('a JTWC warning reads as a warning, notes the official regional centre and its danger area', async () => {
const jtwc = {
...storm('sh042027'),
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
advisoryNumber: '15',
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
dangerArea: null,
};
const h = harness({ getSnapshot: async () => snapshot([jtwc]) });
try {
h.layer.enable();
await h.layer.update();
const controls = h.layer.getRowControls();
assert.match(
plain(controls.summary.detail),
/^Xavier · Tropical cyclone · Warning 15 · issued/,
);
assert.deepEqual(controls.summary.actions, [
{ id: 'advisory', label: 'JTWC warning ↗', href: jtwc.advisoryUrl },
]);
const note = controls.summary.lines.find((line) => line.id === 'note');
assert.equal(
note.text,
'JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.',
);
assert.match(controls.info, /awaiting warning 15/);
assert.match(controls.info, /regional centre’s warning is official/);
assert.deepEqual(
controls.legend.map((item) => item.label),
['Advisory center / forecast track', '34-knot wind danger area'],
);
assert.equal(h.layer.getStats().source, 'JTWC');
} finally {
h.layer.destroy();
}
});
test('an NHC advisory carries no JTWC note and keeps its cone legend', async () => {
const h = harness({ getSnapshot: async () => snapshot([storm()]) });
try {
h.layer.enable();
await h.layer.update();
const controls = h.layer.getRowControls();
assert.equal(
controls.summary.lines.find((line) => line.id === 'note'),
undefined,
);
assert.deepEqual(
controls.legend.map((item) => item.label),
['Advisory center / forecast track', 'Center-track uncertainty cone'],
);
assert.equal(h.layer.getStats().source, 'NOAA NHC / CPHC');
} finally {
h.layer.destroy();
}
});
+35 -3
View File
@@ -3,6 +3,7 @@ import {
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
import { t } from '../../i18n/index.js';
/**
* @module cyclones/labels
@@ -19,6 +20,8 @@ export const CYCLONE_LEAD_LABEL_MAX_DISTANCE_M = 4_000_000;
export const CYCLONE_OVERLAY_COHORT_LIMIT = 64;
/** Advisory centre and forecast track; single source for points and cards. */
export const CYCLONE_ACCENT = '#7fe6ed';
/** JTWC's 34-knot wind danger area: its fill, dashed edge and label. */
export const CYCLONE_DANGER_ACCENT = '#ffb15c';
/** Selected advisory centre. */
export const CYCLONE_SELECTED_ACCENT = '#ffe19a';
/** Point sizes the cards keep clear of. */
@@ -112,7 +115,32 @@ function cycloneLeadEntry(stormId, point) {
}
/**
* Storm cards for every storm and lead-hour labels for the selected one.
* The name of the selected storm's 34-knot wind danger area, on its edge.
* @param {string} stormId
* @param {object} position
* @returns {object}
*/
function cycloneDangerAreaEntry(stormId, position) {
return {
...SHARED_CARD,
...markerClearance(0),
id: `area:${stormId}`,
position,
variant: 'card',
title: t('34-knot wind danger area'),
details: [],
accent: CYCLONE_DANGER_ACCENT,
selected: false,
protected: false,
// Below every lead-hour label.
priority: LEAD_PRIORITY - 200,
maxDistance: Number.POSITIVE_INFINITY,
};
}
/**
* Storm cards for every storm, and lead-hour labels and the danger area's
* name for the selected one.
* @param {Array<object>} storms Renderer anchors with `forecasts`.
* @param {?string} selectedId
* @returns {Array<object>}
@@ -125,13 +153,17 @@ export function cycloneOverlayEntries(storms, selectedId) {
if (!selected) continue;
for (const point of storm.forecasts || [])
entries.push(cycloneLeadEntry(storm.id, point));
if (storm.dangerArea)
entries.push(cycloneDangerAreaEntry(storm.id, storm.dangerArea));
}
return entries;
}
/** Storm id behind a published card or lead-hour label id, else null. */
/** Storm id behind a published card, lead-hour or area label id, else null. */
export function cycloneStormIdFromEntryId(entryId) {
const match = /^(?:storm|lead):([^:]+)(?::|$)/.exec(String(entryId ?? ''));
const match = /^(?:storm|lead|area):([^:]+)(?::|$)/.exec(
String(entryId ?? ''),
);
return match ? match[1] : null;
}
+4
View File
@@ -198,3 +198,7 @@ test('storm identity resolves from card and lead-hour ids only', () => {
for (const value of ['vessel:123', 'storm:', 'lead:', '', null, undefined])
assert.equal(cycloneStormIdFromEntryId(value), null, String(value));
});
test('a danger area label names its storm', () => {
assert.equal(cycloneStormIdFromEntryId('area:sh042027'), 'sh042027');
});
+93 -33
View File
@@ -3,6 +3,7 @@ import { sphereFromPoints } from '../../geo/sphere.js';
import { drawOf } from '../../render/rendererOf.js';
import {
CYCLONE_ACCENT,
CYCLONE_DANGER_ACCENT,
CYCLONE_MARKER_PX,
CYCLONE_SELECTED_ACCENT,
createCycloneLabels,
@@ -24,6 +25,29 @@ export function coherentCycloneGeometry(storm) {
);
}
/**
* Where a danger area's label sits: the vertex of its outer ring nearest the
* forecast point halfway along the track (ECEF).
*/
function dangerAreaAnchor(ring, forecastPoints, ecef, lonLat) {
const middle = forecastPoints[Math.floor(forecastPoints.length / 2)];
if (!middle) return ring[0];
const target = ecef(lonLat(middle.position));
let best = ring[0],
bestDistance = Infinity;
for (const vertex of ring) {
const d =
(vertex.x - target.x) ** 2 +
(vertex.y - target.y) ** 2 +
(vertex.z - target.z) ** 2;
if (d < bestDistance) {
best = vertex;
bestDistance = d;
}
}
return best;
}
/** A `#rrggbb` colour at `alpha`, as CSS. */
function withAlpha(hex, alpha) {
const n = Number.parseInt(hex.slice(1), 16);
@@ -64,7 +88,14 @@ export function createCycloneRendering({ viewer, overlayHost }) {
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const emptyCounts = () => ({
storms: 0,
tracks: 0,
cones: 0,
dangerAreas: 0,
forecastPoints: 0,
});
let counts = emptyCounts();
let itemCount = 0;
function centerItem(storm) {
@@ -104,7 +135,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const nextCounts = emptyCounts();
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
@@ -130,6 +161,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
windKt: storm.windKt,
position: center,
forecasts: [],
dangerArea: null,
};
nextLabels.push(label);
nextCounts.storms++;
@@ -151,38 +183,66 @@ export function createCycloneRendering({ viewer, overlayHost }) {
});
nextCounts.tracks++;
});
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:cone:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(CYCLONE_ACCENT, 0.16),
height: 'clampGround',
});
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: 1,
mode: 'draped',
style: {
kind: 'solid',
color: withAlpha(CYCLONE_ACCENT, 0.55),
},
// NHC's cone of centre-track uncertainty, or JTWC's 34-knot wind
// danger area: drawn apart, never one as the other.
const areas = [
{ kind: 'cone', shape: storm.cone, color: CYCLONE_ACCENT },
{
kind: 'danger',
shape: storm.dangerArea,
color: CYCLONE_DANGER_ACCENT,
},
];
for (const { kind, shape, color } of areas) {
const polygons =
shape?.type === 'Polygon'
? [shape.coordinates]
: shape?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native
// geographic tessellation handles the antimeridian; never
// flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:${kind}:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(color, kind === 'cone' ? 0.16 : 0.12),
height: 'clampGround',
});
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:${kind}:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: kind === 'cone' ? 1 : 1.5,
mode: 'draped',
style:
kind === 'cone'
? { kind: 'solid', color: withAlpha(color, 0.55) }
: {
kind: 'dash',
color: withAlpha(color, 0.8),
length: 16,
},
});
});
if (kind === 'cone') nextCounts.cones++;
else {
nextCounts.dangerAreas++;
// The area's name sits on its edge nearest the middle of
// the forecast track.
label.dangerArea ??= dangerAreaAnchor(
ecefRings[0],
storm.forecastPoints,
ecef,
lonLat,
);
}
});
nextCounts.cones++;
});
}
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
@@ -252,7 +312,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
counts = emptyCounts();
},
destroy() {
if (destroyed) return;
+49
View File
@@ -210,6 +210,7 @@ test('advisory geometry keeps polygon parts, holes and geographic seam coordinat
storms: 1,
tracks: 1,
cones: 2,
dangerAreas: 0,
forecastPoints: 1,
dataSources: 1,
entities: 8,
@@ -375,6 +376,7 @@ test('clear empties the sets and a later advisory draws again', async () => {
storms: 0,
tracks: 0,
cones: 0,
dangerAreas: 0,
forecastPoints: 0,
dataSources: 0,
entities: 0,
@@ -451,3 +453,50 @@ test('labels publish committed anchors to the shared overlay and follow selectio
h.rendering.destroy();
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
});
test('a JTWC danger area is drawn apart from any cone, with a dashed edge and its name for the selected storm', async () => {
const h = harness();
const jtwc = {
...storm(),
id: 'sh042027',
cone: null,
dangerArea: {
type: 'Polygon',
coordinates: [
[
[178, 10],
[-178, 10],
[-178, 20],
[178, 10],
],
],
},
};
assert.equal(await h.rendering.setSnapshot({ storms: [jtwc] }), true);
const [area] = [...h.sets.cones.items.values()];
assert.equal(area.id, 'cyclone:sh042027:danger:0');
assert.equal(area.fill, 'rgba(255,177,92,0.12)');
const outline = [...h.sets.lines.items.values()].find(
(line) => line.id === 'cyclone:sh042027:danger:0:outline:0',
);
assert.deepEqual(outline.style, {
kind: 'dash',
color: 'rgba(255,177,92,0.8)',
length: 16,
});
const diagnostics = h.rendering.getDiagnostics();
assert.equal(diagnostics.cones, 0);
assert.equal(diagnostics.dangerAreas, 1);
// A click on the area names its storm.
assert.equal(
h.rendering.pickStorm(h.hit('cones', 'cyclone:sh042027:danger:0')),
'sh042027',
);
assert.equal(h.overlay.entry('area:sh042027'), null, 'unselected: no name');
h.rendering.setSelection('sh042027');
const name = h.overlay.entry('area:sh042027');
assert.equal(name.title, '34-knot wind danger area');
// On the area's edge, at the vertex nearest the middle forecast point.
assert.deepEqual(name.position, fromDegrees(-178, 20, 0));
h.rendering.destroy();
});
+42 -17
View File
@@ -45,22 +45,33 @@ const position = (value) => {
};
};
function officialLink(value, outlook = false) {
/** The agencies whose advisories the snapshot carries. */
export const CYCLONE_AGENCIES = Object.freeze(['nhc', 'jtwc']);
// Each agency's storm ids, advisory links and outlook links.
const AGENCY_RULES = Object.freeze({
nhc: {
id: /^(?:al|ep|cp)\d{6}$/,
origin: 'https://www.nhc.noaa.gov',
advisory: /^\/text\/[A-Z0-9]+\.shtml$/,
outlook: /^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/,
},
jtwc: {
id: /^(?:wp|io|sh|ep|cp)\d{6}$/,
origin: 'https://www.metoc.navy.mil',
advisory: /^\/jtwc\/products\/[a-z]{2}\d{4}web\.txt$/,
outlook: /^\/jtwc\/products\/(?:abpw|abio)web\.txt$/,
},
});
function officialLink(value, rules, outlook = false) {
if (value === null) return null;
const url = new URL(text(value, 256));
if (
url.origin !== 'https://www.nhc.noaa.gov' ||
url.username ||
url.password ||
url.hash
)
if (url.origin !== rules.origin || url.username || url.password || url.hash)
throw malformed();
if (
outlook
? !/^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/.test(
url.pathname + url.search,
)
: url.search || !/^\/text\/[A-Z0-9]+\.shtml$/.test(url.pathname)
? !rules.outlook.test(url.pathname + url.search)
: url.search || !rules.advisory.test(url.pathname)
)
throw malformed();
return url.href;
@@ -122,8 +133,14 @@ export function validateCycloneSnapshot(value) {
const seen = new Set(),
budget = { coordinates: 0, points: 0 };
const storms = value.storms.map((raw) => {
// A snapshot from before agencies carries NHC storms only.
const agency = raw?.agency === undefined ? 'nhc' : raw.agency;
const rules = Object.hasOwn(AGENCY_RULES, agency)
? AGENCY_RULES[agency]
: null;
if (
!/^(?:al|ep|cp)\d{6}$/.test(raw?.id) ||
!rules ||
!rules.id.test(raw?.id) ||
seen.has(raw.id) ||
!['current', 'pending', 'unavailable'].includes(raw.geometryStatus)
)
@@ -158,20 +175,27 @@ export function validateCycloneSnapshot(value) {
};
});
const track = geometry(raw.track, 'track', budget),
cone = geometry(raw.cone, 'cone', budget);
cone = geometry(raw.cone, 'cone', budget),
dangerArea = geometry(raw.dangerArea ?? null, 'cone', budget);
// NHC draws a cone of centre-track uncertainty; JTWC publishes none, but
// a 34-knot wind danger area, which is never a cone.
const area = agency === 'nhc' ? cone : dangerArea;
if ((agency === 'nhc' && dangerArea) || (agency === 'jtwc' && cone))
throw malformed();
if (
raw.geometryStatus !== 'current' &&
(track || cone || forecastPoints.length)
(track || area || forecastPoints.length)
)
throw malformed();
if (
raw.geometryStatus === 'current' &&
(!track || !cone || !forecastPoints.length)
(!track || !area || !forecastPoints.length)
)
throw malformed();
if (raw.basin !== raw.id.slice(0, 2).toUpperCase()) throw malformed();
return {
id: raw.id,
agency,
name: text(raw.name, 80),
classification: text(raw.classification, 16),
basin: raw.basin,
@@ -185,13 +209,14 @@ export function validateCycloneSnapshot(value) {
directionDegrees: number(raw.movement?.directionDegrees, 0, 360),
speedKt: number(raw.movement?.speedKt, 0, 200),
},
advisoryUrl: officialLink(raw.advisoryUrl),
outlookUrl: officialLink(raw.outlookUrl, true),
advisoryUrl: officialLink(raw.advisoryUrl, rules),
outlookUrl: officialLink(raw.outlookUrl, rules, true),
geometryStatus: raw.geometryStatus,
geometryAdvisoryNumber,
forecastPoints,
track,
cone,
dangerArea,
};
});
if (value.unavailable && storms.length) throw malformed();
+66
View File
@@ -230,3 +230,69 @@ test('source deadline cancels request and removes timer on completion', async (t
await rejected;
assert.equal(signal.aborted, true);
});
/** The current advisory as a JTWC warning with its 34-knot danger area. */
function jtwc() {
const value = current(),
storm = value.storms[0];
Object.assign(storm, {
id: 'sh042027',
agency: 'jtwc',
basin: 'SH',
classification: 'TC',
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
dangerArea: storm.cone,
cone: null,
});
return value;
}
test('a JTWC warning is accepted with its danger area and its own links, never with a cone', () => {
const [storm] = validateCycloneSnapshot(jtwc()).storms;
assert.equal(storm.agency, 'jtwc');
assert.equal(storm.cone, null);
assert.equal(storm.dangerArea.type, 'MultiPolygon');
assert.equal(
storm.advisoryUrl,
'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
);
// A snapshot from before agencies is NHC's.
assert.equal(validateCycloneSnapshot(current()).storms[0].agency, 'nhc');
for (const change of [
(s) => (s.cone = s.dangerArea),
(s) => (s.dangerArea = null),
(s) => (s.agency = 'jma'),
(s) => (s.id = 'al042027'),
(s) => (s.basin = 'WP'),
(s) => (s.advisoryUrl = 'https://www.nhc.noaa.gov/text/MIATCMEP5.shtml'),
(s) => (s.advisoryUrl = 'https://www.metoc.navy.mil/jtwc/other.txt'),
(s) =>
(s.outlookUrl = 'https://www.nhc.noaa.gov/gtwo.php?basin=epac&fdays=7'),
]) {
const value = jtwc();
change(value.storms[0]);
assert.throws(() => validateCycloneSnapshot(value), /Malformed/);
}
// NHC keeps its cone and never carries a danger area; its ids stay its own.
const nhc = current();
nhc.storms[0].dangerArea = nhc.storms[0].cone;
assert.throws(() => validateCycloneSnapshot(nhc), /Malformed/);
const western = current();
western.storms[0].id = 'wp012026';
western.storms[0].basin = 'WP';
assert.throws(() => validateCycloneSnapshot(western), /Malformed/);
// A pending JTWC warning carries no geometry.
const pending = jtwc();
Object.assign(pending.storms[0], {
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
dangerArea: null,
});
assert.equal(
validateCycloneSnapshot(pending).storms[0].geometryStatus,
'pending',
);
});
+2 -1
View File
@@ -21,11 +21,12 @@ const PIN_TURN_DEG = 0.1;
* the grounded floor: a floor-pinned row holds a CPU position, so it is not
* planned, and settling a grounded contact puts it straight onto the floor.
*/
export function createIcons({ flightState, services, parts }) {
export function createIcons({ flightState, services, parts, resolveAsset }) {
const icons = createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'flights',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+9 -1
View File
@@ -948,7 +948,12 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
return parts.icons._fleetLook(flightState._trackedIcao);
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
}
/**
@@ -1130,6 +1135,9 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up.
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+34 -15
View File
@@ -1,5 +1,9 @@
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
aircraftViewRef,
registerAircraftViews,
} from '../../data/aircraftViews.js';
import { rotorFrame } from '../../data/rotorFrames.js';
import { KNOT_MPS } from '../../data/units.js';
import {
@@ -13,6 +17,7 @@ import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
@@ -148,6 +153,9 @@ export function createLocalAdsbLayer({
* @type {{markers: object, rings: object}|null}
*/
let sets = null;
/** Whether the renderer draws markers from the aircraft view sheet
* (`aircraftViews.js`), set at `init`. */
let views = false;
let enabled = false;
let unsubscribe = null;
let unsubscribeFeeds = null;
@@ -355,31 +363,36 @@ export function createLocalAdsbLayer({
/**
* A marker's icon, where and how it now draws: a helicopter's rotor frame
* at `at` (still on the ground), an airport vehicle in its own tint, a
* ground station's mast upright.
* ground station's mast upright. On a renderer that draws view sheets, a
* kind with rendered views is drawn from the sheet along its course;
* every other marker is its flat glyph turned on screen.
*/
function markerItem(marker, basis, at) {
const kind = marker.iconKind ?? 'airliner';
const frame =
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined;
const view = views ? aircraftViewRef(kind, frame) : null;
return {
id: marker.id,
pos: marker.position,
image: aircraftIcon(
kind,
undefined,
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined,
),
image: view ?? aircraftIcon(kind, undefined, frame),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color: kind === 'vehicle' ? vehicleColor : color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
...(view
? { rotationMode: 'course', course: marker.courseDeg ?? 0 }
: {
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
}),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -773,6 +786,11 @@ export function createLocalAdsbLayer({
init(nextViewer) {
viewer = nextViewer;
const draw = drawOf(viewer);
views = registerAircraftViews(
draw,
rendererOf(viewer)?.capabilities ?? null,
resolveAsset,
);
const prefix = `${LAYER_ID}:${++instances}`;
sets = {
markers: draw.icons({
@@ -872,6 +890,7 @@ export function createLocalAdsbLayer({
models = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
views = false;
viewer = null;
void receiver.destroy?.();
},
+58
View File
@@ -223,6 +223,7 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
feeds,
services: { ...services, ...options.services },
now: () => clock.now,
...(options.resolveAsset ? { resolveAsset: options.resolveAsset } : {}),
});
layer.init(viewer);
await layer.enable();
@@ -319,6 +320,63 @@ test('local aircraft use their class silhouette at one size in magenta', async (
assert.equal(detectable.type, 'AIR');
});
test('on a renderer that draws view sheets, local aircraft draw their view along their track; vehicles and masts stay flat', async (t) => {
const { aircraftViewRef } = await import('../../data/aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
const viewer = { scene: {} };
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, {
camera: camera.port,
query: { drillPick: () => [] },
capabilities: new Set(['viewSheets']),
});
fakeInput(viewer);
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { draw, viewer },
resolveAsset: (url) => `/gev${url}`,
});
t.after(() => layer.destroy());
// Registered once, at the layer's own asset URL.
assert.deepEqual(draw.viewSheets, [
[
AIRCRAFT_VIEWS.id,
{ ...AIRCRAFT_VIEWS.sheet, image: '/gev/sprites/aircraft-views.webp' },
],
]);
receiver.set({
aircraft: [
record({ trackDeg: 0 }),
record({ icao: 'a0b702', category: 'A7' }),
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
],
});
await layer.update();
const icon = iconOf(draw, 'local-adsb:abc123');
assert.equal(icon.image, aircraftViewRef('airliner'));
assert.equal(icon.rotationMode, 'course');
assert.equal(icon.course, 0);
assert.equal('rotation' in icon, false);
assert.deepEqual(icon.size, [20, 20]);
assert.deepEqual(icon.color, MAGENTA);
assert.equal(
iconOf(draw, 'local-adsb:a0b702').image,
aircraftViewRef('helicopter', rotorFrame('local-adsb:a0b702', clock.now)),
'the rotor turns through the sheet',
);
const vehicle = iconOf(draw, 'local-adsb:a0c001');
assert.equal(vehicle.image, aircraftIcon('vehicle'));
assert.equal(vehicle.rotationMode, 'screen');
const mast = iconOf(draw, 'local-adsb:a0c003');
assert.equal(mast.image, aircraftIcon('station'));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
+2 -1
View File
@@ -8,11 +8,12 @@ import {
} from './policy.js';
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
export function createIcons({ flightState, services, parts }) {
export function createIcons({ flightState, services, parts, resolveAsset }) {
return createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'military',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+9 -1
View File
@@ -396,7 +396,12 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
return parts.icons._fleetLook(flightState._trackedIcao);
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
}
/**
@@ -1087,6 +1092,9 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up (ready + shown).
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+3 -6
View File
@@ -8,14 +8,13 @@ import { buildIncidentCard } from './cards.js';
const now = Date.UTC(2026, 9, 14);
const row = {
id: 'x',
stableId: 'x',
name: 'Lake',
acres: 1200,
containedPct: 40,
state: 'CA',
discoveredTime: now - 2 * 3600e3,
updatedTime: now - 3600e3,
lastGrowthTime: now - 3 * 3600e3,
cause: 'Human',
behavior: 'Moderate',
complexity: 'Type 3 Incident',
@@ -34,7 +33,6 @@ test('en: the fire card keeps its English wording', () => {
'part of North Complex',
'Human cause · Moderate · Type 3 Incident',
'1,500 personnel · Plumas County · $4.2M to date',
'last growth 3h ago',
'discovered 2h ago · updated 1h ago',
'InciWeb ↗ · click card to open',
]);
@@ -46,8 +44,8 @@ for (const locale of ['es', 'ru']) {
setLocale(locale);
try {
assert.notEqual(
t('Older or unknown'),
'Older or unknown',
t('Fully contained'),
'Fully contained',
'legend is translated',
);
const card = buildIncidentCard(row, now, {
@@ -62,7 +60,6 @@ for (const locale of ['es', 'ru']) {
'contained',
'discovered',
'updated',
'last growth',
'part of',
'cause',
'personnel',
+52 -11
View File
@@ -11,6 +11,55 @@ export function containmentAccent(containedPct) {
return '#8bc34a';
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/**
* Compact USD in the UI language: en "$85K / $4.2M / $1.3B", ru "4,2 млн $",
* es "4,2 M$". Null under $1,000.
@@ -100,9 +149,8 @@ function formatAge(deltaMs) {
/**
* Build the overlay-host entry for one selected incident. The caller supplies
* `position` (Cartesian) separately — this model stays JSON-safe for tests.
* @param {Object} row - A snapshot fire (see records.js).
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
* `at`, or now.
* @param {Object} row - Normalized perimeter row (see records.js).
* @param {number} nowMs - Current epoch milliseconds.
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
* @returns {Object} World-overlay entry without `position`.
*/
@@ -146,12 +194,6 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
if (cost) response.push(t('{cost} to date', { cost }));
}
const growth = formatAge(nowMs - row.lastGrowthTime);
const lastGrowth =
row.lastGrowthTime != null && growth
? t('last growth {age} ago', { age: growth })
: null;
const ages = [];
const discovered = formatAge(nowMs - row.discoveredTime);
if (row.discoveredTime != null && discovered)
@@ -167,7 +209,6 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
);
if (situation.length) details.push(situation.join(' · '));
if (response.length) details.push(response.join(' · '));
if (lastGrowth) details.push(lastGrowth);
if (ages.length) details.push(ages.join(' · '));
if (link) details.push(t('InciWeb ↗ · click card to open'));
@@ -175,7 +216,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
name: row.name || t('Unnamed incident'),
});
return {
id: `fire-perimeter-card:${row.id}`,
id: `fire-perimeter-card:${row.stableId}`,
// `selected` picks the paint lane and collision protection; an explicit
// paintLane would override it in the host's lane resolver.
selected: true,
+10 -32
View File
@@ -1,7 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildIncidentCard } from './cards.js';
import { perimeterAnchorDegrees } from './records.js';
import { perimeterAnchorDegrees, buildIncidentCard } from './cards.js';
const square = [
[-108.2, 35.0],
@@ -94,7 +93,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
const now = 1758000000000;
const card = buildIncidentCard(
{
id: '2026-NMGNF-000123',
stableId: '2026-NMGNF-000123',
name: 'Frijoles',
acres: 15956.4,
containedPct: 74,
@@ -102,7 +101,6 @@ test('a full incident row renders name, size, containment, and ages', () => {
category: 'WF',
discoveredTime: now - 36 * 3600000,
updatedTime: now - 2 * 3600000,
lastGrowthTime: now - 5 * 3600000,
cause: 'Natural',
behavior: 'Active',
personnel: 380,
@@ -118,7 +116,6 @@ test('a full incident row renders name, size, containment, and ages', () => {
'15,956 ac · 74% contained · US-NM',
'Natural cause · Active · Type 3 Incident',
'380 personnel · Sandoval County · $4.2M to date',
'last growth 5h ago',
'discovered 1d ago · updated 2h ago',
]);
assert.equal(card.selected, true);
@@ -128,7 +125,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
test('missing attributes degrade to available facts instead of placeholders', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: null,
acres: null,
containedPct: null,
@@ -152,7 +149,7 @@ test('missing attributes degrade to available facts instead of placeholders', ()
test('a known InciWeb page adds a link line to the card', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Timber',
acres: 25426,
containedPct: 44,
@@ -180,7 +177,7 @@ test('a known InciWeb page adds a link line to the card', () => {
test('the selected card claims the selected paint lane, not the ambient lane', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Any',
acres: 1,
containedPct: 1,
@@ -207,7 +204,7 @@ test('the selected card claims the selected paint lane, not the ambient lane', (
test('costs near a unit boundary promote to the larger unit', () => {
const base = {
id: 'x',
stableId: 'x',
name: 'Any',
acres: null,
containedPct: null,
@@ -235,7 +232,7 @@ test('costs near a unit boundary promote to the larger unit', () => {
test('a complex member names its complex on the card', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Crosswhite',
acres: 342923,
containedPct: 99,
@@ -259,7 +256,7 @@ test('a complex member names its complex on the card', () => {
test('a card without a link is not interactive', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Crosswhite',
acres: 1,
containedPct: 1,
@@ -282,7 +279,7 @@ test('a card without a link is not interactive', () => {
test('partial incident details render only the facts that exist', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Whiskey',
acres: 542,
containedPct: 48,
@@ -308,7 +305,7 @@ test('partial incident details render only the facts that exist', () => {
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
const row = {
id: 'x',
stableId: 'x',
name: 'Grey',
acres: 0.25,
containedPct: null,
@@ -336,22 +333,3 @@ test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () =>
'1 ac · containment unknown · US-WA',
);
});
test('ages count from the moment shown, not from the clock', () => {
const at = Date.UTC(2025, 7, 1, 12);
const card = buildIncidentCard(
{
id: 'past',
name: 'Past',
containedPct: 10,
discoveredTime: at - 3 * 86400000,
updatedTime: at - 30 * 60000,
lastGrowthTime: at - 7 * 3600000,
},
at,
);
assert.deepEqual(card.details.slice(-2), [
'last growth 7h ago',
'discovered 3d ago · updated 30m ago',
]);
});
+106 -172
View File
@@ -1,6 +1,12 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
import { hexColor } from '../../render/color.js';
import {
PERIMETER_OVERLAY_SOURCE_ID,
perimeterAnchorDegrees,
buildIncidentCard,
containmentAccent,
} from './cards.js';
import {
findInciwebLink,
inciwebNodeId,
@@ -8,72 +14,21 @@ import {
} from './inciweb.js';
import { msg, t } from '../../i18n/index.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
export {
normalizeFirePerimeterSnapshot,
firePerimeterSnapshot,
perimeterAnchorDegrees,
} from './records.js';
export { normalizeFirePerimeterSnapshot } from './records.js';
export { createWfigsPerimeterSource } from './source.js';
export * from './cards.js';
export * from './inciweb.js';
const HOUR_MS = 3600000;
/**
* Piece colours by age, newest first, as WorldFX draws fire growth: the
* upper bound of each age and its colour (renderer RGB, 0–1). A piece of
* unknown birth is drawn as the oldest.
* Fill/line colour for a perimeter by containment progress (same ramp as the
* card accent), as a renderer colour `[r, g, b, a]`.
*/
export const PERIMETER_AGE_BANDS = Object.freeze(
[
{ upToMs: 6 * HOUR_MS, rgb: [1, 0.78, 0.18], label: msg('New in 6 hours') },
{ upToMs: 24 * HOUR_MS, rgb: [1, 0.45, 0.05], label: msg('6–24 hours') },
{ upToMs: 72 * HOUR_MS, rgb: [0.85, 0.16, 0.05], label: msg('1–3 days') },
{
upToMs: Infinity,
rgb: [0.45, 0.06, 0.04],
label: msg('Older or unknown'),
},
].map((band) => Object.freeze(band)),
);
/**
* The age band of something born (or last grown) at `time`, seen at `atMs`:
* an index into PERIMETER_AGE_BANDS.
*/
export function perimeterAgeBand(time, atMs) {
const last = PERIMETER_AGE_BANDS.length - 1;
if (!Number.isFinite(time)) return last;
const age = atMs - time;
const index = PERIMETER_AGE_BANDS.findIndex(({ upToMs }) => age < upToMs);
return index < 0 ? last : index;
export function containmentColor(containedPct) {
return hexColor(containmentAccent(containedPct));
}
const FILL_ALPHA = 0.35;
const LINE_ALPHA = 0.9;
const LINE_WIDTH_PX = 2;
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
const cssColor = (rgb) =>
`#${rgb
.map((v) =>
Math.round(v * 255)
.toString(16)
.padStart(2, '0'),
)
.join('')}`;
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
@@ -97,12 +52,8 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
/**
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
*
* The source's `getSnapshot({signal})` answers fires and the pieces of
* their burned area (records.js `firePerimeterSnapshot`). Each piece is a
* ground-clamped fill in one renderer draw set, coloured by its age at the
* snapshot's `at` (else now), and its outline draped lines in another
* (`drawOf(viewer)`), made at `init`. When to read again (a timeline, the
* camera) is the host's call, through the manager's `refreshLayer`.
* 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.
*/
@@ -120,16 +71,12 @@ export function createFirePerimetersLayer({
let _viewer = null;
let _request = null;
let _linkRequest = null;
// What the sets show: the snapshot revision and each piece's age band.
let _drawnKey = null;
let _snapshotSignature = 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 proxy's last snapshot, served while WFIGS is unreachable.
let _stale = false;
let _lastError = null;
@@ -141,11 +88,8 @@ export function createFirePerimetersLayer({
let _inciwebIndex = [];
let _indexFetchedAt = 0;
let _indexFetchInFlight = false;
/** The snapshot's fires by id, each with its card anchor. */
let _fireById = new Map();
/** `<set id>\n<item id>` → the fire that item belongs to. */
const _fireByItem = new Map();
const shownAt = () => _at ?? Date.now();
/** @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();
@@ -203,7 +147,7 @@ export function createFirePerimetersLayer({
discoveredTime: row.discoveredTime,
}),
);
if (_selectedId === row.id) publishSelectedCard();
if (_selectedId === row.stableId) publishSelectedCard();
})
.catch(() => {
// Fail closed without caching: no link now, retry on reselection.
@@ -215,7 +159,7 @@ export function createFirePerimetersLayer({
function publishSelectedCard() {
if (!canSelect()) return;
const row = _selectedId ? _fireById.get(_selectedId) : null;
const row = _selectedId ? _rowById.get(_selectedId) : null;
if (!row) {
_selectedId = null;
_selectedLink = null;
@@ -232,7 +176,7 @@ export function createFirePerimetersLayer({
_selectedLink =
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
const card = {
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
position: fromDegrees(row.anchor.lon, row.anchor.lat),
};
if (!openExternal) card.interactive = false;
@@ -258,8 +202,10 @@ export function createFirePerimetersLayer({
*/
function pickedIncidentId(hit) {
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
return incidentId != null && _fireById.has(incidentId) ? incidentId : 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() {
@@ -308,56 +254,6 @@ export function createFirePerimetersLayer({
});
}
/** Draw `pieces`, each in the colour of its age band. */
function drawPieces(pieces, bands) {
abortLinkVerification();
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 { rgb } = 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, 4)))
continue;
nextFills.push({
id: itemId(piece.fireId, ''),
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: withAlpha(rgb, 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: withAlpha(rgb, 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;
@@ -429,45 +325,80 @@ export function createFirePerimetersLayer({
_request = request;
refreshInciwebIndex(request.signal);
try {
const snapshot = await source.getSnapshot({ signal: request.signal });
// 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;
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
throw new Error(msg('Malformed perimeter snapshot'));
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();
_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),
// 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)),
);
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;
if (drawKey === null || drawKey !== _drawnKey) {
drawPieces(pieces, bands);
_drawnKey = drawKey;
if (signature === _snapshotSignature) {
if (_selectedId) publishSelectedCard();
_lastUpdate = updatedAt;
_lastError = null;
return true;
}
// Refresh (or drop) the selected incident's card against the new
// snapshot: its ages move with `at` even when nothing is redrawn.
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 = fires.size;
_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)
@@ -487,11 +418,8 @@ export function createFirePerimetersLayer({
_request = null;
removeClickHandler();
clearSelection();
_fireById = new Map();
_fireByItem.clear();
_drawnKey = null;
_at = null;
_note = null;
_rowById.clear();
_snapshotSignature = null;
_inciwebIndex = [];
_indexFetchedAt = 0;
_linkVerdicts.clear();
@@ -514,11 +442,11 @@ export function createFirePerimetersLayer({
? Math.max(1, Math.floor(maxCount))
: 2000;
const result = [];
for (const fire of _fireById.values()) {
for (const row of _rowById.values()) {
if (result.length >= limit) break;
const { anchor, id, ...facts } = fire;
const { anchor, stableId, ...facts } = row;
result.push({
id,
id: stableId,
...facts,
lat: anchor.lat,
lon: anchor.lon,
@@ -528,21 +456,27 @@ export function createFirePerimetersLayer({
},
getRowControls() {
const atMs = shownAt();
const counts = PERIMETER_AGE_BANDS.map(() => 0);
for (const fire of _fireById.values())
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
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: PERIMETER_AGE_BANDS.map((band, index) => ({
label: t(band.label),
color: cssColor(band.rgb),
count: counts[index],
legend: bands.map((band, index) => ({
...band,
count: [..._rowById.values()].filter(
(row) => containmentAccent(row.containedPct) === band.color,
).length,
...(index === 0
? { blurb: t('Colour shows how long ago each area was mapped.') }
? {
blurb: t(
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
),
}
: {}),
})),
...(_note ? { info: t(_note) } : {}),
};
},
+106 -262
View File
@@ -1,10 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createFirePerimetersLayer,
perimeterAnchorDegrees,
PERIMETER_AGE_BANDS,
} from './index.js';
import { createFirePerimetersLayer } from './index.js';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -101,9 +97,8 @@ const ring = [
[-108.0, 35.3],
[-108.1, 35.2],
];
const HOUR = 3600000;
const fire = {
id: '2026-NMGNF-000123',
const row = {
stableId: '2026-NMGNF-000123',
name: 'Fixture Fire',
acres: 512.5,
containedPct: 40,
@@ -118,107 +113,58 @@ const fire = {
costToDate: 4200000,
complexity: 'Type 3 Incident',
complexName: 'ROWE CREEK COMPLEX',
lastGrowthTime: 1757950000000,
anchor: perimeterAnchorDegrees([[ring]]),
polygons: [[ring]],
};
/** One piece of `fireId`'s area: one polygon, outlined by its rings. */
const pieceOf = (fireId, { rings = [ring], born = null, ...rest } = {}) => ({
fireId,
born,
polygons: [rings],
outline: rings,
...rest,
});
/** A source snapshot of `fires`, one piece each unless `pieces` is given. */
function snap(fires, { pieces, ...rest } = {}) {
return {
at: null,
fetchedAt: null,
stale: false,
revision: fires
.map(({ id, updatedTime }) => `${id}@${updatedTime}`)
.sort()
.join('|'),
note: null,
fires,
pieces: pieces ?? fires.map(({ id }) => pieceOf(id)),
...rest,
};
}
const rgba = (band, alpha) => [...PERIMETER_AGE_BANDS[band].rgb, alpha];
test('each piece draws as a clamped fill and its outline as draped lines, coloured by age', async () => {
test('each perimeter polygon draws as one clamped fill with its draped fire line', async () => {
const hole = [
[-108.08, 35.22],
[-108.02, 35.22],
[-108.02, 35.25],
[-108.08, 35.22],
];
const at = Date.UTC(2025, 7, 1, 12);
const other = { ...fire, id: 'other', containedPct: 100 };
const h = harness({
getSnapshot: async () =>
snap([fire, other], {
at,
pieces: [
pieceOf(fire.id, { rings: [ring, hole], born: at - HOUR }),
// A piece cut from a larger area: no line along the cut.
{
fireId: 'other',
born: at - 30 * HOUR,
polygons: [[ring]],
outline: [ring.slice(0, 3)],
},
pieceOf('other', { born: null }),
],
}),
getSnapshot: async () => [
{ ...row, polygons: [[ring, hole]] },
{
...row,
stableId: 'other',
containedPct: 100,
polygons: [[ring], [ring]],
},
],
});
assert.equal(h.fills().show, true);
assert.equal(h.lines().show, true);
assert.equal(await h.layer.update(h.viewer), true);
assert.deepEqual(
[...h.fills().items.keys()],
[
'fire-perimeter:2026-NMGNF-000123:0',
'fire-perimeter:other:0',
'fire-perimeter:other:1',
],
);
assert.deepEqual(
[...h.lines().items.keys()],
[
'fire-perimeter:2026-NMGNF-000123:line:0',
'fire-perimeter:2026-NMGNF-000123:line:1',
'fire-perimeter:other:line:0',
'fire-perimeter:other:line:1',
],
);
const fill = h.fills().items.get('fire-perimeter:2026-NMGNF-000123:0');
const ids = [
'fire-perimeter:2026-NMGNF-000123:0',
'fire-perimeter:other:0',
'fire-perimeter:other:1',
];
assert.deepEqual([...h.fills().items.keys()], ids);
assert.deepEqual([...h.lines().items.keys()], ids);
const fill = h.fills().items.get(ids[0]);
assert.equal(fill.height, 'clampGround');
assert.deepEqual(fill.fill, rgba(0, 0.35));
assert.deepEqual(fill.fill, [1, 122 / 255, 0, 0.25]);
assert.equal(fill.geometry.kind, 'polygon');
assert.equal(fill.geometry.rings.length, 2, 'the hole stays');
assert.deepEqual(fill.geometry.rings[0][1], { lon: -108.0, lat: 35.2 });
const line = h.lines().items.get('fire-perimeter:2026-NMGNF-000123:line:1');
const line = h.lines().items.get(ids[0]);
assert.equal(line.mode, 'draped');
assert.equal(line.widthPx, 2);
assert.deepEqual(line.style, { kind: 'solid', color: rgba(0, 0.9) });
assert.equal(line.positions.length, hole.length, 'the hole is outlined too');
assert.deepEqual(line.style, {
kind: 'solid',
color: [1, 122 / 255, 0, 0.9],
});
assert.equal(line.positions.length, ring.length, 'the exterior ring only');
assert.ok(Number.isFinite(line.positions[0].x), 'lines take ECEF');
assert.equal(
h.lines().items.get('fire-perimeter:other:line:0').positions.length,
3,
'the outline as given, not the polygon',
);
// Aged at the snapshot's moment, not now: 30 h is 1–3 days; unknown is oldest.
assert.deepEqual(
h.fills().items.get('fire-perimeter:other:0').fill,
rgba(2, 0.35),
);
assert.deepEqual(
h.fills().items.get('fire-perimeter:other:1').fill,
rgba(3, 0.35),
);
assert.deepEqual(h.fills().items.get(ids[1]).fill, [
139 / 255,
195 / 255,
74 / 255,
0.25,
]);
assert.equal(h.layer.getStats().count, 2);
h.layer.disable();
assert.equal(h.fills().show, false);
@@ -228,23 +174,10 @@ test('each piece draws as a clamped fill and its outline as draped lines, colour
assert.equal(h.lines(), undefined);
});
test('a piece of a fire the snapshot does not list is dropped', async () => {
const h = harness({
getSnapshot: async () =>
snap([fire], { pieces: [pieceOf(fire.id), pieceOf('ghost')] }),
});
await h.layer.update();
assert.deepEqual(
[...h.fills().items.keys()],
['fire-perimeter:2026-NMGNF-000123:0'],
);
h.layer.destroy();
});
test("a pick selects only an item of the layer's own sets", async () => {
let pickResult = null;
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{ pick: () => pickResult },
);
await h.layer.update(h.viewer);
@@ -255,10 +188,7 @@ test("a pick selects only an item of the layer's own sets", async () => {
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
// The fire line picks as its perimeter, as the one entity used to.
pickResult = {
id: {
set: h.lines().spec.id,
id: 'fire-perimeter:2026-NMGNF-000123:line:0',
},
id: { set: h.lines().spec.id, id: 'fire-perimeter:2026-NMGNF-000123:0' },
};
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(h.overlay.entries.get('fire-perimeters').length, 1);
@@ -279,7 +209,7 @@ test('late refresh cannot publish after disable or destroy', async () => {
h.layer[action](h.viewer);
assert.equal(signal.aborted, true);
if (action === 'disable') h.layer.enable(h.viewer);
resolve(snap([fire]));
resolve([row]);
assert.equal(await pending, false);
assert.equal(h.layer.getStats().count, 0);
h.layer.destroy(h.viewer);
@@ -289,7 +219,7 @@ test('late refresh cannot publish after disable or destroy', async () => {
test('clicking a perimeter publishes its incident card; empty space clears it', async () => {
let pickResult = null;
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{
pick: () => pickResult,
},
@@ -329,7 +259,7 @@ test("another layer's overlay on top keeps a click off the area", async () => {
let pickResult = null;
let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{
pick: () => pickResult,
// Unfiltered: the topmost entry of any source.
@@ -362,7 +292,7 @@ test("another layer's overlay on top keeps a click off the area", async () => {
test('disable removes the click handler, pick ownership, and any card', async () => {
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
);
await h.layer.update(h.viewer);
@@ -374,7 +304,7 @@ test('disable removes the click handler, pick ownership, and any card', async ()
});
test('a refresh that drops the selected incident also drops its card', async () => {
let rows = snap([fire]);
let rows = [row];
const h = harness(
{ getSnapshot: async () => rows },
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
@@ -382,61 +312,11 @@ test('a refresh that drops the selected incident also drops its card', async ()
await h.layer.update(h.viewer);
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(h.overlay.entries.get('fire-perimeters').length, 1);
rows = snap([{ ...fire, id: 'different' }]);
rows = [{ ...row, stableId: 'different' }];
await h.layer.update(h.viewer);
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
});
test('a selected fire keeps its card while listed, even with no pieces left', async () => {
let current = snap([fire]);
const h = harness(
{ getSnapshot: async () => current },
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
);
await h.layer.update();
h.clicks.handler({ position: { x: 10, y: 10 } });
current = snap([fire], { pieces: [] });
await h.layer.update();
assert.equal(h.fills().items.size, 0);
const [card] = h.overlay.entries.get('fire-perimeters');
assert.equal(card.id, 'fire-perimeter-card:2026-NMGNF-000123');
assert.equal(h.layer.getStats().count, 1, 'a fire without pieces counts');
assert.equal(
h.layer.getRowControls().legend.reduce((sum, { count }) => sum + count, 0),
1,
);
h.layer.destroy();
});
test('the card ages from the moment the snapshot shows', async () => {
const at = Date.UTC(2025, 7, 1, 12);
const h = harness(
{
getSnapshot: async () =>
snap(
[
{
...fire,
discoveredTime: at - 50 * HOUR,
updatedTime: at - 2 * HOUR,
lastGrowthTime: at - 5 * HOUR,
},
],
{ at },
),
},
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
);
await h.layer.update();
h.clicks.handler({ position: { x: 10, y: 10 } });
const [card] = h.overlay.entries.get('fire-perimeters');
assert.deepEqual(card.details.slice(-2), [
'last growth 5h ago',
'discovered 2d ago · updated 2h ago',
]);
h.layer.destroy();
});
test('a matched incident card carries the InciWeb line and click-through', async () => {
const inciwebIndex = [
{
@@ -448,7 +328,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
let cardHitResult = null;
let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => snap([{ ...fire, name: 'Fixture' }]) },
{ getSnapshot: async () => [{ ...row, name: 'Fixture' }] },
{
pick: () => null,
inciwebIndex,
@@ -491,7 +371,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
test('a click on a mission label over the incident card never opens its InciWeb page, and keeps the card open', async () => {
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [
@@ -529,7 +409,7 @@ test('a click on a mission label over the incident card never opens its InciWeb
test('an unmatched incident renders no InciWeb line and card clicks stay inert', async () => {
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [],
@@ -552,7 +432,7 @@ test('an unmatched incident renders no InciWeb line and card clicks stay inert',
test('a complex member resolves to its complex page from the catalog', async () => {
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [
@@ -593,7 +473,7 @@ test('a stale or unverifiable publication yields no link', async () => {
},
]) {
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ getSnapshot: async () => [row] },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex,
@@ -615,20 +495,17 @@ test('a stale or unverifiable publication yields no link', async () => {
});
test('a hanging InciWeb index fetch never blocks the perimeter refresh', async (t) => {
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ inciwebIndex: null },
);
const h = harness({ getSnapshot: async () => [row] }, { inciwebIndex: null });
// Replace the index source with one that never resolves.
h.layer.destroy(h.viewer);
const hanging = harness({ getSnapshot: async () => snap([fire]) });
const hanging = harness({ getSnapshot: async () => [row] });
hanging.layer.destroy(hanging.viewer);
const viewer = { scene: { pick: () => null } };
bindFakeDraw(viewer);
const input = fakeInput(viewer);
t.after(() => input.destroy());
const layer = createFirePerimetersLayer({
source: { getSnapshot: async () => snap([fire]) },
source: { getSnapshot: async () => [row] },
overlayHost: {
setEntries() {},
setVisible() {},
@@ -660,9 +537,9 @@ test('a hanging InciWeb index fetch never blocks the perimeter refresh', async (
});
test('an InciWeb outage never breaks the perimeter refresh', async (t) => {
const h = harness({ getSnapshot: async () => snap([fire]) });
const h = harness({ getSnapshot: async () => [row] });
const failing = createFirePerimetersLayer({
source: { getSnapshot: async () => snap([fire]) },
source: { getSnapshot: async () => [row] },
overlayHost: {
setEntries() {},
setVisible() {},
@@ -700,7 +577,7 @@ test('an InciWeb outage never breaks the perimeter refresh', async (t) => {
});
test('analyst records expose incident facts without geometry payloads', async () => {
const h = harness({ getSnapshot: async () => snap([fire]) });
const h = harness({ getSnapshot: async () => [row] });
await h.layer.update(h.viewer);
const records = h.layer.getAnalystRecords();
assert.equal(records.length, 1);
@@ -714,132 +591,95 @@ test('analyst records expose incident facts without geometry payloads', async ()
assert.equal(records[0].county, 'Sandoval');
assert.equal(records[0].costToDate, 4200000);
assert.equal(records[0].complexity, 'Type 3 Incident');
assert.equal(records[0].lastGrowthTime, fire.lastGrowthTime);
assert.equal(records[0].id, fire.id);
// Spatial scoping in the analyst engine requires coordinates.
assert.ok(Math.abs(records[0].lat - 35.2333) < 0.01);
assert.ok(Math.abs(records[0].lon - -108.0333) < 0.01);
assert.equal('polygons' in records[0] || 'anchor' in records[0], false);
assert.equal('polygons' in records[0], false);
});
test('the layer redraws on a new revision or a change of age band, and only then', async () => {
const at = Date.UTC(2025, 7, 1, 12);
const other = { ...fire, id: 'other' };
let current = snap([fire, other], {
at,
pieces: [pieceOf(fire.id, { born: at - HOUR }), pieceOf('other')],
});
const h = harness({ getSnapshot: async () => current });
test('unchanged snapshots draw nothing again even if source ordering changes', async () => {
let rows = [row, { ...row, stableId: 'other' }];
const h = harness({ getSnapshot: async () => rows });
await h.layer.update();
const writes = () => [h.fills().writes, h.lines().writes];
assert.deepEqual(writes(), [1, 1]);
rows = [...rows].reverse();
await h.layer.update();
assert.deepEqual(writes(), [1, 1]);
// Same revision, feed reordered, facts changed, still in the same band.
current = {
...current,
at: at + 4 * HOUR,
fires: [{ ...other, containedPct: 100 }, fire],
};
await h.layer.update();
assert.deepEqual(writes(), [1, 1]);
// The new piece turns 6 h old.
current = { ...current, at: at + 6 * HOUR };
rows = rows.map((value) => ({
...value,
updatedTime: value.updatedTime + 1,
}));
await h.layer.update();
assert.deepEqual(writes(), [2, 2]);
rows = rows.map((value) => ({ ...value, containedPct: 100 }));
await h.layer.update();
assert.deepEqual(
h.fills().items.get('fire-perimeter:2026-NMGNF-000123:0').fill,
rgba(1, 0.35),
writes(),
[3, 3],
'incident facts can change without a new polygon timestamp',
);
current = { ...current, revision: 'changed' };
await h.layer.update();
assert.deepEqual(writes(), [3, 3]);
// A source without a revision is drawn every time.
current = { ...current, revision: undefined };
await h.layer.update();
await h.layer.update();
assert.deepEqual(writes(), [5, 5]);
current = snap([]);
assert.equal(h.layer.getRowControls().legend[3].count, 2);
rows = [];
await h.layer.update();
assert.equal(h.fills().items.size, 0);
assert.equal(h.lines().items.size, 0);
h.layer.destroy();
});
test('a failed read keeps the picture and reports the error', async () => {
let fail = false;
const h = harness({
getSnapshot: async () => {
if (fail) throw new Error('WFIGS HTTP 502');
return snap([fire]);
},
});
await h.layer.update();
fail = true;
assert.equal(await h.layer.update(), false);
assert.equal(h.fills().items.size, 1);
assert.equal(h.layer.getStats().error, 'WFIGS HTTP 502');
assert.equal(h.layer.getStats().count, 1);
h.layer.destroy();
});
test('a malformed snapshot is an error, not an empty map', async () => {
const h = harness({ getSnapshot: async () => [fire] });
assert.equal(await h.layer.update(), false);
assert.equal(h.layer.getStats().error, 'Malformed perimeter snapshot');
h.layer.destroy();
});
test('the legend counts fires by their last growth at the moment shown, with the source note', async () => {
const at = Date.UTC(2025, 7, 1, 12);
const ages = [0, 5.9, 6, 23.9, 24, 71.9, 72, null, -1];
test('containment legend uses the existing thresholds, colours and incident counts', async () => {
const values = [null, -1, 0, 0.5, 49.9, 50, 99.9, 100, 101];
const h = harness({
getSnapshot: async () =>
snap(
ages.map((hours, index) => ({
...fire,
id: String(index),
lastGrowthTime: hours === null ? null : at - hours * HOUR,
})),
{ at, note: 'Perimeters are simplified to about 100 m.' },
),
values.map((containedPct, index) => ({
...row,
stableId: String(index),
containedPct,
})),
});
await h.layer.update();
const controls = h.layer.getRowControls();
assert.deepEqual(controls.chips, []);
assert.deepEqual(
controls.legend.map(({ label, color, count }) => [label, color, count]),
controls.legend.map(({ color, count }) => [color, count]),
[
['New in 6 hours', '#ffc72e', 3],
['6–24 hours', '#ff730d', 2],
['1–3 days', '#d9290d', 2],
['Older or unknown', '#730f0a', 2],
['#ff3b30', 3],
['#ff7a00', 2],
['#ffb300', 2],
['#8bc34a', 2],
],
);
assert.ok(
controls.legend.every(
({ label }) => typeof label === 'string' && label.length,
),
);
assert.equal(
controls.legend[0].blurb,
'Colour shows how long ago each area was mapped.',
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
);
assert.equal(controls.info, 'Perimeters are simplified to about 100 m.');
h.layer.destroy();
assert.deepEqual(
h.layer.getRowControls().legend.map(({ count }) => count),
[0, 0, 0, 0],
);
assert.equal(h.layer.getRowControls().info, undefined);
});
for (const action of ['disable', 'destroy', 'selection']) {
test(`incident-link verification aborts on ${action} and ignores late completion`, async () => {
let finish, signal;
let pickId = `fire-perimeter:${fire.id}:0`;
let pickId = `fire-perimeter:${row.stableId}:0`;
const h = harness(
{
getSnapshot: async () =>
snap([fire, { ...fire, id: 'other', name: 'Other Fire' }]),
getSnapshot: async () => [
row,
{ ...row, stableId: 'other', name: 'Other Fire' },
],
},
{
pick: () => perimeterPick(pickId),
inciwebIndex: [
{ incident_id: '123', incident_title: fire.name, tau: 'nm' },
{ incident_id: '123', incident_title: row.name, tau: 'nm' },
],
publication: (_id, options) => {
signal = options.signal;
@@ -858,7 +698,7 @@ for (const action of ['disable', 'destroy', 'selection']) {
} else h.layer[action]();
assert.equal(signal.aborted, true);
const entries = h.overlay.entries.get('fire-perimeters');
finish({ createdMs: fire.discoveredTime, changedMs: fire.updatedTime });
finish({ createdMs: row.discoveredTime, changedMs: row.updatedTime });
await new Promise(setImmediate);
assert.equal(h.overlay.entries.get('fire-perimeters'), entries);
if (action !== 'destroy') h.layer.destroy();
@@ -867,12 +707,15 @@ for (const action of ['disable', 'destroy', 'selection']) {
test('a stale snapshot reads stale, dated by its own fetch, and a fresh one clears it', async () => {
const fetchedAt = Date.now() - 3 * 60 * 60 * 1000;
let snapshot = snap([fire], { stale: true, fetchedAt });
const h = harness({ getSnapshot: async () => snapshot });
let snapshot = { rows: [row], stale: true, fetchedAt };
const h = harness({
getSnapshot: async () => snapshot.rows,
getSnapshotDetail: async () => snapshot,
});
await h.layer.update(h.viewer);
assert.equal(h.layer.getStats().stale, true);
assert.equal(h.layer.getStats().lastUpdate, fetchedAt);
snapshot = snap([fire], { fetchedAt: Date.now() });
snapshot = { rows: [row], stale: false, fetchedAt: Date.now() };
await h.layer.update(h.viewer);
assert.equal(h.layer.getStats().stale, false);
assert.ok(h.layer.getStats().lastUpdate > fetchedAt);
@@ -881,9 +724,10 @@ test('a stale snapshot reads stale, dated by its own fetch, and a fresh one clea
test('a failed refresh after a stale snapshot reads as the failure, not stale', async () => {
let fail = false;
const h = harness({
getSnapshot: async () => {
getSnapshot: async () => [row],
getSnapshotDetail: async () => {
if (fail) throw new Error('WFIGS HTTP 502');
return snap([fire], { stale: true, fetchedAt: Date.now() - 60_000 });
return { rows: [row], stale: true, fetchedAt: Date.now() - 60_000 };
},
});
await h.layer.update(h.viewer);
-113
View File
@@ -1,12 +1,3 @@
/**
* WFIGS perimeters: the proxy's rows (normalizeFirePerimeterSnapshot) and
* the snapshot the layer draws (firePerimeterSnapshot).
*
* A portable export (package.json): no i18n here.
*/
const msg = (text) => text;
/**
* Normalize a WFIGS feed, skipping individually invalid features.
* Only a payload that is not a feature collection at all rejects the whole
@@ -89,7 +80,6 @@ export function normalizeFirePerimeterSnapshot(geojson) {
: null,
discoveredTime: finiteOrNull(properties.attr_FireDiscoveryDateTime),
updatedTime: finiteOrNull(properties.poly_DateCurrent),
polygonTime: finiteOrNull(properties.poly_PolygonDateTime),
cause: textOrNull(properties.attr_FireCause),
behavior: textOrNull(properties.attr_FireBehaviorGeneral),
personnel: finiteOrNull(properties.attr_TotalIncidentPersonnel),
@@ -102,106 +92,3 @@ export function normalizeFirePerimeterSnapshot(geojson) {
}
return rows;
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/** A clock this far ahead of ours is still taken as now, not as the future. */
const CLOCK_SKEW_MS = 10 * 60 * 1000;
/**
* The snapshot the Fire Perimeters layer draws, from the proxy's rows.
*
* WFIGS keeps one perimeter per fire, so each of its polygons is one piece,
* born when the perimeter was mapped (`poly_PolygonDateTime`, else the
* record's last edit `poly_DateCurrent`). A time in the future is unknown.
* @param {object[]} rows - normalizeFirePerimeterSnapshot rows.
* @param {{fetchedAt?: number|null, stale?: boolean, now?: number}} [options]
* @returns {{at: null, fetchedAt: number|null, stale: boolean,
* revision: string, note: string, fires: object[], pieces: object[]}}
*/
export function firePerimeterSnapshot(
rows,
{ fetchedAt = null, stale = false, now = Date.now() } = {},
) {
const fires = [];
const pieces = [];
const versions = [];
for (const row of rows) {
const { stableId, polygons, polygonTime, ...facts } = row;
if (typeof stableId !== 'string' || !Array.isArray(polygons)) continue;
if (!polygons.length) continue;
const mapped = polygonTime ?? facts.updatedTime;
const grown =
Number.isFinite(mapped) && mapped <= now + CLOCK_SKEW_MS ? mapped : null;
fires.push({
...facts,
id: stableId,
lastGrowthTime: grown,
anchor: perimeterAnchorDegrees(polygons),
});
for (const rings of polygons)
pieces.push({
fireId: stableId,
born: grown,
polygons: [rings],
outline: rings,
});
versions.push(`${stableId}@${facts.updatedTime ?? ''}`);
}
return {
at: null,
fetchedAt: Number.isFinite(fetchedAt) ? fetchedAt : null,
stale: stale === true,
revision: versions.sort().join('|'),
note: msg('Perimeters are simplified to about 100 m.'),
fires,
pieces,
};
}
+1 -123
View File
@@ -1,9 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
normalizeFirePerimeterSnapshot,
firePerimeterSnapshot,
} from './records.js';
import { normalizeFirePerimeterSnapshot } from './records.js';
const ring = [
[-108.1, 35.2],
@@ -25,7 +22,6 @@ function feature(overrides = {}) {
attr_IncidentTypeCategory: 'WF',
attr_FireDiscoveryDateTime: 1757900000000,
poly_DateCurrent: 1757950000000,
poly_PolygonDateTime: 1757940000000,
attr_FireCause: 'Natural',
attr_FireBehaviorGeneral: 'Active',
attr_TotalIncidentPersonnel: 380,
@@ -63,7 +59,6 @@ test('a valid snapshot yields one row per incident with polygons preserved', ()
category: 'WF',
discoveredTime: 1757900000000,
updatedTime: 1757950000000,
polygonTime: 1757940000000,
cause: 'Natural',
behavior: 'Active',
personnel: 380,
@@ -95,7 +90,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
attr_IncidentTypeCategory: null,
attr_FireDiscoveryDateTime: null,
poly_DateCurrent: null,
poly_PolygonDateTime: null,
attr_FireCause: null,
attr_FireBehaviorGeneral: null,
attr_TotalIncidentPersonnel: null,
@@ -116,7 +110,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
category: rows[0].category,
discoveredTime: rows[0].discoveredTime,
updatedTime: rows[0].updatedTime,
polygonTime: rows[0].polygonTime,
cause: rows[0].cause,
behavior: rows[0].behavior,
personnel: rows[0].personnel,
@@ -133,7 +126,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
category: null,
discoveredTime: null,
updatedTime: null,
polygonTime: null,
cause: null,
behavior: null,
personnel: null,
@@ -207,117 +199,3 @@ test('a perimeter with no rings is skipped rather than rendered empty', () => {
assert.equal(rows.length, 1);
assert.equal(rows[0].stableId, 'other');
});
const NOW = 1758000000000;
const rowsOf = (...features) => normalizeFirePerimeterSnapshot({ features });
// feature() replaces all properties with the overrides' own: keep the rest.
const fixture = (id, properties) =>
feature({ id, properties: { ...feature().properties, ...properties } });
test('each WFIGS polygon becomes one piece of its fire, born when it was mapped', () => {
const hole = [
[-108.08, 35.22],
[-108.02, 35.22],
[-108.02, 35.25],
[-108.08, 35.22],
];
const snapshot = firePerimeterSnapshot(
rowsOf(
feature({
geometry: { type: 'MultiPolygon', coordinates: [[ring, hole], [ring]] },
}),
),
{ fetchedAt: NOW - 1000, now: NOW },
);
assert.equal(snapshot.at, null);
assert.equal(snapshot.stale, false);
assert.equal(snapshot.fetchedAt, NOW - 1000);
assert.equal(snapshot.note, 'Perimeters are simplified to about 100 m.');
assert.equal(snapshot.fires.length, 1);
const [fire] = snapshot.fires;
assert.equal(fire.id, '2026-NMGNF-000123');
assert.equal(fire.lastGrowthTime, 1757940000000);
assert.equal(fire.containedPct, 40);
assert.equal('stableId' in fire || 'polygons' in fire, false);
assert.ok(Math.abs(fire.anchor.lat - 35.2333) < 0.01);
assert.deepEqual(
snapshot.pieces.map(({ fireId, born, polygons, outline }) => [
fireId,
born,
polygons,
outline,
]),
[
['2026-NMGNF-000123', 1757940000000, [[ring, hole]], [ring, hole]],
['2026-NMGNF-000123', 1757940000000, [[ring]], [ring]],
],
'the outline is every ring, holes included',
);
});
test('a perimeter without its mapping time falls back to the last edit; a future time is unknown', () => {
const [fallback, future, futureEdit, none] = firePerimeterSnapshot(
rowsOf(
fixture(1, { poly_PolygonDateTime: null }),
fixture(2, {
attr_UniqueFireIdentifier: 'future',
poly_PolygonDateTime: NOW + 3600000,
}),
fixture(3, {
attr_UniqueFireIdentifier: 'future-edit',
poly_PolygonDateTime: null,
poly_DateCurrent: NOW + 3600000,
}),
fixture(4, {
attr_UniqueFireIdentifier: 'none',
poly_PolygonDateTime: null,
poly_DateCurrent: null,
}),
),
{ now: NOW },
).fires;
assert.equal(fallback.lastGrowthTime, 1757950000000);
assert.equal(future.lastGrowthTime, null);
assert.equal(futureEdit.lastGrowthTime, null);
assert.equal(none.lastGrowthTime, null);
// A clock a few minutes ahead of ours is not the future.
const skewed = firePerimeterSnapshot(
rowsOf(fixture(1, { poly_PolygonDateTime: NOW + 60000 })),
{ now: NOW },
);
assert.equal(skewed.fires[0].lastGrowthTime, NOW + 60000);
assert.equal(skewed.pieces[0].born, NOW + 60000);
});
test('the revision follows fire ids and update times, not feed order', () => {
const a = feature();
const b = fixture(2, { attr_UniqueFireIdentifier: 'b' });
const revision = (...features) =>
firePerimeterSnapshot(rowsOf(...features), { now: NOW }).revision;
assert.equal(revision(a, b), revision(b, a));
assert.notEqual(
revision(a, b),
revision(
a,
fixture(2, { attr_UniqueFireIdentifier: 'b', poly_DateCurrent: 1 }),
),
);
assert.notEqual(revision(a, b), revision(a));
});
test('the snapshot carries staleness and skips rows it cannot place', () => {
const snapshot = firePerimeterSnapshot(
[
{ stableId: 'empty', polygons: [] },
{ polygons: [[ring]] },
...rowsOf(feature()),
],
{ stale: true, fetchedAt: 'yesterday', now: NOW },
);
assert.equal(snapshot.stale, true);
assert.equal(snapshot.fetchedAt, null);
assert.deepEqual(
snapshot.fires.map(({ id }) => id),
['2026-NMGNF-000123'],
);
});
+29 -25
View File
@@ -1,38 +1,42 @@
import { readResponseJsonCapped } from '../../sources/httpBody.js';
import { firePerimeterSnapshot } from './records.js';
// A portable export (package.json): no i18n here. Failures stay English data;
// the Layers panel shows them translated.
const msg = (text) => text;
/** Request a snapshot through the bounded, same-origin WFIGS proxy. */
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
export function createWfigsPerimeterSource({
fetchImpl = (...args) => globalThis.fetch(...args),
now = () => Date.now(),
} = {}) {
/**
* The rows with how fresh they are: the proxy answers from its last
* snapshot, marked stale, while WFIGS is unreachable.
* @returns {Promise<{rows: object[], stale: boolean, fetchedAt: number|null}>}
*/
async function getSnapshotDetail({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/fire-perimeters', { signal });
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
80 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
if (!Array.isArray(payload?.rows))
throw new Error(msg('Malformed perimeter snapshot'));
return {
rows: payload.rows,
stale: payload.stale === true,
fetchedAt: Number.isFinite(payload.fetchedAt) ? payload.fetchedAt : null,
};
}
return {
/**
* Current perimeters as fires and their pieces (firePerimeterSnapshot).
* The proxy answers from its last snapshot, marked stale, while WFIGS is
* unreachable.
*/
async getSnapshot({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/fire-perimeters', { signal });
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
80 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
if (!Array.isArray(payload?.rows))
throw new Error(msg('Malformed perimeter snapshot'));
return firePerimeterSnapshot(payload.rows, {
fetchedAt: payload.fetchedAt,
stale: payload.stale === true,
now: now(),
});
/** The perimeter rows (see getSnapshotDetail for staleness). */
async getSnapshot(options = {}) {
return (await getSnapshotDetail(options)).rows;
},
getSnapshotDetail,
};
}
+12 -14
View File
@@ -20,7 +20,7 @@ const validPayload = {
],
};
test('a successful response yields the snapshot of fires and pieces', async () => {
test('a successful response yields normalized perimeter rows', async () => {
let requested;
const source = createWfigsPerimeterSource({
fetchImpl: async (url) => {
@@ -30,13 +30,9 @@ test('a successful response yields the snapshot of fires and pieces', async () =
});
},
});
const snapshot = await source.getSnapshot();
assert.deepEqual(
snapshot.fires.map((fire) => fire.id),
['2026-NMGNF-000123'],
);
assert.deepEqual(snapshot.pieces[0].polygons, [[ring]]);
assert.equal(snapshot.at, null);
const rows = await source.getSnapshot();
assert.equal(rows.length, 1);
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
assert.equal(requested, '/api/fire-perimeters');
});
@@ -164,20 +160,22 @@ test('a failed refresh serves the last snapshot marked stale for a day, then ref
assert.equal((await ask()).status, 502, 'a day-old snapshot is not served');
});
test('the snapshot carries the proxy staleness and fetch time', async () => {
test('the snapshot detail carries the proxy staleness and fetch time', async () => {
const fetchedAt = Date.UTC(2026, 9, 25, 12);
const source = createWfigsPerimeterSource({
fetchImpl: async () => Response.json({ rows: [], stale: true, fetchedAt }),
});
const snapshot = await source.getSnapshot();
assert.equal(snapshot.stale, true);
assert.equal(snapshot.fetchedAt, fetchedAt);
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
assert.deepEqual(await source.getSnapshotDetail(), {
rows: [],
stale: true,
fetchedAt,
});
assert.deepEqual(await source.getSnapshot(), []);
});
test('getSnapshot works when taken off its source object', async () => {
const { getSnapshot } = createWfigsPerimeterSource({
fetchImpl: async () => Response.json({ rows: [] }),
});
assert.deepEqual((await getSnapshot()).fires, []);
assert.deepEqual(await getSnapshot(), []);
});
+51 -3
View File
@@ -21,6 +21,11 @@ import { ISS_NORAD, TRACKED_ORBIT_COLOR } from './policy.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import {
clearFocusTarget,
getFocusTarget,
publishFocusTargetAt,
} from '../../data/focusDeemphasis.js';
const COMPANION = 25545;
const GPS = 32711;
@@ -70,7 +75,14 @@ function fakeFollowCamera() {
camera.flightsCancelled += 1;
},
flyTo() {},
pose: () => ({ lon: 0, lat: 0, height: 2e7, heading: 0, pitch: -1.57 }),
pose: () => ({
lon: 0,
lat: 0,
height: 2e7,
heading: 0,
pitch: -1.57,
position: { x: 2.6378e7, y: 0, z: 0 },
}),
on(event, cb) {
if (event !== 'followChanged') return () => {};
listeners.add(cb);
@@ -135,7 +147,13 @@ const SENSORS = indexImagingSensors({
],
});
async function fixture(t) {
/**
* @param {object} t The test context.
* @param {{realFocus?: boolean}} [options] `realFocus` publishes through the
* shared focus rectangle, with a query port that projects every point to
* the screen centre.
*/
async function fixture(t, { realFocus = false } = {}) {
const source = {
async readGroup(group) {
const text = GROUP_TEXT[group] || '';
@@ -165,6 +183,9 @@ async function fixture(t) {
getFocusTarget: () => null,
focusNowMs: (now) => now,
focusPassIsNeeded: () => false,
...(realFocus
? { clearFocusTarget, getFocusTarget, publishFocusTargetAt }
: {}),
},
context: {
clearTrackedSubjectContext: noop,
@@ -203,7 +224,12 @@ async function fixture(t) {
const viewer = { canvas: new EventTarget(), scene: {} };
const camera = fakeFollowCamera();
const frame = fakeFrame();
const { draw, unbind } = bindFakeDraw(viewer, { camera, frame });
const query = { project: () => ({ x: 720, y: 450 }) };
const { draw, unbind } = bindFakeDraw(viewer, {
camera,
frame,
...(realFocus ? { query } : {}),
});
const input = fakeInput(viewer);
let frameNumber = 1;
const { log, warn } = console;
@@ -221,6 +247,7 @@ async function fixture(t) {
console.log = log;
input.destroy();
unbind();
if (realFocus) clearFocusTarget();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
@@ -412,6 +439,27 @@ test('holding the subject hides its dot, ring, docked companions and bracket', a
assert.ok(f.detected().includes(ISS_NORAD));
});
test('releasing a satellite leaves no focus rectangle, even when a follow listener reads it', async (t) => {
const f = await fixture(t, { realFocus: true });
// As the Cockpit entry button does: every follow change asks for the subject.
let readsOnRelease = 0;
f.camera.on('followChanged', (followed) => {
if (followed) return;
readsOnRelease += 1;
f.methods.getCockpitSubject();
});
assert.equal(f.track(GPS), true);
f.nextFrame();
f.methods.getCockpitSubject();
assert.equal(getFocusTarget()?.ownerLayer, 'satellites');
assert.equal(getFocusTarget()?.id, GPS);
f.methods.stopTracking();
assert.equal(readsOnRelease, 1, 'the listener ran during the release');
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(getFocusTarget(), null);
});
test('a subject that is not tracked holds nothing', async (t) => {
const f = await fixture(t);
f.track(GPS);
+11 -8
View File
@@ -90,18 +90,18 @@ export function createTracking({ state: layerState, services, parts, source }) {
return;
}
const clearedNorad = layerState._trackedNorad;
clearFocusTarget('satellites', layerState._trackedNorad);
clearFocusTarget('satellites', clearedNorad);
// Re-show the dot (hidden while the tracked dot drew it) and
// restore the original group palette from the shared style table (WS-D3)
parts.rendering._restorePoint(
layerState._trackedNorad,
clearedNorad,
parts.controls._pointStyleFor(
layerState._trackedNorad,
layerState._catalog.get(layerState._trackedNorad)?.group,
clearedNorad,
layerState._catalog.get(clearedNorad)?.group,
),
// Back to its class's visibility: a hidden class stays hidden.
parts.controls._classVisible(layerState._trackedNorad),
parts.controls._classVisible(clearedNorad),
);
// Invalidate the per-frame tracked-position cache (WS-D2)
@@ -109,9 +109,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedFrameGeo = null;
// Remove the tracked dot and orbit path (unless ISS — keep its path)
if (layerState._trackedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(layerState._trackedNorad);
if (clearedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(clearedNorad);
}
// Released before the camera hears of it: a follow listener that reads
// the tracked position mid-release must find nothing, or it would publish
// the focus rectangle again after it was cleared above.
layerState._trackedNorad = null;
if (layerState._viewer && !skipViewerUntrack)
stopFollowing(layerState._viewer);
layerState._followTarget = null;
@@ -119,7 +123,6 @@ export function createTracking({ state: layerState, services, parts, source }) {
parts.rendering._removeTrackedEntity(layerState._trackedEntity);
layerState._trackedEntity = null;
}
layerState._trackedNorad = null;
layerState._trackedDockedToStation = null;
layerState._trackedDockedToIss = false;
parts.controls._syncIssOrbit?.();
+72 -2
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createVesselLayer } from './index.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { VESSEL_VIEWS } from '../../data/viewSheet.js';
// Following the world clock on a renderer that moves icons along motion
// segments on its own clock, each vessel's icon is drawn along its track
@@ -10,7 +12,7 @@ import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const noop = () => {};
function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
function setup(t, { capabilities = new Set(['motionSegments']), fleet } = {}) {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
@@ -35,6 +37,7 @@ function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
clearOverlaySource: noop,
},
geoid: {},
...(fleet ? { fleet } : null),
sprites: {},
focus: {
focusNowMs: () => 0,
@@ -68,7 +71,7 @@ function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
[...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
);
return { layer, viewer, icons };
return { layer, viewer, icons, draw };
}
const T = 1_000_000;
@@ -282,3 +285,70 @@ test('going live, a vessel a live update has drawn since stays where that drew i
assert.deepEqual(icons().items.get(id).pos, visual.position);
}
});
test('on a renderer that draws view sheets a vessel is a view of its hull, an aid still its buoy', (t) => {
const { layer, viewer, icons, draw } = setup(t, {
capabilities: new Set(['motionSegments', 'viewSheets']),
fleet: { resolveAsset: (url) => `/gev${url}` },
});
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
{ ...row(minuteFixes), mmsi: '222', type: '36' },
{ ...row(minuteFixes), mmsi: '333', type: '50' },
{ ...row(minuteFixes), mmsi: '993672001', type: 'Port Hand Mark' },
]);
// The sheet, once, at the layer's asset URL.
assert.deepEqual(draw.viewSheets, [
[
VESSEL_VIEWS.id,
{ ...VESSEL_VIEWS.sheet, image: '/gev/sprites/vessel-views.webp' },
],
]);
const set = icons();
const cargo = set.items.get('111');
assert.deepEqual(cargo.image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.cargo,
fallback: vesselSprite('cargo'),
});
assert.equal(cargo.rotationMode, 'course', 'a view lies along its course');
assert.equal(cargo.imageLod, undefined);
assert.equal(set.items.get('222').image.first, VESSEL_VIEWS.subjects.sailing);
// A pilot boat: its own hull from the sheet, a service boat's flat hull.
assert.deepEqual(set.items.get('333').image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
const buoy = set.items.get('993672001');
assert.equal(buoy.image, aidSprite());
assert.equal(buoy.rotationMode, 'screen');
});
test('without view sheets a vessel keeps its flat hull', (t) => {
const { layer, viewer, icons, draw } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
]);
assert.deepEqual(draw.viewSheets, []);
assert.equal(icons().items.get('111').image, vesselSprite('cargo'));
});
test('a vessel is drawn larger near than far, under an aircraft at every range, and recedes toward the horizon', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
// The fastest step of a vessel's own scale.
{ ...row(minuteFixes), type: 'Cargo', speed: 20 },
]);
const set = icons();
assert.deepEqual(set.spec.recede, {}, "the renderer's own recession");
const item = set.items.get('111');
const curve = item.scaleByDistance;
const px = (value) => item.size[0] * item.scale * value;
assert.ok(px(curve.nearValue) > px(1), 'larger up close than it was');
// An aircraft icon: 20 px, three times that near and half of it far, over
// the same range (aircraftIconLayer.js).
assert.deepEqual([curve.near, curve.far], [1000, 8000000]);
assert.ok(px(curve.nearValue) < 20 * 3);
assert.ok(px(curve.farValue) < 20 * 0.5);
});
+56 -12
View File
@@ -44,8 +44,13 @@ import {
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { vesselPartState } from '../../data/modelPartDrivers.js';
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
import {
isAidToNavigation,
vesselKind,
vesselShape,
} from '../../data/vesselTypes.js';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { registerVesselViews, vesselViewRef } from '../../data/vesselViews.js';
import { cssColor } from '../../render/color.js';
import { KNOT_MPS } from '../../data/units.js';
@@ -61,6 +66,19 @@ const HIDDEN_FOLLOW_MS = 250;
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
const SHIP_ICON_PX = 32;
/**
* How a vessel or aid sprite's size follows its range from the eye, on the
* aircraft icons' range (`aircraftIconLayer.js`): half as large again up
* close, where a hull's shape reads; as it was drawn before at some
* 1,000 km; and a third from 8,000 km out. Under an aircraft's icon at every
* range, so a world of ships is a field of small marks.
*/
const SHIP_SCALE_BY_DISTANCE = Object.freeze({
near: 1000,
nearValue: 1.5,
far: 8000000,
farValue: 0.35,
});
let instances = 0;
@@ -228,6 +246,7 @@ export function createRendering({
advanceSpriteFocus,
focusAlphaNeedsWrite,
spriteFocusAtRest,
nearFarScalarValueAtDistance,
} = services.focus;
const {
holdContinuousRender,
@@ -265,12 +284,22 @@ export function createRendering({
const capabilities = rendererOf(viewer)?.capabilities ?? null;
iconMotion = capabilities?.has('motionSegments') === true;
segmentsWere = segmentsOn();
// On a renderer that draws view sheets a vessel is the view of its
// hull from where the eye is, not the flat hull.
iconViews = registerVesselViews(
drawOf(viewer),
capabilities,
services.fleet?.resolveAsset,
);
const set = drawOf(viewer).icons({
id: `ais-vessels:${++instances}`,
// Translucent, as its billboards were: overlapping chevrons keep
// their outlines rather than the first one's fill.
blend: 'translucent',
horizonCull: true,
// Toward the horizon a vessel shrinks and fades, as an aircraft does
// (the renderer's defaults, which are the aircraft sets').
recede: {},
drawOrder: spriteDrawOrder?.('ais') ?? 0,
...(iconMotion ? { motionClock: motionClock(segmentsWere) } : null),
});
@@ -286,6 +315,8 @@ export function createRendering({
// segments on its own clock.
let iconSet = null;
let iconMotion = false;
// Whether a vessel's icon is drawn from the vessel view sheet.
let iconViews = false;
// Whether the icons last moved on the renderer's clock.
let segmentsWere = false;
// The record drawn under each icon id, for replanning an id.
@@ -381,6 +412,7 @@ export function createRendering({
state.icons?.dispose();
state.icons = null;
iconSet = null;
iconViews = false;
iconRecords.clear();
planFrom.clear();
replannedAtMs = -Infinity;
@@ -430,6 +462,7 @@ export function createRendering({
// Tinted by type; selection changes neither the colour nor the size.
color: shipTint(record),
scale: shipScale(record),
scaleByDistance: SHIP_SCALE_BY_DISTANCE,
// An aid's buoy stands upright on screen; a vessel turns with course.
rotationMode: aid ? 'screen' : 'course',
rotation: 0,
@@ -529,18 +562,22 @@ export function createRendering({
}
/**
* The sprite a vessel is drawn as: the white hull of its kind
* (`vesselKind`), bow up so the row's course turns it to its heading, or
* for an aid to navigation the buoy. The layer tints it
* (`shipTint`), so each shape takes one icon-atlas slot.
* The sprite a vessel is drawn as: on a renderer that draws view sheets,
* the view of its kind's hull (`vesselKind`) from where the eye is
* (`vesselViews.js`), with the flat hull to fall back on; else the flat
* white hull, bow up so the row's course turns it to its heading. An aid
* to navigation is the buoy either way. The layer tints it (`shipTint`).
* @param {Object} record - Vessel record.
* @returns {string} SVG data URL.
* @returns {string|{views: string, first: number, fallback: string}} SVG
* data URL, or a view of the vessel sheet.
*/
function shipIcon(record) {
return isAidToNavigation(record)
? aidSprite()
: vesselSprite(vesselKind(record.type));
if (isAidToNavigation(record)) return aidSprite();
const kind = vesselKind(record.type);
return iconViews
? vesselViewRef(vesselShape(record.type), kind)
: vesselSprite(kind);
}
/**
@@ -1308,18 +1345,25 @@ export function createRendering({
!focusAlphaNeedsWrite(icons.focus(id), 1, params)
)
continue;
const cameraDistance = cameraDistanceFor(position);
// The sprite's half size as drawn at that range.
const half =
(item.scale ?? 1) *
(nearFarScalarValueAtDistance?.(item.scaleByDistance, cameraDistance) ??
1) *
0.5;
const focus = advanceSpriteFocus(sprite, {
// Hidden/far-side icons still finish any pending release so the active
// count remains truthful and they cannot reappear with stale dim alpha.
screenPosition: visual.visible ? screenPositionFor(position) : null,
cameraDistance: cameraDistanceFor(position),
cameraDistance,
nowMs,
target,
params,
// Vessel artwork is 32 px before scale. Including the ambient
// chevron's own rendered extent prevents edge-overlap misses.
spriteHalfWidthPx: item.size[0] * (item.scale ?? 1) * 0.5,
spriteHalfHeightPx: item.size[1] * (item.scale ?? 1) * 0.5,
spriteHalfWidthPx: item.size[0] * half,
spriteHalfHeightPx: item.size[1] * half,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more