mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d60144f60 | ||
|
|
eebde0bdca | ||
|
|
d9d79ebc4d | ||
|
|
e4caf5d3af | ||
|
|
561f5885c2 | ||
|
|
7ff536299a | ||
|
|
918435ddc7 | ||
|
|
fbbe6cd91f | ||
|
|
5608b12a25 | ||
|
|
ae212e5b63 | ||
|
|
deff042265 | ||
|
|
aac6be7773 | ||
|
|
84324ea678 | ||
|
|
41c792208e | ||
|
|
b94e556693 | ||
|
|
20647f6549 | ||
|
|
2c5f9f89f7 | ||
|
|
d19ae89630 | ||
|
|
99a70a0e0c | ||
|
|
b020a1cd91 | ||
|
|
28007e20ef | ||
|
|
02c60c0a20 | ||
|
|
b98b9d390f | ||
|
|
c0752784d2 | ||
|
|
147d1f5e4e | ||
|
|
5887235894 | ||
|
|
564383e4b5 | ||
|
|
b1b66e9717 | ||
|
|
9a3fc84935 | ||
|
|
0151c178a4 | ||
|
|
3bda877a8a |
No files matched your search
+22
-1
@@ -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),
|
||||
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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,4 @@
|
||||
- Quantized-mesh terrain can supply its tiles through `fetchTile`, as `xyz`
|
||||
imagery does: Cesium still reads `layer.json`, schedules, cancels and
|
||||
decodes the tiles, and a `missing` tile draws its parent's terrain there
|
||||
(samehkhamis, #1902).
|
||||
+50
-25
@@ -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
|
||||
@@ -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)).
|
||||
@@ -9904,7 +9924,12 @@ unless its plugin hands the application a map engine of its own
|
||||
terrain as `quantizedMesh` terrain at its URL (`src/maps/keylessTerrain.js`);
|
||||
while the keyless terrain does not answer, the ellipsoid stands in and the
|
||||
map stack tries it again behind it. A renderer without the `terrain`
|
||||
capability keeps the ellipsoid.
|
||||
capability keeps the ellipsoid. A `quantizedMesh` terrain source can supply
|
||||
its tiles through `fetchTile`, like `xyz` imagery: Cesium still reads
|
||||
`layer.json` at the source's URL, schedules, cancels and decodes the tiles,
|
||||
and only each tile's bytes come from `fetchTile`; a `missing` tile draws its
|
||||
parent's terrain, a `defer`red one is asked for again shortly
|
||||
(`src/render/cesium/terrainTiles.js`).
|
||||
|
||||
A viewer with no renderer bound gets the Cesium engine
|
||||
(`src/render/cesium/mapEngine.js`), with the other unbound ports, from the
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -813,4 +872,4 @@ course. The stub keeps no drawn course. These wait for scenes that capture
|
||||
an icon mid-turn. Height queries that count a set
|
||||
(`includeInHeightQueries`) are not checked either: the stub's heights are
|
||||
scripted, so it does not model them. Nor are video frames (a check needs a
|
||||
video) or `fetchTile` (the stub fetches nothing).
|
||||
video) or `fetchTile`, imagery's or terrain's (the stub fetches nothing).
|
||||
+1
-1
@@ -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) |
|
||||
|
||||
@@ -78,8 +78,12 @@
|
||||
"src/render/cesium/uploadProbe.test.mjs",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
"src/render/cesium/tileRequests.test.mjs",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/cesium/terrainTiles.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 +471,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",
|
||||
|
||||
@@ -279,7 +279,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 +1103,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",
|
||||
@@ -1344,6 +1344,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",
|
||||
@@ -1386,6 +1387,7 @@
|
||||
"src/render/cesium/effects.js",
|
||||
"src/render/cesium/screenModulation.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
"src/render/cesium/imageryFrames.js",
|
||||
@@ -2433,6 +2435,7 @@
|
||||
"src/render/cesium/gpuIcons.js",
|
||||
"src/render/cesium/effects.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/cesium/query.js",
|
||||
"src/render/cesium/quality.js",
|
||||
"src/render/input/wheel.js",
|
||||
@@ -2531,6 +2534,7 @@
|
||||
"src/render/stub/math.js",
|
||||
"src/render/cesium/unbound.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
@@ -3220,6 +3224,7 @@
|
||||
"src/sources/requestDeadline.js",
|
||||
"src/layers/traffic/lifecycle.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
@@ -3385,6 +3390,7 @@
|
||||
"modules": [
|
||||
"src/render/cesium/google3d.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/cesium/imagery.js",
|
||||
"src/render/cesium/imageryFrames.js",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
@@ -3966,6 +3972,7 @@
|
||||
"src/maps/catalog.js",
|
||||
"src/maps/controller.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/iconSetPrimitive.js",
|
||||
"src/render/recession.js",
|
||||
@@ -4279,6 +4286,7 @@
|
||||
"src/render/motion/iconMotion.js",
|
||||
"src/render/cesium/query.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/drawHit.js",
|
||||
"src/render/cesium/draw.js",
|
||||
@@ -4796,6 +4804,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",
|
||||
@@ -6249,6 +6258,7 @@
|
||||
"src/layers/recentImagery/rendering.js",
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/globe.js",
|
||||
"src/render/cesium/terrainTiles.js",
|
||||
"src/layers/recentImagery/thumbnails.js",
|
||||
"src/maps/imageryHost.js",
|
||||
"src/layers/streetLevel/index.js",
|
||||
@@ -8188,7 +8198,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",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -23,7 +23,6 @@ const API_URL =
|
||||
'attr_IncidentTypeCategory',
|
||||
'attr_FireDiscoveryDateTime',
|
||||
'poly_DateCurrent',
|
||||
'poly_PolygonDateTime',
|
||||
'attr_FireCause',
|
||||
'attr_FireBehaviorGeneral',
|
||||
'attr_TotalIncidentPersonnel',
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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({
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -541,7 +541,7 @@
|
||||
"Conversation",
|
||||
"Country",
|
||||
"Cyan",
|
||||
"Cyclones · NHC / CPHC",
|
||||
"Cyclones · NHC / CPHC · JTWC",
|
||||
"DENSE",
|
||||
"DEST ---°",
|
||||
"DEST {bearing}",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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=/);
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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) } : {}),
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,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'],
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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(), []);
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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?.();
|
||||
|
||||
@@ -86,6 +86,62 @@ function sameMatrix(array, matrix) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const finiteVector = (v) =>
|
||||
!!v && Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z);
|
||||
|
||||
/** Conservative globe/frustum visibility; null means unknown. */
|
||||
export function createPointsVisibility(scene, camera) {
|
||||
const visibilitySphere = new Cesium.BoundingSphere();
|
||||
let visibilityMargin = null;
|
||||
let visibilityEllipsoid = null;
|
||||
let visibilityOccluder = null;
|
||||
return function visiblePoints(points, marginM) {
|
||||
const eye = camera.positionWC;
|
||||
const direction = camera.directionWC;
|
||||
const up = camera.upWC;
|
||||
if (
|
||||
scene.mode !== Cesium.SceneMode.SCENE3D ||
|
||||
!points?.length ||
|
||||
!finiteVector(eye) ||
|
||||
!finiteVector(direction) ||
|
||||
!finiteVector(up) ||
|
||||
!points.every(finiteVector)
|
||||
)
|
||||
return null;
|
||||
if (visibilityMargin !== marginM) {
|
||||
const radii = Cesium.Ellipsoid.WGS84.radii;
|
||||
visibilityMargin = marginM;
|
||||
visibilityEllipsoid = new Cesium.Ellipsoid(
|
||||
radii.x - marginM,
|
||||
radii.y - marginM,
|
||||
radii.z - marginM,
|
||||
);
|
||||
visibilityOccluder = new Cesium.EllipsoidalOccluder(visibilityEllipsoid);
|
||||
}
|
||||
const inverse = visibilityEllipsoid.oneOverRadii;
|
||||
// Inside the ellipsoid Cesium's occluder hides nearby points; judge by the frustum alone.
|
||||
const outside =
|
||||
Math.hypot(eye.x * inverse.x, eye.y * inverse.y, eye.z * inverse.z) >= 1;
|
||||
if (outside) {
|
||||
visibilityOccluder.cameraPosition = eye;
|
||||
let visible = false;
|
||||
for (const p of points) {
|
||||
if (visibilityOccluder.isPointVisible(p)) {
|
||||
visible = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!visible) return false;
|
||||
}
|
||||
const culling = camera.frustum.computeCullingVolume(eye, direction, up);
|
||||
return (
|
||||
culling.computeVisibility(
|
||||
Cesium.BoundingSphere.fromPoints(points, visibilitySphere),
|
||||
) !== Cesium.Intersect.OUTSIDE
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{scene: object, camera: object, report: (error: unknown) => void,
|
||||
* widget?: object, capabilities?: ReadonlySet<string>,
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
headlessCamera,
|
||||
withVirtualClock,
|
||||
} from './cameraGoldens.js';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { createCesiumCamera, createPointsVisibility } from './camera.js';
|
||||
import { createCesiumPorts } from './ports.js';
|
||||
import { bindRenderer, cameraOf } from '../rendererOf.js';
|
||||
|
||||
@@ -337,6 +337,147 @@ test('the camera port gives the clock its own tick back as it goes', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('visiblePoints is there only with its capability, and unknown outside 3D', (t) => {
|
||||
const { scene } = headlessCamera();
|
||||
for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender'])
|
||||
scene[name] = new Cesium.Event();
|
||||
scene.primitives = { add() {}, remove() {} };
|
||||
scene.requestRender = () => {};
|
||||
const viewer = { scene, clock: { currentTime: Cesium.JulianDate.now() } };
|
||||
const without = createCesiumPorts(viewer, { capabilities: new Set() });
|
||||
assert.equal(without.camera.visiblePoints, undefined);
|
||||
without.dispose();
|
||||
const ports = createCesiumPorts(viewer, {
|
||||
capabilities: new Set(['pointVisibility']),
|
||||
});
|
||||
t.after(() => ports.dispose());
|
||||
const points = [Cesium.Cartesian3.fromDegrees(0, 0, 10)];
|
||||
for (const mode of [
|
||||
Cesium.SceneMode.SCENE2D,
|
||||
Cesium.SceneMode.COLUMBUS_VIEW,
|
||||
Cesium.SceneMode.MORPHING,
|
||||
undefined,
|
||||
]) {
|
||||
scene.mode = mode;
|
||||
assert.equal(ports.camera.visiblePoints(points, 200), null);
|
||||
}
|
||||
scene.mode = Cesium.SceneMode.SCENE3D;
|
||||
assert.equal(typeof ports.camera.visiblePoints(points, 200), 'boolean');
|
||||
});
|
||||
|
||||
const point = (lon, lat, altitude = 20) =>
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, altitude);
|
||||
const down = Cesium.Cartesian3.negate(
|
||||
Cesium.Cartesian3.UNIT_X,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const up = Cesium.Cartesian3.UNIT_Z;
|
||||
const frustum = new Cesium.PerspectiveFrustum({
|
||||
fov: Cesium.Math.toRadians(60),
|
||||
aspectRatio: 16 / 9,
|
||||
near: 1,
|
||||
// Cesium's default far plane, as the app uses.
|
||||
far: 5e8,
|
||||
});
|
||||
|
||||
function visibility(position, direction, up) {
|
||||
const visiblePoints = createPointsVisibility(
|
||||
{ mode: Cesium.SceneMode.SCENE3D },
|
||||
{ positionWC: position, directionWC: direction, upWC: up, frustum },
|
||||
);
|
||||
return (points) => visiblePoints(points, 200);
|
||||
}
|
||||
|
||||
function directionTo(position, target) {
|
||||
return Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.subtract(target, position, new Cesium.Cartesian3()),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
}
|
||||
|
||||
function assertInFrustum(points, position, direction) {
|
||||
const culling = frustum.computeCullingVolume(position, direction, up);
|
||||
assert.notEqual(
|
||||
culling.computeVisibility(Cesium.BoundingSphere.fromPoints(points)),
|
||||
Cesium.Intersect.OUTSIDE,
|
||||
);
|
||||
}
|
||||
|
||||
test('a plane in front of the camera is visible', () => {
|
||||
assert.equal(visibility(point(0, 0, 30000), down, up)([point(0, 0)]), true);
|
||||
});
|
||||
|
||||
test('a plane behind the camera is outside the frustum', () => {
|
||||
assert.equal(
|
||||
visibility(point(0, 0, 30000), Cesium.Cartesian3.UNIT_X, up)([point(0, 0)]),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a corner can be in view when the mount and centre are outside', () => {
|
||||
const visible = visibility(point(0, 0, 30000), down, up);
|
||||
const mount = point(0.3, 0);
|
||||
const points = [
|
||||
mount,
|
||||
point(0.1, 0.0001),
|
||||
point(0.3, 0.0001),
|
||||
point(0.3, -0.0001),
|
||||
point(0.1, -0.0001),
|
||||
];
|
||||
assert.equal(visible(points), true);
|
||||
assert.equal(visible([mount]), false);
|
||||
assert.equal(visible([point(0.2, 0)]), false);
|
||||
});
|
||||
|
||||
test('a nearby plane below the ellipsoid is visible to low and high viewers', () => {
|
||||
const cap = point(0.00054, 0, -18);
|
||||
const points = [point(0, 0, -18), cap];
|
||||
for (const altitude of [4, 1200]) {
|
||||
const position = point(0.00135, 0, altitude);
|
||||
const direction = directionTo(position, cap);
|
||||
assertInFrustum(points, position, direction);
|
||||
assert.equal(visibility(position, direction, up)(points), true);
|
||||
}
|
||||
});
|
||||
|
||||
test('the horizon rejects a negative-height plane on the far side', () => {
|
||||
const mount = point(0, 0, -18);
|
||||
const points = [mount, point(0.00054, 0, -18)];
|
||||
for (const altitude of [4, 30000, 2e7]) {
|
||||
const position = point(180, 0, altitude);
|
||||
const direction = directionTo(position, mount);
|
||||
assertInFrustum(points, position, direction);
|
||||
assert.equal(visibility(position, direction, up)(points), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('a low viewer can see a plane beyond the WGS84 horizon', () => {
|
||||
const mount = point(0, 0, 1);
|
||||
const position = point(0.2, 0, 4);
|
||||
assert.equal(
|
||||
visibility(position, directionTo(position, mount), up)([mount]),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('deep viewers do not lose nearby planes to the horizon test', () => {
|
||||
const mount = point(0, 0, -350);
|
||||
const position = point(0.00135, 0, -300);
|
||||
assert.equal(
|
||||
visibility(position, directionTo(position, mount), up)([mount]),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('a non-finite camera direction leaves visibility unknown', () => {
|
||||
const visible = visibility(
|
||||
point(0, 0, 30000),
|
||||
new Cesium.Cartesian3(NaN, 0, 0),
|
||||
up,
|
||||
);
|
||||
assert.equal(visible([point(0, 0)]), null);
|
||||
});
|
||||
|
||||
test('setFov holds the vertical angle across resizes, and waits for a first one', () => {
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
|
||||
@@ -321,6 +321,8 @@ test('the application’s Cesium renderer runs the controller around its preUpda
|
||||
const renderer = await plugin.create({ container: {} });
|
||||
assert.equal(scene.screenSpaceCameraController.enableInputs, false);
|
||||
assert.equal(typeof renderer.camera.native.setPose, 'function');
|
||||
assert.equal(renderer.capabilities.has('pointVisibility'), true);
|
||||
assert.equal(renderer.camera.visiblePoints([], 200), null);
|
||||
renderer.frame.on('preUpdate', () => order.push('preUpdate'));
|
||||
scene.preUpdate.raise(scene, Cesium.JulianDate.fromDate(new Date(5000)));
|
||||
assert.deepEqual(order, [['before', 5000], 'preUpdate', 'after']);
|
||||
|
||||
+672
-69
File diff suppressed because it is too large.
Load diff
@@ -2294,7 +2294,7 @@ test('points show only within their display range', () => {
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('the fire perimeters layer draws holed ground fills and draped outlines on a viewer of its own', async () => {
|
||||
test('the fire perimeters layer draws holed ground fills and draped fire lines on a viewer of its own', async () => {
|
||||
const { createFirePerimetersLayer } =
|
||||
await import('../../layers/perimeters/index.js');
|
||||
const scene = fakeScene();
|
||||
@@ -2313,19 +2313,9 @@ test('the fire perimeters layer draws holed ground fills and draped outlines on
|
||||
];
|
||||
const layer = createFirePerimetersLayer({
|
||||
source: {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
revision: 'r',
|
||||
fires: [{ id: 'a', containedPct: 0, anchor: { lon: -108, lat: 35.2 } }],
|
||||
pieces: [
|
||||
{
|
||||
fireId: 'a',
|
||||
born: null,
|
||||
polygons: [[outer, hole]],
|
||||
outline: [outer, hole],
|
||||
},
|
||||
],
|
||||
}),
|
||||
getSnapshot: async () => [
|
||||
{ stableId: 'a', containedPct: 0, polygons: [[outer, hole]] },
|
||||
],
|
||||
},
|
||||
});
|
||||
layer.init(viewer);
|
||||
@@ -2346,9 +2336,9 @@ test('the fire perimeters layer draws holed ground fills and draped outlines on
|
||||
assert.equal(instance.geometry._polygonHierarchy.holes.length, 1);
|
||||
const [line] = of(Cesium.GroundPolylinePrimitive);
|
||||
assert.equal(line.classificationType, Cesium.ClassificationType.BOTH);
|
||||
assert.equal(line.geometryInstances.length, 2, 'the hole is outlined too');
|
||||
assert.equal(line.geometryInstances.length, 1, 'the exterior ring only');
|
||||
assert.equal(line.geometryInstances[0].geometry.width, 2);
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:line:0');
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:0');
|
||||
layer.destroy();
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import test, { after } from 'node:test';
|
||||
import { createCesiumDraw, lineAgeData } from './draw.js';
|
||||
|
||||
// Node has no WebGL context to report line-width limits.
|
||||
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
|
||||
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
|
||||
|
||||
// A material's texture uniform is told from the browser's image classes, which
|
||||
// Node lacks.
|
||||
const IMAGE_CLASSES = [
|
||||
'HTMLCanvasElement',
|
||||
'HTMLImageElement',
|
||||
'ImageBitmap',
|
||||
'OffscreenCanvas',
|
||||
];
|
||||
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
|
||||
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
|
||||
after(() =>
|
||||
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
|
||||
);
|
||||
|
||||
/** A scene with what a line set touches: primitives, its events and its time. */
|
||||
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
|
||||
const added = [];
|
||||
return {
|
||||
added,
|
||||
postRender: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
|
||||
frameState: {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
},
|
||||
updateHeight: () => () => {},
|
||||
getHeight: () => undefined,
|
||||
primitives: {
|
||||
add: (primitive) => (added.push(primitive), primitive),
|
||||
remove: (primitive) => {
|
||||
const at = added.indexOf(primitive);
|
||||
if (at >= 0) added.splice(at, 1);
|
||||
return at >= 0;
|
||||
},
|
||||
length: 0,
|
||||
},
|
||||
requestRender() {},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
}
|
||||
|
||||
const T0 = Date.UTC(2026, 0, 1);
|
||||
|
||||
/** A port that fades lines with age, over `scene`, and its frames at a scene time. */
|
||||
function agedDraw(scene = fakeScene(), capabilities = ['lineAgeFade']) {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
capabilities: new Set(capabilities),
|
||||
});
|
||||
return {
|
||||
part,
|
||||
scene,
|
||||
frameAt(ms) {
|
||||
scene.frameState.time = Cesium.JulianDate.fromDate(new Date(ms));
|
||||
part.beforeRender();
|
||||
part.afterRender();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const along = (n, lat = 10) =>
|
||||
Array.from({ length: n }, (_, i) =>
|
||||
Cesium.Cartesian3.fromDegrees(i * 0.01, lat, 100),
|
||||
);
|
||||
|
||||
const trail = (positions, times, extra = {}) => ({
|
||||
id: 'trail',
|
||||
positions,
|
||||
widthPx: 3,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
|
||||
ageFade: { times, windowMs: 60_000, alphaFloor: 0.06, ...extra },
|
||||
pickable: false,
|
||||
});
|
||||
|
||||
/** The polylines a line set's host draws in its collection. */
|
||||
function collectionOf(scene) {
|
||||
const host = scene.added.at(-1);
|
||||
if (host instanceof Cesium.PolylineCollection) return host;
|
||||
for (let i = 0; i < host.length; i++)
|
||||
if (host.get(i) instanceof Cesium.PolylineCollection) return host.get(i);
|
||||
return null;
|
||||
}
|
||||
|
||||
test('a polyline’s age texels: a point at the place of the one before it is dropped, the rest even along it, times in seconds before the newest', () => {
|
||||
const [a, b, c] = along(3);
|
||||
const age = lineAgeData([a, a, b, c], [T0, T0 + 1000, T0 + 2000, T0 + 4000], {
|
||||
times: [],
|
||||
windowMs: 30_000,
|
||||
alphaFloor: 0.06,
|
||||
squaredAlphaFloor: 0.14,
|
||||
});
|
||||
assert.equal(age.count, 3);
|
||||
assert.equal(age.base, T0 + 4000);
|
||||
const texel = (i) => [age.data[i * 4], age.data[i * 4 + 1]];
|
||||
assert.deepEqual(texel(0), [0, -4]);
|
||||
assert.deepEqual(texel(1), [0.5, -2]);
|
||||
assert.deepEqual(texel(2), [1, 0]);
|
||||
assert.deepEqual(age.uniforms, {
|
||||
ageCount: 3,
|
||||
ageWidth: 3,
|
||||
ageRows: 1,
|
||||
ageByLength: 0,
|
||||
ageWindow: 30,
|
||||
ageAlphaFloor: 0.06,
|
||||
ageSquaredFloor: 0.14,
|
||||
ageWidthFloor: 1,
|
||||
ageShow: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test('a windowed line’s age texels carry its span, in seconds; an endless one cuts at now alone', () => {
|
||||
const points = along(2);
|
||||
const fade = (showMs) => ({
|
||||
times: [],
|
||||
windowMs: 30_000,
|
||||
alphaFloor: 0.06,
|
||||
showMs,
|
||||
});
|
||||
const at = (showMs, windowed = true) =>
|
||||
lineAgeData(points, [T0, T0 + 1000], fade(showMs), false, windowed).uniforms
|
||||
.ageShow;
|
||||
assert.equal(at(45_000), 45);
|
||||
assert.equal(at(Infinity), -1);
|
||||
assert.equal(at(undefined), 0, 'no span, no cut');
|
||||
assert.equal(at(45_000, false), 0, 'not cut where the port does not');
|
||||
});
|
||||
|
||||
test('a draped line’s age texels lie along it by distance, and a long line takes more rows', () => {
|
||||
const points = [
|
||||
Cesium.Cartesian3.fromDegrees(0, 0),
|
||||
Cesium.Cartesian3.fromDegrees(1, 0),
|
||||
Cesium.Cartesian3.fromDegrees(4, 0),
|
||||
];
|
||||
const age = lineAgeData(
|
||||
points,
|
||||
[0, 1000, 2000],
|
||||
{ times: [], windowMs: 1, alphaFloor: 0 },
|
||||
true,
|
||||
);
|
||||
assert.equal(age.uniforms.ageByLength, 1);
|
||||
assert.equal(age.data[0], 0);
|
||||
assert.ok(
|
||||
Math.abs(age.data[4] - 0.25) < 1e-6,
|
||||
`a quarter along (${age.data[4]})`,
|
||||
);
|
||||
assert.equal(age.data[8], 1);
|
||||
const long = along(2500);
|
||||
const many = lineAgeData(
|
||||
long,
|
||||
long.map((_, i) => i),
|
||||
{ times: [], windowMs: 1, alphaFloor: 0 },
|
||||
);
|
||||
assert.equal(many.width, 1024);
|
||||
assert.equal(many.rows, 3);
|
||||
assert.equal(many.data.length, 1024 * 3 * 4);
|
||||
});
|
||||
|
||||
test('an aged line fades on the scene clock: time passing changes its material, never its line', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const positions = along(4);
|
||||
const times = [T0 - 30_000, T0 - 20_000, T0 - 10_000, T0];
|
||||
set.set([
|
||||
trail(positions, times, { squaredAlphaFloor: 0.14, widthFloor: 0.3 }),
|
||||
]);
|
||||
const polylines = collectionOf(scene);
|
||||
const polyline = polylines.get(0);
|
||||
const material = polyline.material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid');
|
||||
assert.ok(material.isTranslucent(), 'drawn in the translucent pass');
|
||||
assert.equal(material.uniforms.ageWindow, 60);
|
||||
assert.equal(material.uniforms.ageAlphaFloor, 0.06);
|
||||
assert.equal(material.uniforms.ageSquaredFloor, 0.14);
|
||||
assert.equal(material.uniforms.ageWidthFloor, 0.3);
|
||||
assert.equal(material.uniforms.ageCount, 4);
|
||||
assert.ok(
|
||||
Cesium.Color.equals(
|
||||
material.materials.aged.uniforms.color,
|
||||
new Cesium.Color(0.2, 0.8, 1, 0.9),
|
||||
),
|
||||
'its style’s colour inside',
|
||||
);
|
||||
for (let k = 1; k <= 120; k++) {
|
||||
frameAt(T0 + k * 1000);
|
||||
assert.equal(
|
||||
material.uniforms.ageNow,
|
||||
k,
|
||||
`seconds after its newest point, frame ${k}`,
|
||||
);
|
||||
}
|
||||
assert.equal(collectionOf(scene), polylines, 'the same collection');
|
||||
assert.equal(polylines.length, 1);
|
||||
assert.equal(polylines.get(0), polyline, 'the same line');
|
||||
assert.equal(polyline.material, material, 'the same material');
|
||||
});
|
||||
|
||||
test('an aged line given new points and times moves in place and takes the new times', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const positions = along(5);
|
||||
const times = [0, 1, 2, 3, 4].map((i) => T0 + i * 10_000);
|
||||
set.set([trail(positions.slice(0, 4), times.slice(0, 4))]);
|
||||
const polyline = collectionOf(scene).get(0);
|
||||
const material = polyline.material;
|
||||
frameAt(T0 + 40_000);
|
||||
assert.equal(material.uniforms.ageNow, 10);
|
||||
set.upsert([trail(positions.slice(1), times.slice(1))]);
|
||||
assert.equal(collectionOf(scene).get(0), polyline, 'moved in place');
|
||||
assert.equal(polyline.material, material);
|
||||
frameAt(T0 + 45_000);
|
||||
assert.equal(material.uniforms.ageNow, 5, 'from its new newest point');
|
||||
assert.ok(Cesium.Cartesian3.equals(polyline.positions[0], positions[1]));
|
||||
// A new colour is taken in place too, inside the fade.
|
||||
set.upsert([
|
||||
{
|
||||
...trail(positions.slice(1), times.slice(1)),
|
||||
style: { kind: 'solid', color: '#ff0000' },
|
||||
},
|
||||
]);
|
||||
assert.equal(collectionOf(scene).get(0), polyline, 'recoloured in place');
|
||||
assert.ok(
|
||||
Cesium.Color.equals(
|
||||
material.materials.aged.uniforms.color,
|
||||
Cesium.Color.RED,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('segment colours fade with age too, each segment with its own two times', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const times = [T0, T0 + 1000, T0 + 2000];
|
||||
set.set([
|
||||
{
|
||||
...trail(along(3), times),
|
||||
segmentColors: ['#ff0000', '#00ff00'],
|
||||
},
|
||||
]);
|
||||
const pieces = [];
|
||||
const visit = (primitive) => {
|
||||
if (primitive instanceof Cesium.Primitive) pieces.push(primitive);
|
||||
else if (primitive?.length !== undefined && primitive.get)
|
||||
for (let i = 0; i < primitive.length; i++) visit(primitive.get(i));
|
||||
};
|
||||
visit(scene.added.at(-1));
|
||||
assert.equal(pieces.length, 2);
|
||||
frameAt(T0 + 3000);
|
||||
const [first, second] = pieces.map((piece) => piece.appearance.material);
|
||||
assert.equal(first.type, 'DrawAgedLine_solid');
|
||||
assert.equal(
|
||||
first.uniforms.ageNow,
|
||||
2,
|
||||
'its newer point a second after the first',
|
||||
);
|
||||
assert.equal(second.uniforms.ageNow, 1);
|
||||
assert.ok(
|
||||
Cesium.Color.equals(first.materials.aged.uniforms.color, Cesium.Color.RED),
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.Color.equals(
|
||||
second.materials.aged.uniforms.color,
|
||||
Cesium.Color.LIME,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('a draped aged line draws by a ground primitive of its own, its times along its length', () => {
|
||||
const { part, scene } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const ground = [0, 1, 2].map((i) =>
|
||||
Cesium.Cartesian3.fromDegrees(i * 0.01, 10),
|
||||
);
|
||||
set.set([{ ...trail(ground, [T0, T0 + 1, T0 + 2]), mode: 'draped' }]);
|
||||
const host = scene.added.at(-1);
|
||||
const primitives = [];
|
||||
const visit = (primitive) => {
|
||||
if (primitive instanceof Cesium.GroundPolylinePrimitive)
|
||||
primitives.push(primitive);
|
||||
else if (primitive?.length !== undefined && primitive.get)
|
||||
for (let i = 0; i < primitive.length; i++) visit(primitive.get(i));
|
||||
};
|
||||
visit(host);
|
||||
assert.equal(primitives.length, 1);
|
||||
const material = primitives[0].appearance.material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid');
|
||||
assert.equal(material.uniforms.ageByLength, 1);
|
||||
});
|
||||
|
||||
test('an aged line built anew lets its old material go once its primitive is gone', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const deep = (times) => ({
|
||||
...trail(along(3), times),
|
||||
depthFail: { kind: 'solid', color: '#ffffff' },
|
||||
});
|
||||
set.set([deep([T0, T0 + 1, T0 + 2])]);
|
||||
const record = part.sets.get('trails');
|
||||
assert.equal(record.ages.size, 2, 'its line and the part behind the surface');
|
||||
const [old] = record.ages.keys();
|
||||
set.upsert([deep([T0 + 1, T0 + 2, T0 + 3])]);
|
||||
frameAt(T0 + 10);
|
||||
assert.ok(old.isDestroyed(), 'the old material went with its primitive');
|
||||
assert.equal(record.ages.size, 2);
|
||||
void scene;
|
||||
});
|
||||
|
||||
test('a windowed line is cut on the scene clock: time passing changes its material, never its line', () => {
|
||||
const { part, scene, frameAt } = agedDraw(fakeScene(), [
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
]);
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
// A whole track, an hour of it, shown over its last minute.
|
||||
const positions = along(61);
|
||||
const times = positions.map((_, i) => T0 + i * 60_000);
|
||||
set.set([trail(positions, times, { alphaFloor: 1, showMs: 60_000 })]);
|
||||
const polylines = collectionOf(scene);
|
||||
const polyline = polylines.get(0);
|
||||
const material = polyline.material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid');
|
||||
assert.equal(material.uniforms.ageShow, 60);
|
||||
assert.equal(material.uniforms.ageCount, 61);
|
||||
const before = polyline.positions;
|
||||
for (let k = 1; k <= 120; k++) {
|
||||
frameAt(T0 + k * 30_000);
|
||||
assert.equal(
|
||||
material.uniforms.ageNow,
|
||||
(k * 30_000 - 3_600_000) / 1000,
|
||||
`seconds after its newest point, frame ${k}`,
|
||||
);
|
||||
}
|
||||
assert.equal(collectionOf(scene), polylines, 'the same collection');
|
||||
assert.equal(polylines.get(0), polyline, 'the same line');
|
||||
assert.equal(polyline.material, material, 'the same material');
|
||||
assert.equal(polyline.positions, before, 'its points untouched');
|
||||
// A new span is a new look: drawn anew, with it.
|
||||
set.upsert([trail(positions, times, { alphaFloor: 1, showMs: 120_000 })]);
|
||||
assert.equal(collectionOf(scene).get(0).material.uniforms.ageShow, 120);
|
||||
});
|
||||
|
||||
test('without the window’s capability a line ignores its span and draws whole', () => {
|
||||
const { part, scene } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
set.set([trail(along(3), [T0, T0 + 1, T0 + 2], { showMs: 60_000 })]);
|
||||
const material = collectionOf(scene).get(0).material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid', 'still faded');
|
||||
assert.equal(material.uniforms.ageShow, 0, 'never cut');
|
||||
});
|
||||
|
||||
test('without the capability a line ignores its age fade; with it a bad fade is refused', () => {
|
||||
const plain = agedDraw(fakeScene(), []);
|
||||
const lines = plain.part.port.lines({ id: 'trails' });
|
||||
lines.set([trail(along(3), [T0])]);
|
||||
const material = collectionOf(plain.scene).get(0).material;
|
||||
assert.equal(material.type, 'Color', 'drawn as its style alone');
|
||||
|
||||
const { part } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
assert.throws(
|
||||
() => set.set([trail(along(3), [T0, T0])]),
|
||||
TypeError,
|
||||
'one time a position',
|
||||
);
|
||||
assert.throws(
|
||||
() => set.set([trail(along(2), [T0, T0], { windowMs: 0 })]),
|
||||
TypeError,
|
||||
'a positive window',
|
||||
);
|
||||
assert.throws(
|
||||
() => set.set([trail(along(2), [T0, T0], { widthFloor: 2 })]),
|
||||
TypeError,
|
||||
'floors from 0 to 1',
|
||||
);
|
||||
for (const showMs of [0, -1, Number.NaN])
|
||||
assert.throws(
|
||||
() => set.set([trail(along(2), [T0, T0], { showMs })]),
|
||||
TypeError,
|
||||
'a positive span',
|
||||
);
|
||||
assert.equal(set.size(), 0, 'nothing changed');
|
||||
});
|
||||
|
||||
test('an aged line made first leaves its style’s type named as a plain material of it is', () => {
|
||||
const lists = Cesium.Material._uniformList;
|
||||
const was = lists.Color;
|
||||
delete lists.Color;
|
||||
try {
|
||||
const { part, scene } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
set.set([trail(along(2), [T0, T0 + 1])]);
|
||||
assert.deepEqual(lists.Color, ['color_0'], 'as a plain Color material');
|
||||
// A plain line beside it then draws with it in its collection.
|
||||
set.upsert([
|
||||
{ ...trail(along(2), [T0, T0 + 1]), id: 'plain', ageFade: undefined },
|
||||
]);
|
||||
const plain = collectionOf(scene).get(1).material;
|
||||
assert.equal(plain.type, 'Color');
|
||||
assert.ok(
|
||||
lists.Color.every((name) => typeof plain._uniforms[name] === 'function'),
|
||||
);
|
||||
} finally {
|
||||
if (was) lists.Color = was;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import test, { after } from 'node:test';
|
||||
import { createCesiumDraw } from './draw.js';
|
||||
|
||||
// Node has no WebGL context to report line-width limits.
|
||||
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
|
||||
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
|
||||
|
||||
// A material's texture uniform is told from the browser's image classes, which
|
||||
// Node lacks.
|
||||
const IMAGE_CLASSES = [
|
||||
'HTMLCanvasElement',
|
||||
'HTMLImageElement',
|
||||
'ImageBitmap',
|
||||
'OffscreenCanvas',
|
||||
];
|
||||
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
|
||||
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
|
||||
after(() =>
|
||||
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
|
||||
);
|
||||
|
||||
/** A scene with what a line set touches: primitives, its events and its time. */
|
||||
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
|
||||
const added = [];
|
||||
return {
|
||||
added,
|
||||
postRender: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
|
||||
frameState: {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
},
|
||||
updateHeight: () => () => {},
|
||||
getHeight: () => undefined,
|
||||
primitives: {
|
||||
add: (primitive) => (added.push(primitive), primitive),
|
||||
remove: (primitive) => {
|
||||
const at = added.indexOf(primitive);
|
||||
if (at >= 0) added.splice(at, 1);
|
||||
return at >= 0;
|
||||
},
|
||||
length: 0,
|
||||
},
|
||||
requestRender() {},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
}
|
||||
|
||||
const T0 = Date.UTC(2026, 0, 1);
|
||||
|
||||
/** A port over a fake scene that draws lines in runs (and with `more`). */
|
||||
function brokenDraw(capabilities = ['lineBreaks'], scene = fakeScene()) {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
capabilities: new Set(capabilities),
|
||||
});
|
||||
return { part, scene, set: part.port.lines({ id: 'trails' }) };
|
||||
}
|
||||
|
||||
/** Six positions west to east, `height` up. */
|
||||
const along = (n = 6, height = 100) =>
|
||||
Array.from({ length: n }, (_, i) =>
|
||||
Cesium.Cartesian3.fromDegrees(i * 0.01, 10, height),
|
||||
);
|
||||
|
||||
/** Three runs: positions 0-1, 2-4 and 5 alone (which draws nothing). */
|
||||
const trails = (extra = {}) => ({
|
||||
id: 'trails',
|
||||
positions: along(),
|
||||
breaks: [2, 5],
|
||||
widthPx: 3,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
|
||||
...extra,
|
||||
});
|
||||
|
||||
/** Everything a set's host holds, collections opened. */
|
||||
function everything(scene) {
|
||||
const all = [];
|
||||
const walk = (p) => {
|
||||
all.push(p);
|
||||
if (p instanceof Cesium.PrimitiveCollection)
|
||||
for (let i = 0; i < p.length; i++) walk(p.get(i));
|
||||
};
|
||||
for (const p of scene.added) walk(p);
|
||||
return all;
|
||||
}
|
||||
|
||||
/** The polylines a set's collection draws. */
|
||||
function polylinesOf(scene) {
|
||||
const collection = everything(scene).find(
|
||||
(p) => p instanceof Cesium.PolylineCollection,
|
||||
);
|
||||
const lines = [];
|
||||
for (let i = 0; i < collection.length; i++) lines.push(collection.get(i));
|
||||
return lines;
|
||||
}
|
||||
|
||||
const lonOf = (p) =>
|
||||
Number(
|
||||
Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(p).longitude,
|
||||
).toFixed(6),
|
||||
);
|
||||
|
||||
test('an undraped line in runs is a polyline a run in its collection, each picked as the line', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails()]);
|
||||
const lines = polylinesOf(scene);
|
||||
assert.equal(lines.length, 2, 'a polyline a run with length');
|
||||
assert.deepEqual(
|
||||
lines.map((line) => line.positions.map(lonOf)),
|
||||
[
|
||||
[0, 0.01],
|
||||
[0.02, 0.03, 0.04],
|
||||
],
|
||||
'nothing from position 1 to 2, nor 4 to 5',
|
||||
);
|
||||
assert.deepEqual(
|
||||
lines.map((line) => line.id.id),
|
||||
['trails', 'trails'],
|
||||
'each run picks as its line',
|
||||
);
|
||||
assert.notEqual(lines[0].id, lines[1].id, 'under a pick id of its own');
|
||||
assert.equal(set.size(), 1, 'one item');
|
||||
});
|
||||
|
||||
test('a line in runs takes packed positions and breaks', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
const flat = new Float64Array(along().flatMap((p) => [p.x, p.y, p.z]));
|
||||
set.set([trails({ positions: flat, breaks: new Uint32Array([3]) })]);
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.positions.length),
|
||||
[3, 3],
|
||||
);
|
||||
});
|
||||
|
||||
test('an arrow in runs has a head at the end of each run', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails({ style: { kind: 'arrow', color: '#ffffff' } })]);
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.material.type),
|
||||
['PolylineArrow', 'PolylineArrow'],
|
||||
);
|
||||
});
|
||||
|
||||
test('segment colours and shows stay a pair of positions; the pairs across a break draw nothing', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
const red = [1, 0, 0, 1];
|
||||
const green = [0, 1, 0, 1];
|
||||
const blue = [0, 0, 1, 1];
|
||||
const line = (colors, shows) =>
|
||||
trails({
|
||||
style: { kind: 'glow', color: '#ffffff', power: 0.2 },
|
||||
segmentColors: colors,
|
||||
segmentShow: shows,
|
||||
});
|
||||
set.set([
|
||||
line([red, blue, green, green, blue], [true, true, true, false, true]),
|
||||
]);
|
||||
const host = scene.added[0];
|
||||
// In the set's collection, a polyline a segment.
|
||||
const pieces = polylinesOf(scene);
|
||||
assert.equal(pieces.length, 3, 'segments 0, 2 and 3; not 1 nor 4');
|
||||
assert.equal(pieces[0].material.type, 'PolylineGlow');
|
||||
const color = (p) => p.material.uniforms.color;
|
||||
assert.deepEqual(
|
||||
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
|
||||
[
|
||||
[1, 0, 0, true],
|
||||
[0, 1, 0, true],
|
||||
[0, 1, 0, false],
|
||||
],
|
||||
);
|
||||
set.upsert([
|
||||
line([green, red, red, blue, red], [true, false, true, true, true]),
|
||||
]);
|
||||
assert.equal(scene.added[0], host, 'recoloured and shown in place');
|
||||
assert.deepEqual(
|
||||
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
|
||||
[
|
||||
[0, 1, 0, true],
|
||||
[1, 0, 0, true],
|
||||
[0, 0, 1, true],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('a run of a line that fades with age takes its own points’ times', () => {
|
||||
const { scene, set } = brokenDraw(['lineAgeFade', 'lineBreaks']);
|
||||
const times = along().map((_, i) => T0 + i * 1000);
|
||||
set.set([trails({ ageFade: { times, windowMs: 60_000, alphaFloor: 0.1 } })]);
|
||||
const lines = polylinesOf(scene);
|
||||
assert.deepEqual(
|
||||
lines.map((line) => [line.material.type, line.material.uniforms.ageCount]),
|
||||
[
|
||||
['DrawAgedLine_solid', 2],
|
||||
['DrawAgedLine_solid', 3],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('a revealed line in runs reveals them in order, along their own length', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
// Runs of one leg and of two, all of one length, the gap between them
|
||||
// (positions 1 to 2) none: half their length is all of the first run
|
||||
// and a quarter of the second.
|
||||
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.5 })]);
|
||||
let lines = polylinesOf(scene);
|
||||
const revealOf = (line) => line.material.materials?.revealed;
|
||||
assert.equal(revealOf(lines[0]), undefined, 'the first run all shown');
|
||||
assert.equal(lines[0].show, true);
|
||||
const second = lines[1];
|
||||
assert.ok(revealOf(second), 'the second run revealed');
|
||||
// Half its first leg, of two.
|
||||
assert.ok(
|
||||
Math.abs(second.material.uniforms.reveal - 0.25) < 1e-9,
|
||||
`revealed a quarter along (${second.material.uniforms.reveal})`,
|
||||
);
|
||||
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.25 })]);
|
||||
lines = polylinesOf(scene);
|
||||
assert.equal(lines[1].show, false, 'a run not yet reached is hidden');
|
||||
});
|
||||
|
||||
test('a draped line in runs drapes a ground piece a run; a solid segmented one a ground instance a segment, none across a break', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails({ mode: 'draped', positions: along(6, 0) })]);
|
||||
const ground = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
);
|
||||
assert.equal(ground.length, 2, 'a ground piece a run with length');
|
||||
assert.deepEqual(
|
||||
ground.map((p) => p.geometryInstances[0].geometry._positions.length),
|
||||
[2, 3],
|
||||
);
|
||||
set.set([
|
||||
trails({
|
||||
mode: 'draped',
|
||||
positions: along(6, 0),
|
||||
segmentColors: along()
|
||||
.slice(1)
|
||||
.map(() => [0, 1, 0, 1]),
|
||||
}),
|
||||
]);
|
||||
const batch = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
);
|
||||
assert.equal(batch.length, 1, 'one batch');
|
||||
assert.equal(
|
||||
batch[0].geometryInstances.length,
|
||||
3,
|
||||
'segments 0, 2 and 3: not 1 nor 4',
|
||||
);
|
||||
});
|
||||
|
||||
test('changed breaks draw the line anew; the same ones change it in place', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails()]);
|
||||
const host = scene.added[0];
|
||||
set.upsert([trails({ show: false })]);
|
||||
assert.equal(scene.added[0], host, 'shown in place');
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.show),
|
||||
[false, false],
|
||||
);
|
||||
set.upsert([trails({ breaks: [3] })]);
|
||||
assert.notEqual(scene.added[0], host, 'built anew');
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.positions.length),
|
||||
[3, 3],
|
||||
);
|
||||
});
|
||||
|
||||
test('without the capability a line ignores its breaks; with it bad breaks are refused', () => {
|
||||
const plain = brokenDraw([]);
|
||||
plain.set.set([trails()]);
|
||||
assert.equal(polylinesOf(plain.scene).length, 1, 'one line, joined');
|
||||
|
||||
const { set } = brokenDraw();
|
||||
for (const breaks of [[0], [6], [3, 2], [2, 2], [1.5], ['2']])
|
||||
assert.throws(
|
||||
() => set.set([trails({ breaks })]),
|
||||
TypeError,
|
||||
`refused: ${JSON.stringify(breaks)}`,
|
||||
);
|
||||
assert.equal(set.size(), 0, 'nothing changed');
|
||||
set.set([trails({ breaks: [] })]);
|
||||
assert.equal(set.size(), 1, 'no breaks: one run');
|
||||
});
|
||||
|
||||
test('where the scene cannot drape, a draped line in runs draws a run over the surface each, hidden past the horizon', () => {
|
||||
const scene = fakeScene();
|
||||
scene.frameState.context = { depthTexture: false };
|
||||
const { part, set } = brokenDraw(['lineBreaks'], scene);
|
||||
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0);
|
||||
set.set([
|
||||
trails({
|
||||
mode: 'draped',
|
||||
positions: [at(0), at(0.01), at(0.02), at(0.03)],
|
||||
breaks: [2],
|
||||
// The overlay draws its shown segments only, from first to last.
|
||||
segmentShow: [false, true, true],
|
||||
}),
|
||||
trails({
|
||||
id: 'two',
|
||||
mode: 'draped',
|
||||
positions: [at(0), at(0.01), at(0.02), at(0.03)],
|
||||
breaks: [2],
|
||||
}),
|
||||
]);
|
||||
const frame = () => {
|
||||
part.beforeRender();
|
||||
part.afterRender();
|
||||
};
|
||||
const runs = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.Primitive && p.depthFailAppearance,
|
||||
);
|
||||
// The first line kept positions 1 to 3, its break at 1 of them: a run of
|
||||
// one position and one of two; the second two runs of two.
|
||||
assert.equal(runs.length, 3, 'a primitive a run with length');
|
||||
scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0);
|
||||
frame();
|
||||
assert.deepEqual(
|
||||
runs.map((p) => p.show),
|
||||
[true, true, true],
|
||||
);
|
||||
scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0);
|
||||
frame();
|
||||
assert.deepEqual(
|
||||
runs.map((p) => p.show),
|
||||
[false, false, false],
|
||||
'past the horizon',
|
||||
);
|
||||
});
|
||||
|
||||
test('a draped line in runs whose first run is later than its second times each run by its own points', () => {
|
||||
const { scene, set } = brokenDraw([
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
'lineBreaks',
|
||||
]);
|
||||
set.set([
|
||||
trails({
|
||||
mode: 'draped',
|
||||
positions: along(4, 0),
|
||||
breaks: [2],
|
||||
ageFade: {
|
||||
times: [T0 + 110_000, T0 + 120_000, T0, T0 + 10_000],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
showMs: 30_000,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const ground = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
);
|
||||
assert.equal(ground.length, 2, 'a ground piece a run');
|
||||
const ages = ground.map((p) => p.appearance.material.uniforms);
|
||||
assert.deepEqual(
|
||||
ages.map((u) => [u.ageCount, u.ageByLength, u.ageShow]),
|
||||
[
|
||||
[2, 1, 30],
|
||||
[2, 1, 30],
|
||||
],
|
||||
'its own two points each, along its length, cut to the span',
|
||||
);
|
||||
// Each run's clock reads from its own newest point: the first's is
|
||||
// 110 s later than the second's.
|
||||
assert.equal(ages[1].ageNow - ages[0].ageNow, 110);
|
||||
});
|
||||
@@ -23,6 +23,7 @@ import { createCesiumImagery } from './imagery.js';
|
||||
import { attributionText } from './vectorBase.js';
|
||||
import { loadVectorStyle } from '../vectorBase/index.js';
|
||||
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
|
||||
import { tileFetchResource, trackTileRequests } from './terrainTiles.js';
|
||||
|
||||
// The base marks live outside the adapter, so code that is not Cesium's can
|
||||
// mark a base; they are re-exported here for the code that still is.
|
||||
@@ -68,15 +69,26 @@ async function terrainProvider(spec, { worldDataToken }) {
|
||||
);
|
||||
},
|
||||
});
|
||||
const resource = new Cesium.Resource({
|
||||
const options = {
|
||||
url: spec.url,
|
||||
retryCallback: policy.retryCallback,
|
||||
retryAttempts: policy.retryAttempts,
|
||||
});
|
||||
return Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
};
|
||||
if (spec.fetchTile !== undefined && typeof spec.fetchTile !== 'function')
|
||||
throw new TypeError('Quantized-mesh terrain fetchTile is a function');
|
||||
// With `fetchTile`, Cesium still reads `layer.json` at the url; each
|
||||
// tile's bytes come from `fetchTile`.
|
||||
const tiles = new WeakMap();
|
||||
const resource = spec.fetchTile
|
||||
? tileFetchResource(options, spec.fetchTile, (request) =>
|
||||
request ? tiles.get(request) : undefined,
|
||||
)
|
||||
: new Cesium.Resource(options);
|
||||
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestVertexNormals: spec.requestVertexNormals ?? false,
|
||||
requestWaterMask: false,
|
||||
});
|
||||
return spec.fetchTile ? trackTileRequests(provider, tiles) : provider;
|
||||
}
|
||||
throw new TypeError(`Unknown terrain kind: ${spec.kind}`);
|
||||
}
|
||||
|
||||
@@ -491,6 +491,38 @@ test('terrain: quantized mesh at its url, asked again when its host is busy', as
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain: quantized mesh tiles through fetchTile', async (t) => {
|
||||
const { scene, port } = setup();
|
||||
const made = new Cesium.EllipsoidTerrainProvider();
|
||||
const own = made.requestTileGeometry;
|
||||
const asked = [];
|
||||
t.mock.method(Cesium.CesiumTerrainProvider, 'fromUrl', async (...args) => {
|
||||
asked.push(args);
|
||||
return made;
|
||||
});
|
||||
const fetchTile = async () => ({ missing: true });
|
||||
await port.setTerrain({
|
||||
kind: 'quantizedMesh',
|
||||
url: 'https://terrain.example/mesh',
|
||||
fetchTile,
|
||||
});
|
||||
assert.equal(scene.terrainProvider, made);
|
||||
const [[resource]] = asked;
|
||||
assert.equal(resource.url, 'https://terrain.example/mesh');
|
||||
assert.ok(resource.retryAttempts > 0, 'layer.json keeps its retry policy');
|
||||
assert.ok(resource instanceof Cesium.Resource);
|
||||
assert.notEqual(resource.constructor, Cesium.Resource);
|
||||
assert.notEqual(made.requestTileGeometry, own, 'tile requests are tracked');
|
||||
await assert.rejects(
|
||||
port.setTerrain({
|
||||
kind: 'quantizedMesh',
|
||||
url: 'https://terrain.example/mesh',
|
||||
fetchTile: 'nope',
|
||||
}),
|
||||
/fetchTile is a function/,
|
||||
);
|
||||
});
|
||||
|
||||
test('setBase replaces the imagery and says what it drew', async () => {
|
||||
const { scene, port } = setup();
|
||||
const overlay = port.imagery.add({ kind: 'xyz', url: url('overlay') });
|
||||
|
||||
@@ -72,6 +72,10 @@ export const CESIUM_CHECKS = new Set([
|
||||
'draw.lines.drape',
|
||||
'draw.lines.split',
|
||||
'draw.lines.outlineDraped',
|
||||
'draw.lines.ageFade',
|
||||
'draw.lines.timeWindow',
|
||||
'draw.lines.breaks',
|
||||
'draw.lines.breaks.timeWindow',
|
||||
'draw.lines.segments',
|
||||
'draw.lines.segmentStyles',
|
||||
'draw.sets.blend',
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
* absent, never stubbed.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { createCesiumCamera, createPointsVisibility } from './camera.js';
|
||||
import { createControlledCamera } from './controlledCamera.js';
|
||||
import { listenerList, toCartesian, uncaught } from './common.js';
|
||||
import { createCesiumCredits } from './credits.js';
|
||||
@@ -83,7 +83,16 @@ export function cesiumCapabilities(scene, only) {
|
||||
'meshes',
|
||||
// Raster shells; other field kinds are refused.
|
||||
'fields',
|
||||
// Lines faded with age in their material, from a floating-point
|
||||
// texture of their points' times (`draw.js`).
|
||||
// And cut by time there, within a span of the scene clock.
|
||||
...(scene?.context?.floatingPointTexture
|
||||
? ['lineAgeFade', 'lineTimeWindow']
|
||||
: []),
|
||||
// Lines in runs, a piece a run (`draw.js`).
|
||||
'lineBreaks',
|
||||
'followFrame',
|
||||
'pointVisibility',
|
||||
// Cesium's AUTODETECT tracking frame (`follow.js`).
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
@@ -488,6 +497,8 @@ export function createCesiumPorts(
|
||||
: {}),
|
||||
});
|
||||
const cameraPort = cameraPart.port;
|
||||
if (capabilities.has('pointVisibility'))
|
||||
cameraPort.visiblePoints = createPointsVisibility(scene, camera);
|
||||
measureCameraChanged = cameraPart.measureChanged ?? null;
|
||||
const effectsPart = createCesiumEffects(scene, {
|
||||
capabilities,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { createNativeClick } from './nativeClick.js';
|
||||
test('capabilities follow what the scene supports', () => {
|
||||
const effects = [
|
||||
'followFrame',
|
||||
'pointVisibility',
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
'columns',
|
||||
@@ -42,6 +43,7 @@ test('capabilities follow what the scene supports', () => {
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
'lineBreaks',
|
||||
];
|
||||
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
|
||||
// A scene with a globe reads its visibility back.
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* @module render/cesium/terrainTiles
|
||||
* @description Quantized-mesh terrain tiles fetched through a terrain
|
||||
* spec's `fetchTile`, the way imagery layers fetch theirs.
|
||||
*
|
||||
* Cesium still reads `layer.json` itself, decides which tiles a frame needs,
|
||||
* schedules and cancels their requests and decodes the meshes; only the
|
||||
* fetch of each tile's bytes goes through `fetchTile`. Every resource
|
||||
* Cesium derives from the terrain's resource (its `layer.json`, each tile)
|
||||
* is a {@link tileFetchResource}, so a tile request reaches `fetchTile`
|
||||
* with the tile's URL as Cesium resolved it.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** Delay before a deferred terrain tile is asked for again. */
|
||||
export const TERRAIN_RETRY_DELAY_MS = 250;
|
||||
|
||||
/** A tile `fetchTile` says is not there; Cesium draws the parent's instead. */
|
||||
export class MissingTerrainTile extends Error {
|
||||
constructor() {
|
||||
super('Terrain tile is missing');
|
||||
this.name = 'MissingTerrainTile';
|
||||
}
|
||||
}
|
||||
|
||||
const wait = (ms, signal) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(done, ms);
|
||||
function done() {
|
||||
signal.removeEventListener('abort', aborted);
|
||||
resolve();
|
||||
}
|
||||
function aborted() {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason);
|
||||
}
|
||||
signal.addEventListener('abort', aborted, { once: true });
|
||||
});
|
||||
|
||||
/** Whether a resource's template values name one tile. */
|
||||
const isTile = (values) =>
|
||||
Number.isInteger(values?.x) &&
|
||||
Number.isInteger(values?.y) &&
|
||||
Number.isInteger(values?.z);
|
||||
|
||||
/**
|
||||
* A Cesium `Resource` whose tile fetches go through `fetchTile`.
|
||||
*
|
||||
* `tileOf` gives the tile, in the terrain's own tiling scheme (rows from
|
||||
* the north, as `requestTileGeometry` counts them), that a Cesium request
|
||||
* is for; without one it is read from the resolved template values.
|
||||
* @param {object} options Cesium `Resource` options.
|
||||
* @param {(request: {tile: import('../contract/globe').TileRequest,
|
||||
* url: string, signal: AbortSignal})
|
||||
* => Promise<import('../contract/globe').TileFetch>} fetchTile
|
||||
* @param {(request: object|undefined) => import('../contract/globe').TileRequest|undefined} tileOf
|
||||
* @param {{retryDelayMs?: number}} [timing]
|
||||
* @returns {object} A Cesium `Resource`.
|
||||
*/
|
||||
export function tileFetchResource(options, fetchTile, tileOf, timing = {}) {
|
||||
const retryDelayMs = timing.retryDelayMs ?? TERRAIN_RETRY_DELAY_MS;
|
||||
|
||||
class TileFetchResource extends Cesium.Resource {
|
||||
/**
|
||||
* Clones stay of this kind, so derived tile resources keep the hook.
|
||||
* `clone(result)` copies every field onto `result`, its URL included.
|
||||
*/
|
||||
clone(result) {
|
||||
return super.clone(
|
||||
result ?? new TileFetchResource({ url: this.url, parseUrl: false }),
|
||||
);
|
||||
}
|
||||
|
||||
fetchArrayBuffer() {
|
||||
const values = this.templateValues;
|
||||
if (!isTile(values)) return super.fetchArrayBuffer();
|
||||
const request = this.request;
|
||||
const url = this.url;
|
||||
const tile = tileOf(request) ?? {
|
||||
x: values.x,
|
||||
y: values.y,
|
||||
level: values.z,
|
||||
};
|
||||
if (
|
||||
request.state === Cesium.RequestState.ISSUED ||
|
||||
request.state === Cesium.RequestState.ACTIVE
|
||||
)
|
||||
throw new Cesium.RuntimeError('The Resource is already being fetched.');
|
||||
const controller = new AbortController();
|
||||
request.url = url;
|
||||
request.state = Cesium.RequestState.UNISSUED;
|
||||
request.deferred = undefined;
|
||||
// Cesium cancels a request whose tile is no longer wanted.
|
||||
request.cancelFunction = () => controller.abort();
|
||||
request.requestFunction = async () => {
|
||||
for (;;) {
|
||||
const answer = await fetchTile({
|
||||
tile: { ...tile },
|
||||
url,
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.signal.throwIfAborted();
|
||||
if (answer?.defer) {
|
||||
await wait(retryDelayMs, controller.signal);
|
||||
continue;
|
||||
}
|
||||
if (!answer || answer.missing) throw new MissingTerrainTile();
|
||||
return answer.bytes;
|
||||
}
|
||||
};
|
||||
const promise = Cesium.RequestScheduler.request(request);
|
||||
if (!promise) return undefined;
|
||||
return promise.finally(() => {
|
||||
request.cancelFunction = undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new TileFetchResource(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* A terrain provider whose tile requests tell `tileFetchResource` which
|
||||
* tile each is for. Requests Cesium makes without a `Request` are given one.
|
||||
* @param {object} provider Cesium `CesiumTerrainProvider`.
|
||||
* @param {WeakMap<object, import('../contract/globe').TileRequest>} tiles
|
||||
* @returns {object} The same provider.
|
||||
*/
|
||||
export function trackTileRequests(provider, tiles) {
|
||||
const own = provider.requestTileGeometry.bind(provider);
|
||||
provider.requestTileGeometry = (x, y, level, request) => {
|
||||
const asked = request ?? new Cesium.Request({ throttle: false });
|
||||
tiles.set(asked, { x, y, level });
|
||||
return own(x, y, level, asked);
|
||||
};
|
||||
return provider;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
MissingTerrainTile,
|
||||
tileFetchResource,
|
||||
trackTileRequests,
|
||||
} from './terrainTiles.js';
|
||||
|
||||
const ROOT = 'https://terrain.invalid/mesh/';
|
||||
const LAYER = JSON.stringify({
|
||||
tilejson: '2.1.0',
|
||||
format: 'quantized-mesh-1.0',
|
||||
version: '1.0.0',
|
||||
scheme: 'tms',
|
||||
tiles: ['{z}/{x}/{y}.terrain?v={version}'],
|
||||
projection: 'EPSG:4326',
|
||||
bounds: [-180, -90, 180, 90],
|
||||
minzoom: 0,
|
||||
maxzoom: 2,
|
||||
available: [
|
||||
[{ startX: 0, startY: 0, endX: 1, endY: 0 }],
|
||||
[{ startX: 0, startY: 0, endX: 3, endY: 1 }],
|
||||
[{ startX: 0, startY: 0, endX: 7, endY: 3 }],
|
||||
],
|
||||
});
|
||||
|
||||
/** One triangle over the tile: the smallest mesh Cesium decodes. */
|
||||
function meshBytes() {
|
||||
const view = new DataView(new ArrayBuffer(160));
|
||||
let at = 88; // centre, heights, bounding sphere, horizon point: all zero
|
||||
view.setFloat64(24 + 8 + 24, 1, true); // bounding sphere radius
|
||||
const u32 = (v) => (view.setUint32(at, v, true), (at += 4));
|
||||
const u16 = (v) => (view.setUint16(at, v, true), (at += 2));
|
||||
u32(3);
|
||||
// Zig-zag deltas of u (0, 32767, 0), v (0, 0, 32767) and h (0, 0, 0).
|
||||
[0, 65534, 65533, 0, 0, 65534, 0, 0, 0].forEach(u16);
|
||||
u32(1);
|
||||
[0, 0, 0].forEach(u16); // high-water-mark indices 0, 1, 2
|
||||
(u32(2), u16(0), u16(2)); // west
|
||||
(u32(2), u16(0), u16(1)); // south
|
||||
(u32(1), u16(1)); // east
|
||||
(u32(1), u16(2)); // north
|
||||
return view.buffer.slice(0, at);
|
||||
}
|
||||
|
||||
/** Answers `layer.json` the way a host would; tiles never reach the network. */
|
||||
function serveLayer(t) {
|
||||
const fetched = [];
|
||||
t.mock.method(
|
||||
Cesium.Resource._Implementations,
|
||||
'loadWithXhr',
|
||||
(url, responseType, method, data, headers, deferred) => {
|
||||
fetched.push(url);
|
||||
if (url.startsWith(`${ROOT}layer.json`)) deferred.resolve(LAYER);
|
||||
else deferred.reject(new Error(`unexpected fetch ${url}`));
|
||||
},
|
||||
);
|
||||
return fetched;
|
||||
}
|
||||
|
||||
async function terrain(fetchTile, timing) {
|
||||
const tiles = new WeakMap();
|
||||
const resource = tileFetchResource(
|
||||
{ url: ROOT },
|
||||
fetchTile,
|
||||
(request) => (request ? tiles.get(request) : undefined),
|
||||
timing,
|
||||
);
|
||||
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestWaterMask: false,
|
||||
});
|
||||
return trackTileRequests(provider, tiles);
|
||||
}
|
||||
|
||||
test('terrain fetchTile: tiles come from fetchTile, layer.json from the url', async (t) => {
|
||||
const fetched = serveLayer(t);
|
||||
const asked = [];
|
||||
const provider = await terrain(async (request) => {
|
||||
asked.push(request);
|
||||
return { bytes: meshBytes() };
|
||||
});
|
||||
const data = await provider.requestTileGeometry(
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
new Cesium.Request(),
|
||||
);
|
||||
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
|
||||
assert.deepEqual(
|
||||
fetched.map((u) => new URL(u).pathname),
|
||||
['/mesh/layer.json'],
|
||||
);
|
||||
assert.equal(asked.length, 1);
|
||||
// Rows from the north for the tile; the URL is Cesium's, rows from the
|
||||
// south as the layer's tms scheme counts them.
|
||||
assert.deepEqual(asked[0].tile, { x: 1, y: 0, level: 1 });
|
||||
assert.equal(asked[0].url, `${ROOT}1/1/1.terrain?v=1.0.0`);
|
||||
assert.ok(asked[0].signal instanceof AbortSignal);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a request Cesium makes without a Request still names its tile', async (t) => {
|
||||
serveLayer(t);
|
||||
const asked = [];
|
||||
const provider = await terrain(async (request) => {
|
||||
asked.push(request.tile);
|
||||
return { bytes: meshBytes() };
|
||||
});
|
||||
await provider.requestTileGeometry(3, 1, 2);
|
||||
assert.deepEqual(asked, [{ x: 3, y: 1, level: 2 }]);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a missing tile fails, so the parent is drawn there', async (t) => {
|
||||
serveLayer(t);
|
||||
const provider = await terrain(async () => ({ missing: true }));
|
||||
await assert.rejects(
|
||||
provider.requestTileGeometry(0, 0, 0, new Cesium.Request()),
|
||||
MissingTerrainTile,
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a deferred tile is asked for again', async (t) => {
|
||||
serveLayer(t);
|
||||
let calls = 0;
|
||||
const provider = await terrain(
|
||||
async () => (++calls < 3 ? { defer: true } : { bytes: meshBytes() }),
|
||||
{ retryDelayMs: 1 },
|
||||
);
|
||||
const data = await provider.requestTileGeometry(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
new Cesium.Request(),
|
||||
);
|
||||
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: cancelling the request aborts the fetch', async (t) => {
|
||||
serveLayer(t);
|
||||
let signal;
|
||||
const provider = await terrain(
|
||||
(request) =>
|
||||
new Promise((resolve, reject) => {
|
||||
signal = request.signal;
|
||||
signal.addEventListener('abort', () => reject(signal.reason));
|
||||
}),
|
||||
);
|
||||
const request = new Cesium.Request();
|
||||
const pending = provider.requestTileGeometry(0, 0, 0, request);
|
||||
pending.catch(() => {});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(signal.aborted, false);
|
||||
request.cancel();
|
||||
// Cesium's scheduler cancels on its next update.
|
||||
Cesium.RequestScheduler.update();
|
||||
assert.equal(signal.aborted, true);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: resources that are not tiles fetch as before', async (t) => {
|
||||
const fetched = serveLayer(t);
|
||||
const resource = tileFetchResource(
|
||||
{ url: ROOT },
|
||||
async () => assert.fail('not a tile'),
|
||||
() => undefined,
|
||||
);
|
||||
const derived = resource.getDerivedResource({ url: 'layer.json' });
|
||||
assert.equal(derived.constructor, resource.constructor);
|
||||
assert.equal(await derived.fetchArrayBuffer(), LAYER);
|
||||
assert.equal(fetched.length, 1);
|
||||
});
|
||||
@@ -3453,6 +3453,379 @@ export function portChecks() {
|
||||
}
|
||||
},
|
||||
),
|
||||
check(
|
||||
'draw.lines.ageFade',
|
||||
'a line, draped or not, fades with the age of its points as scene time moves on, without being sent again',
|
||||
async (h, r) => {
|
||||
if (h.pixels === false)
|
||||
return { skip: 'this harness reads no drawn pixels' };
|
||||
await overAustin(h, r);
|
||||
const t0 = Date.UTC(2026, 0, 1, 18);
|
||||
r.frame.setTime(t0);
|
||||
// Off the row under the camera, where a ground line can leave a gap.
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-age-fade' });
|
||||
const line = (id, dLat, mode) => ({
|
||||
id,
|
||||
positions: [
|
||||
at(-0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
at(0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
// Its west end a minute old at t0, its east end new.
|
||||
ageFade: {
|
||||
times: [t0 - 60_000, t0],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 0,
|
||||
},
|
||||
});
|
||||
// Unfaded but narrowed to a quarter of its width where it is old.
|
||||
const narrowed = {
|
||||
...line('narrowed', 0.0035, '3d'),
|
||||
ageFade: {
|
||||
times: [t0 - 60_000, t0],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
widthFloor: 0.25,
|
||||
},
|
||||
};
|
||||
lines.set([
|
||||
line('air', 0.002, '3d'),
|
||||
line('ground', -0.002, 'draped'),
|
||||
narrowed,
|
||||
]);
|
||||
// Whether the line at `dLon` is drawn green there, strongly, `dy`
|
||||
// pixels off its middle.
|
||||
const green = (dLon, dLat, dy = 0) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y) + dy,
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, g, blue] = image.data;
|
||||
return g > red + 80 && g > blue + 80;
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(0.0035, dLat), `${what}: its new end drawn`);
|
||||
ok(!green(-0.0035, dLat), `${what}: its old end faded`);
|
||||
}
|
||||
ok(green(-0.0035, 0.0035), 'narrowed: its old end drawn, unfaded');
|
||||
ok(green(0.0035, 0.0035, 6), 'narrowed: its new end full width');
|
||||
ok(
|
||||
!green(-0.0035, 0.0035, 6),
|
||||
'narrowed: its old end a quarter as wide',
|
||||
);
|
||||
// Two minutes on, all of it is old; back at t0 its new end is new.
|
||||
r.frame.setTime(t0 + 120_000);
|
||||
await drawn(h, r);
|
||||
ok(!green(0.0035, 0.002), '3d: faded as time moved on');
|
||||
ok(!green(0.0035, -0.002), 'draped: faded as time moved on');
|
||||
r.frame.setTime(t0);
|
||||
await drawn(h, r);
|
||||
ok(green(0.0035, 0.002), '3d: new again back at t0');
|
||||
ok(green(0.0035, -0.002), 'draped: new again back at t0');
|
||||
equal(lines.size(), 3, 'never sent again');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineAgeFade' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.timeWindow',
|
||||
'a line, draped or not, draws only its part within a span of scene time, cut as the time moves on, without being sent again',
|
||||
async (h, r) => {
|
||||
if (h.pixels === false)
|
||||
return { skip: 'this harness reads no drawn pixels' };
|
||||
await overAustin(h, r);
|
||||
const t0 = Date.UTC(2026, 0, 1, 18);
|
||||
r.frame.setTime(t0);
|
||||
// Off the row under the camera, where a ground line can leave a gap.
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-time-window' });
|
||||
// West to east over two minutes, t0 at its middle; shown over the
|
||||
// last 30 s, unfaded.
|
||||
const line = (id, dLat, mode) => ({
|
||||
id,
|
||||
positions: [
|
||||
at(-0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
at(0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
ageFade: {
|
||||
times: [t0 - 60_000, t0 + 60_000],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
showMs: 30_000,
|
||||
},
|
||||
});
|
||||
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
|
||||
// Whether the line at `dLon` is drawn green there, strongly.
|
||||
const green = (dLon, dLat) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, g, blue] = image.data;
|
||||
return g > red + 80 && g > blue + 80;
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
// At t0 it shows from 30 s ago (a quarter along) to now (half).
|
||||
ok(green(-0.001, dLat), `${what}: drawn within the span`);
|
||||
ok(!green(0.002, dLat), `${what}: not drawn after now`);
|
||||
ok(!green(-0.0035, dLat), `${what}: not drawn before the span`);
|
||||
}
|
||||
// 40 s on, it shows from 10 s to 40 s after t0.
|
||||
r.frame.setTime(t0 + 40_000);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(0.002, dLat), `${what}: drawn where now reached`);
|
||||
ok(!green(-0.001, dLat), `${what}: cut as it grew old`);
|
||||
}
|
||||
r.frame.setTime(t0);
|
||||
await drawn(h, r);
|
||||
ok(green(-0.001, 0.002), '3d: drawn again back at t0');
|
||||
ok(!green(0.002, -0.002), 'draped: cut again back at t0');
|
||||
equal(lines.size(), 2, 'never sent again');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineTimeWindow' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.breaks',
|
||||
'a line in runs, draped or not, draws and picks each run, in its segment colours, and nothing between them',
|
||||
async (h, r) => {
|
||||
await overAustin(h, r);
|
||||
// Off the row under the camera, where a ground line can leave a gap.
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-breaks' });
|
||||
// Two runs, west and east, the second starting at position 2: the
|
||||
// pair from position 1 to 2, across the break, is not drawn.
|
||||
const lons = [-0.004, -0.002, 0.001, 0.004];
|
||||
const line = (id, dLat, mode, segmentColors) => ({
|
||||
id,
|
||||
positions: lons.map((dLon) =>
|
||||
at(dLon, dLat, mode === 'draped' ? 0 : 20),
|
||||
),
|
||||
breaks: [2],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
...(segmentColors
|
||||
? {
|
||||
// The pair across the break has a colour, ignored.
|
||||
segmentColors: [
|
||||
[1, 0, 0, 1],
|
||||
[0, 1, 0, 1],
|
||||
[0, 0, 1, 1],
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const kinds = [
|
||||
['3d', 0.003, false],
|
||||
['draped', 0.001, false],
|
||||
['3d coloured', -0.001, true],
|
||||
['draped coloured', -0.003, true],
|
||||
];
|
||||
const lat = new Map(kinds.map(([what, dLat]) => [what, dLat]));
|
||||
lines.set(
|
||||
kinds.map(([what, dLat, coloured]) =>
|
||||
line(
|
||||
what,
|
||||
dLat,
|
||||
what.startsWith('draped') ? 'draped' : '3d',
|
||||
coloured,
|
||||
),
|
||||
),
|
||||
);
|
||||
const where = (what, dLon) =>
|
||||
at(dLon, lat.get(what), what.startsWith('draped') ? 0 : 20);
|
||||
// The colour drawn there, strongly: 'r', 'g', 'b', or null.
|
||||
const colour = (what, dLon) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(where(what, dLon));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, green, blue] = image.data;
|
||||
if (red > green + 80 && red > blue + 80) return 'r';
|
||||
if (green > red + 80 && green > blue + 80) return 'g';
|
||||
if (blue > red + 80 && blue > green + 80) return 'b';
|
||||
return null;
|
||||
};
|
||||
const picked = (what, dLon) => {
|
||||
const s = r.query.project(where(what, dLon));
|
||||
ok(s, `${what} projects`);
|
||||
return r.query
|
||||
.drillPick(s.x, s.y)
|
||||
.filter((hit) => hit.set === 'conf:line-breaks')
|
||||
.map((hit) => hit.id);
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, , coloured] of kinds) {
|
||||
deepEqual(
|
||||
picked(what, -0.003),
|
||||
[what],
|
||||
`${what}: its first run picks`,
|
||||
);
|
||||
deepEqual(
|
||||
picked(what, -0.0005),
|
||||
[],
|
||||
`${what}: nothing between its runs`,
|
||||
);
|
||||
deepEqual(
|
||||
picked(what, 0.0025),
|
||||
[what],
|
||||
`${what}: its second run picks`,
|
||||
);
|
||||
if (h.pixels === false) continue;
|
||||
equal(
|
||||
colour(what, -0.003),
|
||||
coloured ? 'r' : 'g',
|
||||
`${what}: its first run drawn`,
|
||||
);
|
||||
equal(
|
||||
colour(what, -0.0005),
|
||||
null,
|
||||
`${what}: nothing drawn between its runs`,
|
||||
);
|
||||
equal(
|
||||
colour(what, 0.0025),
|
||||
coloured ? 'b' : 'g',
|
||||
`${what}: its second run drawn`,
|
||||
);
|
||||
}
|
||||
equal(lines.size(), kinds.length, 'one item a line');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineBreaks' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.breaks.timeWindow',
|
||||
'a line in runs, draped or not, whose first run is later than its second, cuts each run by its own times',
|
||||
async (h, r) => {
|
||||
if (!r.capabilities.has('lineBreaks'))
|
||||
return { skip: 'the renderer draws no lines in runs' };
|
||||
if (h.pixels === false)
|
||||
return { skip: 'this harness reads no drawn pixels' };
|
||||
await overAustin(h, r);
|
||||
const t0 = Date.UTC(2026, 0, 1, 18);
|
||||
r.frame.setTime(t0);
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-breaks-window' });
|
||||
// Its first run, west, the last ten seconds to t0; its second, east,
|
||||
// two minutes before.
|
||||
const line = (id, dLat, mode) => ({
|
||||
id,
|
||||
positions: [-0.004, -0.001, 0.001, 0.004].map((dLon) =>
|
||||
at(dLon, dLat, mode === 'draped' ? 0 : 20),
|
||||
),
|
||||
breaks: [2],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
ageFade: {
|
||||
times: [t0 - 10_000, t0, t0 - 120_000, t0 - 110_000],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
showMs: 30_000,
|
||||
},
|
||||
});
|
||||
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
|
||||
const green = (dLon, dLat) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, g, blue] = image.data;
|
||||
return g > red + 80 && g > blue + 80;
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(-0.0025, dLat), `${what}: its later run drawn at t0`);
|
||||
ok(!green(0.0025, dLat), `${what}: its earlier run too old at t0`);
|
||||
ok(!green(0, dLat), `${what}: nothing between its runs`);
|
||||
}
|
||||
// 105 s before t0 the second run is within the span, the first
|
||||
// not yet begun.
|
||||
r.frame.setTime(t0 - 105_000);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(0.0025, dLat), `${what}: its earlier run drawn then`);
|
||||
ok(!green(-0.0025, dLat), `${what}: its later run not yet drawn`);
|
||||
ok(!green(0, dLat), `${what}: still nothing between its runs`);
|
||||
}
|
||||
equal(lines.size(), 2, 'never sent again');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineTimeWindow' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.segments',
|
||||
'a draped line takes segment colours and shows, changed every frame in place, without stopping the frame or picks',
|
||||
|
||||
Vendored
+9
@@ -234,6 +234,15 @@ export type CameraEvent =
|
||||
'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd';
|
||||
|
||||
export interface CameraPort {
|
||||
/**
|
||||
* Whether any of the ECEF points may be on screen: false only when their
|
||||
* bounding sphere is outside the view or all of them are below the horizon
|
||||
* of WGS84 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), which callers treat as visible. Supply a finite, nonnegative
|
||||
* margin smaller than the shortest WGS84 radius.
|
||||
*/
|
||||
visiblePoints?(points: Ecef[], horizonMarginM: number): boolean | null;
|
||||
pose(): CameraPose;
|
||||
/**
|
||||
* Place the eye. A position with a `{direction, up}` orientation is placed
|
||||
|
||||
Vendored
+8
@@ -183,6 +183,8 @@ export type Capability =
|
||||
| 'pickPosition'
|
||||
/** Points tested against the frame's depth (`query.occlusionTest`). */
|
||||
| 'occlusionTest'
|
||||
/** Conservative camera visibility of a point set (`camera.visiblePoints`). */
|
||||
| 'pointVisibility'
|
||||
/** Outward user zooms that keep the Earth framed (`controls.keepEarthFramed`). */
|
||||
| 'keepEarthFramed'
|
||||
/** Height sampling against tiles and terrain. */
|
||||
@@ -205,6 +207,12 @@ export type Capability =
|
||||
| 'fields'
|
||||
/** Rate-limited course easing (`IconItem.courseGlide`). */
|
||||
| 'courseGlide'
|
||||
/** Lines that fade with the age of their points (`LineItem.ageFade`). */
|
||||
| 'lineAgeFade'
|
||||
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
|
||||
| 'lineTimeWindow'
|
||||
/** Lines drawn as several runs, not joined across their breaks (`LineItem.breaks`). */
|
||||
| 'lineBreaks'
|
||||
/** Screen-space clustering of icons. */
|
||||
| 'cluster'
|
||||
/** Post-processing styles. */
|
||||
|
||||
Vendored
+66
@@ -295,10 +295,74 @@ export type LineStyle =
|
||||
rim?: { shade: number; widthFraction: number };
|
||||
};
|
||||
|
||||
/**
|
||||
* `lineAgeFade`: a line that fades with the age of its points, drawn by the
|
||||
* renderer on the scene clock (`frame.setTime`), so a line whose points stay
|
||||
* where they are is not sent again as time passes. A point's recency is
|
||||
* `1 - clamp((now - time) / windowMs, 0, 1)`, its time running evenly
|
||||
* between neighbouring positions, so the fade is smooth along the line, not
|
||||
* stepped at its points. The line's colour (its style's, or a segment's from
|
||||
* `segmentColors`) draws at its alpha times
|
||||
* `mix(alphaFloor, 1, smoothstep(0, 1, recency))`, and with
|
||||
* `squaredAlphaFloor` times `mix(squaredAlphaFloor, 1, recency²)` as well;
|
||||
* with `widthFloor` it draws `widthPx` times `mix(widthFloor, 1, recency)`
|
||||
* wide, about its path. A point at or past the window draws at the floors, a
|
||||
* point at or after now at full strength. New `times` with new positions are
|
||||
* an ordinary update.
|
||||
*
|
||||
* `lineTimeWindow`: with `showMs`, only the part of the line within `showMs`
|
||||
* of now is drawn, cut along it where its interpolated time crosses: parts
|
||||
* whose time is after now, or before `now - showMs`, are not drawn (nor
|
||||
* picked). The cut follows the scene clock as the fade does, so a moving
|
||||
* object's trail can be its whole track, sent once: drawn from `showMs` ago
|
||||
* up to where the object is now. A renderer without the capability ignores
|
||||
* `showMs` and draws the whole line.
|
||||
*/
|
||||
export interface LineAgeFade {
|
||||
/** Each position's time, epoch ms on the scene clock: one per position. */
|
||||
times: number[] | Float64Array;
|
||||
/** The age a point fades over, ms; positive. */
|
||||
windowMs: number;
|
||||
/** A fully aged point's alpha multiplier, 0..1. */
|
||||
alphaFloor: number;
|
||||
/** A second alpha multiplier's floor, eased by recency squared, 0..1. */
|
||||
squaredAlphaFloor?: number;
|
||||
/** A fully aged point's width multiplier, 0..1 [1, no narrowing]. */
|
||||
widthFloor?: number;
|
||||
/**
|
||||
* `lineTimeWindow`: draw only the part of the line from `showMs` before
|
||||
* now up to now, ms; positive (`Infinity`: up to now, however old).
|
||||
* [absent: the whole line]
|
||||
*/
|
||||
showMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `lineBreaks`: a line drawn as several runs, so many lines in one style can
|
||||
* be one item (thousands of moving objects' trails sent as one line, say),
|
||||
* and the renderer handles one item instead of thousands. Each break is the
|
||||
* index `i` of a position that starts a new run (`0 < i < positions.length`,
|
||||
* strictly increasing): the segment from position `i - 1` to `i` is not
|
||||
* drawn (nor picked), and the line does not join across it, each run having
|
||||
* 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 a pair across a break
|
||||
* has an entry that is ignored; `ageFade.times` stays one a position; and
|
||||
* `revealFraction` runs along the runs, in order, as one length (the gaps
|
||||
* between them have none). A renderer without the capability is never sent
|
||||
* `breaks`: its lines are sent one item a run instead.
|
||||
*/
|
||||
export type LineBreaks = number[] | Uint32Array;
|
||||
|
||||
export interface LineItem {
|
||||
id: string;
|
||||
/** ECEF positions, or packed `x, y, z` triples. */
|
||||
positions: Ecef[] | Float64Array;
|
||||
/**
|
||||
* `lineBreaks`: the positions that start a new run of the line
|
||||
* (`LineBreaks`). [absent or empty: one run]
|
||||
*/
|
||||
breaks?: LineBreaks;
|
||||
widthPx: number;
|
||||
/**
|
||||
* `3d`: straight in space; `geodesic`: along the ellipsoid; `draped`: on
|
||||
@@ -321,6 +385,8 @@ export interface LineItem {
|
||||
segmentShow?: boolean[];
|
||||
/** Draw only the first fraction of the line, 0..1. */
|
||||
revealFraction?: number;
|
||||
/** `lineAgeFade`: fade the line with the age of its points (`LineAgeFade`). */
|
||||
ageFade?: LineAgeFade;
|
||||
/** Positions are in a frame rotating with the sky (orbits). */
|
||||
frame?: 'fixed' | 'inertial';
|
||||
meta?: Meta;
|
||||
|
||||
Vendored
+18
-1
@@ -40,7 +40,24 @@ export type TerrainSpec = (
|
||||
* Quantized-mesh terrain (Cesium's tile format) in the folder `url`,
|
||||
* holding `layer.json` and its tiles; heights above the ellipsoid.
|
||||
*/
|
||||
| { kind: 'quantizedMesh'; url: string; requestVertexNormals?: boolean }
|
||||
| {
|
||||
kind: 'quantizedMesh';
|
||||
url: string;
|
||||
requestVertexNormals?: boolean;
|
||||
/**
|
||||
* Fetches a tile in place of the renderer, as imagery's `fetchTile`
|
||||
* does, with the tile's URL as the renderer resolved it (`layer.json`
|
||||
* is still read from `url`). `tile` is in the terrain's tiling scheme,
|
||||
* rows counted from the north; `bytes` are the tile uncompressed.
|
||||
* `missing` draws the parent tile's terrain there; `defer` asks
|
||||
* again shortly. `signal` aborts when the tile is no longer wanted.
|
||||
*/
|
||||
fetchTile?: (request: {
|
||||
tile: TileRequest;
|
||||
url: string;
|
||||
signal: AbortSignal;
|
||||
}) => Promise<TileFetch>;
|
||||
}
|
||||
) & {
|
||||
/** Vertical exaggeration of the drawn terrain; default 1. */
|
||||
exaggeration?: number;
|
||||
|
||||
@@ -41,6 +41,9 @@ export const CAPABILITIES = Object.freeze([
|
||||
'meshes',
|
||||
'fields',
|
||||
'courseGlide',
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
'lineBreaks',
|
||||
'cluster',
|
||||
'styles',
|
||||
'bloom',
|
||||
@@ -50,6 +53,7 @@ export const CAPABILITIES = Object.freeze([
|
||||
'followFrame',
|
||||
'cameraChangeThreshold',
|
||||
'occlusionTest',
|
||||
'pointVisibility',
|
||||
'keepEarthFramed',
|
||||
]);
|
||||
|
||||
@@ -209,6 +213,7 @@ export const PORTS = deepFreeze({
|
||||
'matrices',
|
||||
),
|
||||
['followFrame', 'followFrame'],
|
||||
['visiblePoints', 'pointVisibility'],
|
||||
['controls.keepEarthFramed', 'keepEarthFramed'],
|
||||
]),
|
||||
query: Object.fromEntries([
|
||||
|
||||
@@ -262,6 +262,8 @@ export function createStubRenderer(options = {}) {
|
||||
camera.setViewRectangle(viewRectangle);
|
||||
if (capabilities.has('followFrame'))
|
||||
camera.port.followFrame = camera.eyeFrame;
|
||||
if (capabilities.has('pointVisibility'))
|
||||
camera.port.visiblePoints = () => null;
|
||||
camera.port.setView({
|
||||
destination: { lon: -97.7431, lat: 30.2672, height: 15000000 },
|
||||
});
|
||||
@@ -1328,9 +1330,19 @@ export function createStubRenderer(options = {}) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The positions that start a run of a line in runs (`lineBreaks`), or
|
||||
* null: nothing is drawn between two runs.
|
||||
*/
|
||||
const runStarts = (item) =>
|
||||
capabilities.has('lineBreaks') && item.breaks?.length
|
||||
? new Set(item.breaks)
|
||||
: null;
|
||||
|
||||
/**
|
||||
* A line's positions as ECEF, cut at its `revealFraction` of length (as
|
||||
* drawn straight between its positions).
|
||||
* drawn straight between its positions, along its runs, the gaps between
|
||||
* them having none).
|
||||
*/
|
||||
function revealedLine(item) {
|
||||
const flat = item.positions instanceof Float64Array;
|
||||
@@ -1348,7 +1360,10 @@ export function createStubRenderer(options = {}) {
|
||||
);
|
||||
const fraction = item.revealFraction;
|
||||
if (fraction === undefined || fraction >= 1) return points;
|
||||
const at = alongLength(points, fraction);
|
||||
const starts = runStarts(item);
|
||||
const at = starts
|
||||
? alongRuns(points, starts, fraction)
|
||||
: alongLength(points, fraction);
|
||||
if (!at) return [];
|
||||
const { index, t } = at;
|
||||
return [
|
||||
@@ -1357,17 +1372,43 @@ export function createStubRenderer(options = {}) {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* `alongLength` for a line in runs: the segment a fraction of its runs'
|
||||
* length ends on, and how far along it, the segments between runs
|
||||
* measuring nothing.
|
||||
*/
|
||||
function alongRuns(points, starts, fraction) {
|
||||
if (!(fraction > 0) || points.length < 2) return null;
|
||||
const lengths = [];
|
||||
for (let i = 0; i + 1 < points.length; i++)
|
||||
lengths.push(
|
||||
starts.has(i + 1) ? 0 : magnitude(sub(points[i + 1], points[i])),
|
||||
);
|
||||
const total = lengths.reduce((sum, length) => sum + length, 0);
|
||||
if (!(total > 0)) return null;
|
||||
let left = fraction * total;
|
||||
for (let i = 0; i < lengths.length; i++) {
|
||||
if (lengths[i] > 0 && left <= lengths[i])
|
||||
return { index: i, t: left / lengths[i] };
|
||||
left -= lengths[i];
|
||||
}
|
||||
return { index: lengths.length - 1, t: 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a line is under the pixel `(x, y)`: the nearest point of a
|
||||
* drawn segment within half its width (and `slack`) of it, or null.
|
||||
*/
|
||||
function lineHit(item, x, y, slack) {
|
||||
const points = revealedLine(item);
|
||||
const starts = runStarts(item);
|
||||
const reach = (item.widthPx ?? 1) / 2 + slack;
|
||||
let best = null;
|
||||
let bestDistance = Infinity;
|
||||
for (let i = 0; i + 1 < points.length; i++) {
|
||||
if (item.segmentShow?.[i] === false) continue;
|
||||
// Nothing is drawn between two runs.
|
||||
if (starts?.has(i + 1)) continue;
|
||||
const a = points[i];
|
||||
const b = points[i + 1];
|
||||
if (isOccluded(a) && isOccluded(b)) continue;
|
||||
|
||||
@@ -20,7 +20,7 @@ test('the stub passes the conformance suite', async () => {
|
||||
.filter((r) => r.status === 'skip')
|
||||
.map((r) => r.id);
|
||||
// It draws only models into pixels, so the sweep's, a lit shape's, a line outline's, a
|
||||
// split line's, a draped outlined line's and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
|
||||
// split line's, a draped outlined line's, an aged line's, a time-windowed line's (in runs too) and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
|
||||
// camera that does (a controller over it, say).
|
||||
assert.deepEqual(skipped, [
|
||||
'effects.screenModulation.pixels',
|
||||
@@ -29,6 +29,9 @@ test('the stub passes the conformance suite', async () => {
|
||||
'draw.sets.blend',
|
||||
'draw.lines.split',
|
||||
'draw.lines.outlineDraped',
|
||||
'draw.lines.ageFade',
|
||||
'draw.lines.timeWindow',
|
||||
'draw.lines.breaks.timeWindow',
|
||||
'draw.models.blend',
|
||||
'draw.models.paint',
|
||||
'globe.imagery.video',
|
||||
@@ -40,6 +43,15 @@ test('the stub passes the conformance suite', async () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('point visibility capability is optional and the stub reports unknown', () => {
|
||||
const without = createStubRenderer({ capabilities: [] });
|
||||
const withVisibility = createStubRenderer({
|
||||
capabilities: ['pointVisibility'],
|
||||
});
|
||||
assert.equal(without.camera.visiblePoints, undefined);
|
||||
assert.equal(withVisibility.camera.visiblePoints([], 200), null);
|
||||
});
|
||||
|
||||
test('a frame runs the contract’s steps in order', () => {
|
||||
const r = createStubRenderer();
|
||||
r.frame.requestRender('test');
|
||||
|
||||
@@ -2150,50 +2150,6 @@ test('a hold resumed partway waits for a clip that starts again, else only its r
|
||||
assert.deepEqual(await hold(0), [2000]);
|
||||
});
|
||||
|
||||
/** Drive frame-by-frame camera motion headlessly for one test. */
|
||||
function installAnimationFrames() {
|
||||
const original = globalThis.requestAnimationFrame;
|
||||
const originalCancel = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => setTimeout(callback, 16);
|
||||
globalThis.cancelAnimationFrame = (handle) => clearTimeout(handle);
|
||||
return () => {
|
||||
globalThis.requestAnimationFrame = original;
|
||||
globalThis.cancelAnimationFrame = originalCancel;
|
||||
};
|
||||
}
|
||||
|
||||
test('a run resumed inside a flight goes on from that point of the path and clock', async () => {
|
||||
const { director, viewer, restore } = makeDirector();
|
||||
const restoreFrames = installAnimationFrames();
|
||||
const clock = [];
|
||||
director.subscribeSceneClock((snap) => clock.push(snap));
|
||||
const poses = [];
|
||||
const setView = director._setCameraView.bind(director);
|
||||
director._setCameraView = (pose) => {
|
||||
poses.push(pose);
|
||||
return setView(pose);
|
||||
};
|
||||
try {
|
||||
// 0.75 of a 0.4 s scene: halfway along shot B's 0.2 s flight.
|
||||
const run = director.startScene('scene-1', {
|
||||
single: true,
|
||||
fromProgress: 0.75,
|
||||
preview: false,
|
||||
});
|
||||
await settle(40);
|
||||
const first = clock.find((snap) => snap.running);
|
||||
assert.equal(first.shotId, 'shot-b', 'starts in the shot that moment is in');
|
||||
assert.ok(Math.abs(first.sceneElapsedSec - 0.3) < 1e-9, 'the clock starts at the moment');
|
||||
// The first frame is the seek's own framing, halfway from A to B.
|
||||
assert.ok(poses.length, 'the camera is driven from where it is');
|
||||
assert.ok(Math.abs(poses[0].lat - -10) < 0.5, 'halfway from A to B');
|
||||
assert.deepEqual(await run, { started: true, shots: 1 });
|
||||
assert.equal(poses.at(-1).lat, -30, 'and ends on shot B');
|
||||
assert.equal(viewer.flights.length, 0, 'no fresh flight from the shot start');
|
||||
assert.equal(director._lastRun.wasCancelled, false);
|
||||
} finally { await director.destroy(); restoreFrames(); restore(); }
|
||||
});
|
||||
|
||||
test('a run resumed inside a hold plays its layers on from the seek’s state and waits only the rest of it', async () => {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes[0].shots[0].holdSec = 0.6;
|
||||
|
||||
@@ -173,7 +173,8 @@ export const getCyclones = defineTool({
|
||||
title: 'Tropical cyclones',
|
||||
description:
|
||||
'Active tropical cyclones from the NOAA National Hurricane Center and ' +
|
||||
'Central Pacific Hurricane Center, optionally limited to an area.',
|
||||
'Central Pacific Hurricane Center, and from the Joint Typhoon Warning ' +
|
||||
'Center elsewhere, optionally limited to an area.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { area: AREA_SCHEMA },
|
||||
@@ -204,6 +205,7 @@ export const getCyclones = defineTool({
|
||||
name: storm.name,
|
||||
classification: storm.classification,
|
||||
basin: storm.basin,
|
||||
agency: storm.agency ?? 'nhc',
|
||||
lat: storm.position.latitude,
|
||||
lon: storm.position.longitude,
|
||||
position_at: storm.positionAt,
|
||||
@@ -248,8 +250,7 @@ export const getFirePerimeters = defineTool({
|
||||
title: 'Wildfire perimeters',
|
||||
description:
|
||||
'Mapped wildfire perimeters from the US WFIGS service in an area, ' +
|
||||
'largest first, with size, containment, cause, personnel and when ' +
|
||||
'each last grew.',
|
||||
'largest first, with size, containment, cause and personnel.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { area: AREA_SCHEMA, limit: LIMIT_SCHEMA },
|
||||
@@ -259,27 +260,19 @@ export const getFirePerimeters = defineTool({
|
||||
requires: ['perimeters'],
|
||||
async run(args, { services, signal }) {
|
||||
const area = await resolveArea(args.area, { services, signal });
|
||||
const snapshot = await services.perimeters.getSnapshot({ signal });
|
||||
const snapshot =
|
||||
typeof services.perimeters.getSnapshotDetail === 'function'
|
||||
? await services.perimeters.getSnapshotDetail({ signal })
|
||||
: { rows: await services.perimeters.getSnapshot({ signal }) };
|
||||
// The proxy answers from its last snapshot, marked stale, while WFIGS is
|
||||
// unreachable.
|
||||
const stale = snapshot.stale === true;
|
||||
// A fire is in the area when a piece of its burned area is.
|
||||
const touching = new Set();
|
||||
for (const piece of snapshot.pieces || [])
|
||||
if (
|
||||
!touching.has(piece.fireId) &&
|
||||
polygonsTouchArea(piece.polygons, area)
|
||||
)
|
||||
touching.add(piece.fireId);
|
||||
const rows = (snapshot.fires || [])
|
||||
.filter(
|
||||
(fire) =>
|
||||
touching.has(fire.id) &&
|
||||
Number.isFinite(fire.anchor?.lat) &&
|
||||
Number.isFinite(fire.anchor?.lon),
|
||||
)
|
||||
.map((fire) => ({
|
||||
id: fire.id,
|
||||
const rows = snapshot.rows
|
||||
.filter((fire) => polygonsTouchArea(fire.polygons, area))
|
||||
.map((fire) => ({ fire, point: polygonCenter(fire.polygons) }))
|
||||
.filter(({ point }) => point)
|
||||
.map(({ fire, point }) => ({
|
||||
id: fire.stableId,
|
||||
name: fire.name,
|
||||
acres: round(fire.acres, 0),
|
||||
contained_pct: fire.containedPct,
|
||||
@@ -291,9 +284,8 @@ export const getFirePerimeters = defineTool({
|
||||
personnel: fire.personnel,
|
||||
discovered: isoTime(fire.discoveredTime),
|
||||
updated: isoTime(fire.updatedTime),
|
||||
last_growth: isoTime(fire.lastGrowthTime),
|
||||
lat: round(fire.anchor.lat, 5),
|
||||
lon: round(fire.anchor.lon, 5),
|
||||
lat: round(point.lat, 5),
|
||||
lon: round(point.lon, 5),
|
||||
}))
|
||||
.sort((a, b) => (b.acres ?? 0) - (a.acres ?? 0));
|
||||
return {
|
||||
@@ -310,6 +302,27 @@ export const getFirePerimeters = defineTool({
|
||||
},
|
||||
});
|
||||
|
||||
/** Average outer-ring vertices, using a circular longitude mean at the dateline. */
|
||||
function polygonCenter(polygons) {
|
||||
let lat = 0;
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let count = 0;
|
||||
const toRad = Math.PI / 180;
|
||||
for (const polygon of polygons || []) {
|
||||
for (const [x, y] of polygon?.[0] || []) {
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
||||
sinLon += Math.sin(x * toRad);
|
||||
cosLon += Math.cos(x * toRad);
|
||||
lat += y;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count
|
||||
? { lat: lat / count, lon: Math.atan2(sinLon, cosLon) / toRad }
|
||||
: null;
|
||||
}
|
||||
|
||||
export const getTerrainHeight = defineTool({
|
||||
name: 'get_terrain_height',
|
||||
title: 'Terrain height',
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
defineTool,
|
||||
ToolError,
|
||||
} from '../index.js';
|
||||
import { firePerimeterSnapshot } from '../../layers/perimeters/records.js';
|
||||
|
||||
const conditions = {
|
||||
observedAt: '2026-10-01T19:15:00.000Z',
|
||||
@@ -162,12 +161,11 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
[lon + 0.1, lat],
|
||||
[lon + 0.1, lat + 0.1],
|
||||
[lon, lat + 0.1],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
const perimeters = {
|
||||
async getSnapshot() {
|
||||
return firePerimeterSnapshot([
|
||||
return [
|
||||
{
|
||||
stableId: 'small',
|
||||
name: 'Small Fire',
|
||||
@@ -181,7 +179,6 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
personnel: 20,
|
||||
discoveredTime: Date.UTC(2026, 8, 1),
|
||||
updatedTime: null,
|
||||
polygonTime: Date.UTC(2026, 8, 2, 6),
|
||||
polygons: [ring(-118.5, 35.2)],
|
||||
},
|
||||
{
|
||||
@@ -198,7 +195,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
polygons: [ring(-80, 30)],
|
||||
},
|
||||
{ stableId: 'empty', name: 'No Outline', acres: 1, polygons: [] },
|
||||
]);
|
||||
];
|
||||
},
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
@@ -225,7 +222,6 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
personnel: 20,
|
||||
discovered: '2026-09-01T00:00:00.000Z',
|
||||
updated: null,
|
||||
last_growth: '2026-09-02T06:00:00.000Z',
|
||||
lat: 35.25,
|
||||
lon: -118.45,
|
||||
});
|
||||
@@ -233,25 +229,24 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
|
||||
test('fire perimeter queries include dateline interiors and exclude the opposite meridian', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const catalog = catalogWith({ perimeters });
|
||||
for (const area of [
|
||||
@@ -273,46 +268,45 @@ test('fire perimeter queries include dateline interiors and exclude the opposite
|
||||
|
||||
test('fire perimeter coordinates stay at the dateline for closed and multipart outlines', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
],
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
],
|
||||
],
|
||||
},
|
||||
]),
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [178, -3, -178, 3] },
|
||||
@@ -765,24 +759,23 @@ test('brief sections use a named place at its own point', async () => {
|
||||
|
||||
test('a fire perimeter enclosing the whole area is found', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'big',
|
||||
name: 'Big Fire',
|
||||
acres: 250000,
|
||||
polygons: [
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'big',
|
||||
name: 'Big Fire',
|
||||
acres: 250000,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[
|
||||
[-122, 38],
|
||||
[-120, 38],
|
||||
[-120, 40],
|
||||
[-122, 40],
|
||||
],
|
||||
[-122, 38],
|
||||
[-120, 38],
|
||||
[-120, 40],
|
||||
[-122, 40],
|
||||
],
|
||||
],
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-121.2, 38.9, -120.8, 39.1] },
|
||||
@@ -890,11 +883,19 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
|
||||
],
|
||||
];
|
||||
const perimeters = {
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot(
|
||||
[{ stableId: 'held', name: 'Held Fire', acres: 300, polygons: [ring] }],
|
||||
{ stale: true, fetchedAt },
|
||||
),
|
||||
getSnapshot: async () => [],
|
||||
getSnapshotDetail: async () => ({
|
||||
rows: [
|
||||
{
|
||||
stableId: 'held',
|
||||
name: 'Held Fire',
|
||||
acres: 300,
|
||||
polygons: [ring],
|
||||
},
|
||||
],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
}),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-120, 34, -117, 36] },
|
||||
@@ -906,43 +907,3 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
|
||||
assert.equal(result.data.stale, true);
|
||||
assert.equal(result.data.retrieved_at, new Date(fetchedAt).toISOString());
|
||||
});
|
||||
|
||||
test('a fire is in the area when one of its pieces is', async () => {
|
||||
const square = (lon, lat) => [
|
||||
[
|
||||
[lon, lat],
|
||||
[lon + 0.1, lat],
|
||||
[lon + 0.1, lat + 0.1],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
const fire = (id, lon, lat) => ({
|
||||
id,
|
||||
name: id,
|
||||
acres: 10,
|
||||
lastGrowthTime: null,
|
||||
anchor: { lon, lat },
|
||||
});
|
||||
const perimeters = {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
stale: false,
|
||||
fetchedAt: null,
|
||||
revision: '',
|
||||
note: null,
|
||||
fires: [fire('split', -80, 30), fire('unmapped', -118.5, 35.2)],
|
||||
pieces: [
|
||||
{ fireId: 'split', born: null, polygons: [square(-80, 30)] },
|
||||
{ fireId: 'split', born: null, polygons: [square(-118.5, 35.2)] },
|
||||
],
|
||||
}),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-120, 34, -117, 36] },
|
||||
});
|
||||
assert.deepEqual(
|
||||
result.data.rows.map(({ id, lat, lon }) => [id, lat, lon]),
|
||||
[['split', 30, -80]],
|
||||
'placed at its card anchor; a fire with no pieces is not mapped',
|
||||
);
|
||||
});
|
||||
@@ -908,9 +908,6 @@ export class StyleManager extends ShellFacade {
|
||||
this._panelChrome.setPanelCollapsed(panelId, collapsed, options),
|
||||
readPanel: (panel) => this._panelChrome._shownPanel(panel),
|
||||
onSheetsClosed: () => this._syncShareState(),
|
||||
onTabOpened: (sheet) => {
|
||||
void this._onMobileTabOpened(sheet);
|
||||
},
|
||||
publish: (view) =>
|
||||
useDisplayStore(applicationPinia()).publishPhoneShell(view),
|
||||
afterPublish: (callback) => {
|
||||
@@ -919,32 +916,6 @@ export class StyleManager extends ShellFacade {
|
||||
});
|
||||
}
|
||||
|
||||
/** Reveal a tracked aircraft through Contacts when its phone tab is opened. */
|
||||
async _onMobileTabOpened(sheet) {
|
||||
const context = this.getContextModeState();
|
||||
if (
|
||||
sheet !== 'context' ||
|
||||
this._disposed ||
|
||||
!context ||
|
||||
context.mode ||
|
||||
context.changing ||
|
||||
context.entering ||
|
||||
!this.getAircraftTrackingTarget()
|
||||
)
|
||||
return false;
|
||||
try {
|
||||
const result = await this.setContextMode('contacts');
|
||||
if (result?.ok) return true;
|
||||
if (result?.cancelled || this._disposed) return false;
|
||||
} catch {
|
||||
if (this._disposed) return false;
|
||||
}
|
||||
this._showToast(
|
||||
t('Contacts could not complete the requested transition; try again'),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the owner-approved map stack chip row from the matching controller
|
||||
* entries. Cesium ion/Bing chips remain keyboard-focusable but unavailable,
|
||||
|
||||
+16
-1
@@ -1,3 +1,5 @@
|
||||
import { watch } from 'vue';
|
||||
import { MOBILE_SHEET_ATTR } from './mobileSheets.js';
|
||||
import {
|
||||
EMPTY_CCTV_FRAME,
|
||||
_clearCctvFrame,
|
||||
@@ -73,7 +75,10 @@ export class CctvControls {
|
||||
if (state) this._renderCctvState(state);
|
||||
if (this._cctvChip) this._publishCctvChip({});
|
||||
});
|
||||
if (this._cctvVideo && typeof MutationObserver !== 'undefined') {
|
||||
if (
|
||||
(this._cctvVideo || this._cctvFrame) &&
|
||||
typeof MutationObserver !== 'undefined'
|
||||
) {
|
||||
this._videoVisibilityObserver = new MutationObserver(() =>
|
||||
this._renderCctvState(this._cctvState),
|
||||
);
|
||||
@@ -82,6 +87,15 @@ export class CctvControls {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'hidden'],
|
||||
});
|
||||
// On phones the panel is on screen only while the Cameras sheet is open.
|
||||
this._videoVisibilityObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', MOBILE_SHEET_ATTR],
|
||||
});
|
||||
this._offPreviewCards = watch(
|
||||
() => this.store.previewCards,
|
||||
() => this._renderCctvState(this._cctvState),
|
||||
);
|
||||
this.listen(document, 'visibilitychange', () =>
|
||||
this._renderCctvState(this._cctvState),
|
||||
);
|
||||
@@ -154,6 +168,7 @@ export class CctvControls {
|
||||
this._quebecCctvOverlay?.dispose();
|
||||
this._cctvVideoSurface?.stop();
|
||||
this._videoVisibilityObserver?.disconnect();
|
||||
this._offPreviewCards?.();
|
||||
this._actionGeneration++;
|
||||
this.listeners.abort();
|
||||
this._cctvUnsubscribe?.();
|
||||
|
||||
+152
-11
@@ -20,7 +20,7 @@ const BUTTONS = {
|
||||
_cctvProjectionBtn: 'cctv-projection-btn',
|
||||
};
|
||||
|
||||
function panel(t) {
|
||||
function panel(t, { video = false } = {}) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
@@ -32,6 +32,7 @@ function panel(t) {
|
||||
document.getElementById(id),
|
||||
]),
|
||||
);
|
||||
if (video) elements._cctvVideo = document.getElementById('cctv-video');
|
||||
const controls = new CctvControls({
|
||||
elements: {
|
||||
...elements,
|
||||
@@ -377,17 +378,10 @@ test('a second edit of the same chip gets a fresh input', async (t) => {
|
||||
});
|
||||
|
||||
test('the frame preview renders each step of a camera frame request', async (t) => {
|
||||
const prior = globalThis.Image;
|
||||
const requests = [];
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
requests.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = prior;
|
||||
});
|
||||
const requests = mockImages(t);
|
||||
const { controls, byId } = panel(t);
|
||||
// The preview loads while the panel is open; the panel starts collapsed.
|
||||
byId('cctv-panel').classList.remove('collapsed');
|
||||
const frame = byId('cctv-frame');
|
||||
const wrap = byId('cctv-frame-wrap');
|
||||
const badge = byId('cctv-source-badge');
|
||||
@@ -606,3 +600,150 @@ test('the meta line of a disabled layer does not describe its last camera', () =
|
||||
);
|
||||
assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /);
|
||||
});
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
function mockImages(t) {
|
||||
const prior = globalThis.Image;
|
||||
const requests = [];
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
requests.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = prior;
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
|
||||
const stillState = (frameUrl, id = 'a') => ({
|
||||
enabled: true,
|
||||
count: 2,
|
||||
cameraIndex: [camera, { ...camera, id: 'b' }],
|
||||
activeCameraId: id,
|
||||
activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' },
|
||||
});
|
||||
|
||||
test('the still preview is fetched only while the tab and the panel are shown', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const hidden = Object.getOwnPropertyDescriptor(document, 'hidden');
|
||||
let tabHidden = false;
|
||||
Object.defineProperty(document, 'hidden', {
|
||||
configurable: true,
|
||||
get: () => tabHidden,
|
||||
});
|
||||
t.after(() => {
|
||||
if (hidden) Object.defineProperty(document, 'hidden', hidden);
|
||||
else delete document.hidden;
|
||||
});
|
||||
const { controls, byId } = panel(t);
|
||||
assert.equal(controls._cctvVideo, undefined);
|
||||
const panelElement = byId('cctv-panel');
|
||||
const state = stillState;
|
||||
|
||||
// Collapsed panel: nothing is requested, however often the state arrives.
|
||||
assert.equal(panelElement.classList.contains('collapsed'), true);
|
||||
controls._renderCctvState(state('a1.jpg'));
|
||||
controls._renderCctvState(state('a2.jpg'));
|
||||
assert.equal(requests.length, 0, 'collapsed panel');
|
||||
|
||||
// Opening it resumes through the class observer, with no manual render.
|
||||
panelElement.classList.remove('collapsed');
|
||||
await settle();
|
||||
assert.equal(requests.length, 1, 'expanded panel');
|
||||
assert.equal(requests[0].src, 'a2.jpg');
|
||||
requests[0].onload();
|
||||
|
||||
// A background tab: refreshed URLs are not requested.
|
||||
tabHidden = true;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
controls._renderCctvState(state('a3.jpg'));
|
||||
assert.equal(requests.length, 1, 'hidden tab');
|
||||
|
||||
// Back in the tab: visibilitychange alone fetches the current URL.
|
||||
tabHidden = false;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
assert.equal(requests.length, 2, 'visible tab');
|
||||
assert.equal(requests[1].src, 'a3.jpg');
|
||||
});
|
||||
|
||||
test('the still preview waits for the Cameras sheet on phones', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
const { controls, byId } = panel(t);
|
||||
byId('cctv-panel').classList.remove('collapsed');
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 0, 'another sheet is open');
|
||||
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 0, 'no sheet is open');
|
||||
|
||||
document.body.setAttribute('data-mobile-sheet', 'cameras');
|
||||
await settle();
|
||||
assert.equal(requests.length, 1, 'Cameras sheet opened');
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
|
||||
// Off a phone the sheet attribute means nothing.
|
||||
requests[0].onload();
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
assert.equal(requests.length, 2, 'desktop ignores the sheet');
|
||||
});
|
||||
|
||||
test('a camera picked while the panel is collapsed shows its own still on expanding', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, byId } = panel(t);
|
||||
const panelElement = byId('cctv-panel');
|
||||
panelElement.classList.remove('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
panelElement.classList.add('collapsed');
|
||||
await settle();
|
||||
controls._renderCctvState(stillState('b1.jpg', 'b'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
panelElement.classList.remove('collapsed');
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'b1.jpg');
|
||||
assert.equal(byId('cctv-frame').dataset.cameraId, 'b');
|
||||
assert.notEqual(byId('cctv-frame').getAttribute('src'), 'a1.jpg');
|
||||
});
|
||||
|
||||
test('leaving the Cameras sheet stops the live video and coming back starts it again', async (t) => {
|
||||
const { controls, byId } = panel(t, { video: true });
|
||||
byId('cctv-panel').classList.remove('collapsed');
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'cameras');
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
controls._renderCctvState({
|
||||
enabled: true,
|
||||
count: 1,
|
||||
cameraIndex: [camera],
|
||||
activeCameraId: 'a',
|
||||
activeCamera: { ...camera, isVideo: true },
|
||||
});
|
||||
const first = controls._cctvVideoSurface;
|
||||
assert.ok(first);
|
||||
const stop = t.mock.method(first, 'stop');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
await settle();
|
||||
assert.equal(stop.mock.callCount(), 1);
|
||||
assert.equal(controls._cctvVideoSurface, null);
|
||||
document.body.setAttribute('data-mobile-sheet', 'cameras');
|
||||
await settle();
|
||||
assert.ok(controls._cctvVideoSurface);
|
||||
assert.notEqual(controls._cctvVideoSurface, first);
|
||||
});
|
||||
@@ -8,6 +8,15 @@ import {
|
||||
import { createCctvVideoSurface } from './cctvVideo.js';
|
||||
import { presentCctvCalibration } from './cctvCalibration.js';
|
||||
import { roundHeadingDegrees } from '../data/headingDegrees.js';
|
||||
import {
|
||||
MOBILE_SHELL_CLASS,
|
||||
MOBILE_SHEET_ATTR,
|
||||
sheetForPanelId,
|
||||
} from './mobileSheets.js';
|
||||
|
||||
const CAMERAS_SHEET = sheetForPanelId('cctv-panel');
|
||||
const CONTEXT_SHEET = sheetForPanelId('global-context-panel');
|
||||
|
||||
export function _calBadgeLabel(badge) {
|
||||
switch (badge) {
|
||||
case 'calibrated':
|
||||
@@ -279,11 +288,25 @@ export function _renderCctvState(state) {
|
||||
const liveIntent =
|
||||
enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl;
|
||||
this.store.setLive(liveIntent);
|
||||
// A background tab, a collapsed panel or a closed phone sheet shows no
|
||||
// picture; the observers and visibilitychange render again on showing.
|
||||
const body = globalThis.document?.body;
|
||||
const phone = body?.classList.contains(MOBILE_SHELL_CLASS);
|
||||
const sheet = body?.getAttribute(MOBILE_SHEET_ATTR);
|
||||
const tabShown = !!body && !document.hidden;
|
||||
const panelShown =
|
||||
tabShown &&
|
||||
!this._cctvPanel?.classList.contains('collapsed') &&
|
||||
(!phone || sheet === CAMERAS_SHEET);
|
||||
// Context's camera card shows the same still.
|
||||
const cardShown =
|
||||
tabShown &&
|
||||
this.store.previewCards > 0 &&
|
||||
(!phone || sheet === CONTEXT_SHEET);
|
||||
// Its bigger view is a popup over the map, shown on any phone sheet.
|
||||
const popupShown = tabShown && this.store.previewPopups > 0;
|
||||
if (this._cctvVideo) {
|
||||
const visible =
|
||||
liveIntent &&
|
||||
!document.hidden &&
|
||||
!this._cctvPanel?.classList.contains('collapsed');
|
||||
const visible = liveIntent && panelShown;
|
||||
if (!visible || this._cctvVideoCameraId !== activeId) {
|
||||
this._cctvVideoSurface?.stop();
|
||||
this._cctvVideoSurface = null;
|
||||
@@ -308,6 +331,7 @@ export function _renderCctvState(state) {
|
||||
// immediate so navigation never waits on the prior camera's request.
|
||||
if (
|
||||
nextSrc &&
|
||||
(panelShown || cardShown || popupShown) &&
|
||||
(cameraChanged || (!frameLoading && this._frame.currentSrc !== nextSrc))
|
||||
) {
|
||||
this._queueCctvFrame(nextSrc, nextCameraId, cameraChanged);
|
||||
|
||||
@@ -9,7 +9,13 @@ import {
|
||||
subjectEntryAllowed,
|
||||
} from '../contextModePolicy.js';
|
||||
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
|
||||
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
|
||||
import {
|
||||
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
|
||||
aircraftClassMatches,
|
||||
formatAwarenessLabel,
|
||||
} from '../data/militaryAwarenessEngine.js';
|
||||
import { fromDegreesInto } from '../geo/ellipsoid.js';
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
import { enterCockpitWithTracking } from '../cockpitTracking.js';
|
||||
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
|
||||
import { readEntityRecord } from '../data/entityRecords.js';
|
||||
@@ -352,13 +358,41 @@ export class CockpitCoordinator {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a requested-layer entry searches from: the aircraft the camera
|
||||
* follows, else the ground under the camera.
|
||||
* @param {{layerId: string}|null} currentTarget The tracked aircraft.
|
||||
* @returns {{x: number, y: number, z: number}|null}
|
||||
*/
|
||||
_cockpitEntrySearchOrigin(currentTarget) {
|
||||
const { flightsLayer, militaryFlightsLayer } = this.services;
|
||||
const layer =
|
||||
currentTarget?.layerId === 'military'
|
||||
? militaryFlightsLayer
|
||||
: currentTarget?.layerId === 'flights'
|
||||
? flightsLayer
|
||||
: null;
|
||||
const subject = layer?.getTrackedSubject?.();
|
||||
if (subject?.position) return subject.position;
|
||||
const pose = findCamera(this.viewer)?.pose?.();
|
||||
if (!Number.isFinite(pose?.lat) || !Number.isFinite(pose?.lon)) return null;
|
||||
return fromDegreesInto(pose.lon, pose.lat, 0, { x: 0, y: 0, z: 0 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retarget a voice entry to the requested layer and class before entering.
|
||||
* It searches the aircraft that layer shows, under the person's own
|
||||
* filters, nearest first, from the followed aircraft or the camera, and
|
||||
* follows the nearest match; the aircraft already followed counts when it
|
||||
* matches. It needs nothing from Contacts.
|
||||
*/
|
||||
_retargetCockpitEntryLayer({
|
||||
targetLayer,
|
||||
aircraftClass,
|
||||
currentTarget,
|
||||
selectedTarget,
|
||||
}) {
|
||||
const { militaryAwarenessLayer } = this.services;
|
||||
const { flightsLayer, militaryFlightsLayer } = this.services;
|
||||
if (!['flights', 'military'].includes(targetLayer)) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -370,12 +404,27 @@ export class CockpitCoordinator {
|
||||
const alreadyOnLayer = activeLayer === targetLayer;
|
||||
if (alreadyOnLayer && !aircraftClass)
|
||||
return { ok: true, retargeted: false };
|
||||
const moved = militaryAwarenessLayer?.navigateNext
|
||||
? !!militaryAwarenessLayer.navigateNext({
|
||||
targetLayer,
|
||||
aircraftClass,
|
||||
origin: 'voice',
|
||||
})
|
||||
const layer =
|
||||
targetLayer === 'military' ? militaryFlightsLayer : flightsLayer;
|
||||
const origin = this._cockpitEntrySearchOrigin(currentTarget);
|
||||
const nearby =
|
||||
origin && typeof layer?.getNearby === 'function'
|
||||
? layer.getNearby(
|
||||
origin,
|
||||
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
|
||||
targetLayer === 'military' ? 5000 : 25000,
|
||||
)
|
||||
: [];
|
||||
const match = nearby.find(
|
||||
(item) => item?.icao24 && aircraftClassMatches(item, aircraftClass),
|
||||
);
|
||||
const followed =
|
||||
match &&
|
||||
currentTarget?.layerId === targetLayer &&
|
||||
String(currentTarget.id) === String(match.icao24);
|
||||
if (followed) return { ok: true, retargeted: false };
|
||||
const moved = match
|
||||
? !!layer.trackById?.(match.icao24, { origin: 'voice' })
|
||||
: false;
|
||||
if (moved) return { ok: true, retargeted: true };
|
||||
// A filter that matched nothing still enters, as long as the layer is
|
||||
|
||||
@@ -869,3 +869,79 @@ test('a malformed provider is left out and the built-in kinds are unchanged', as
|
||||
assert.equal(cockpit.enter(), true);
|
||||
assert.equal(cockpit.subjectKind, 'aircraft');
|
||||
});
|
||||
|
||||
// A requested-layer entry finds its aircraft in that layer, from the
|
||||
// aircraft the camera follows; it never asks Contacts.
|
||||
function retargetFixture(t, nearby) {
|
||||
const { coordinator } = fixture(t, {
|
||||
enabled: ['flights', 'military'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const tracked = [];
|
||||
const searches = [];
|
||||
coordinator.services.militaryAwarenessLayer.navigateNext = () =>
|
||||
assert.fail('entry must not navigate through Contacts');
|
||||
coordinator.services.flightsLayer.getTrackedSubject = () => ({
|
||||
layerId: 'flights',
|
||||
id: CIVIL.icao24,
|
||||
position: { x: 1, y: 2, z: 3 },
|
||||
});
|
||||
coordinator.services.militaryFlightsLayer.getNearby = (...args) => {
|
||||
searches.push(args);
|
||||
return nearby;
|
||||
};
|
||||
coordinator.services.militaryFlightsLayer.trackById = (id, options) => {
|
||||
tracked.push([id, options.origin]);
|
||||
return true;
|
||||
};
|
||||
return { coordinator, tracked, searches };
|
||||
}
|
||||
|
||||
test('a voice entry asking for a military class follows the nearest match without Contacts', (t) => {
|
||||
const { coordinator, tracked, searches } = retargetFixture(t, [
|
||||
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
|
||||
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 20 },
|
||||
{ icao24: 'helo2', aircraftClass: 'helicopter', distance: 30 },
|
||||
]);
|
||||
const result = coordinator._retargetCockpitEntryLayer({
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
|
||||
selectedTarget: null,
|
||||
});
|
||||
assert.deepEqual(result, { ok: true, retargeted: true });
|
||||
assert.deepEqual(tracked, [['helo1', 'voice']]);
|
||||
// Searched from the followed aircraft, among the aircraft the person's
|
||||
// filters show: never the hidden ones.
|
||||
assert.deepEqual(searches[0][0], { x: 1, y: 2, z: 3 });
|
||||
assert.equal(searches[0][3], undefined);
|
||||
});
|
||||
|
||||
test('a voice entry whose followed aircraft already matches stays on it', (t) => {
|
||||
const { coordinator, tracked } = retargetFixture(t, [
|
||||
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 0 },
|
||||
]);
|
||||
const result = coordinator._retargetCockpitEntryLayer({
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
currentTarget: { layerId: 'military', id: 'helo1' },
|
||||
selectedTarget: null,
|
||||
});
|
||||
assert.deepEqual(result, { ok: true, retargeted: false });
|
||||
assert.deepEqual(tracked, []);
|
||||
});
|
||||
|
||||
test('a voice entry with no matching aircraft says so and follows nothing', (t) => {
|
||||
const { coordinator, tracked } = retargetFixture(t, [
|
||||
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
|
||||
]);
|
||||
const result = coordinator._retargetCockpitEntryLayer({
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
|
||||
selectedTarget: null,
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.error, /No helicopter military contact is available/);
|
||||
assert.deepEqual(tracked, []);
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { CctvControls } from './cctvControls.js';
|
||||
import { useCctvStore } from './stores/cctv.js';
|
||||
import CctvPanel from './views/panels/CctvPanel.vue';
|
||||
import CctvPreview from './views/panels/CctvPreview.vue';
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 0));
|
||||
const camera = {
|
||||
id: 'a',
|
||||
city: 'Austin',
|
||||
name: 'Congress Ave',
|
||||
headingDeg: 91.6,
|
||||
fovDeg: 60,
|
||||
rangeM: 120.4,
|
||||
sourceLabel: 'Configured Source',
|
||||
calBadge: 'curated',
|
||||
};
|
||||
const stillState = (frameUrl, id = 'a') => ({
|
||||
enabled: true,
|
||||
count: 2,
|
||||
cameraIndex: [camera, { ...camera, id: 'b' }],
|
||||
activeCameraId: id,
|
||||
activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' },
|
||||
});
|
||||
|
||||
function fixture(t, { card = true } = {}) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const cardHost = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
const app = createApp(CctvPanel).use(pinia);
|
||||
app.mount(host);
|
||||
let preview;
|
||||
function mountCard() {
|
||||
preview = createApp(CctvPreview, { cameraId: 'a' }).use(pinia);
|
||||
preview.mount(cardHost);
|
||||
}
|
||||
function unmountCard() {
|
||||
preview?.unmount();
|
||||
preview = null;
|
||||
}
|
||||
if (card) mountCard();
|
||||
const store = useCctvStore(pinia);
|
||||
const controls = new CctvControls({
|
||||
elements: {
|
||||
_cctvPanel: document.getElementById('cctv-panel'),
|
||||
_cctvFrame: document.getElementById('cctv-frame'),
|
||||
_cctvFrameWrap: document.getElementById('cctv-frame-wrap'),
|
||||
},
|
||||
cctv: {},
|
||||
actions: {
|
||||
isEnabled: () => true,
|
||||
setPanelCollapsed() {},
|
||||
syncViewport() {},
|
||||
},
|
||||
store,
|
||||
});
|
||||
t.after(() => {
|
||||
controls.destroy();
|
||||
app.unmount();
|
||||
preview?.unmount();
|
||||
});
|
||||
return {
|
||||
controls,
|
||||
cardHost,
|
||||
mountCard,
|
||||
unmountCard,
|
||||
store,
|
||||
panelEl: document.getElementById('cctv-panel'),
|
||||
};
|
||||
}
|
||||
|
||||
function mockImages(t) {
|
||||
const prior = globalThis.Image;
|
||||
const requests = [];
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
requests.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = prior;
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
|
||||
test('desktop: the Context card keeps refreshing while the accordion folds CCTV', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, cardHost, panelEl } = fixture(t);
|
||||
panelEl.classList.remove('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a1.jpg');
|
||||
// Context opens: the desktop accordion folds CCTV (class collapsed).
|
||||
panelEl.classList.add('collapsed');
|
||||
await settle();
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'a2.jpg');
|
||||
requests[1].onload();
|
||||
controls._renderCctvState(stillState('a3.jpg'));
|
||||
assert.equal(requests.length, 3);
|
||||
assert.equal(requests[2].src, 'a3.jpg');
|
||||
requests[2].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a3.jpg');
|
||||
});
|
||||
|
||||
test('phone: a camera picked with the Context sheet open gets its still', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
const { controls, cardHost, panelEl } = fixture(t);
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'context');
|
||||
panelEl.classList.remove('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
requests.length,
|
||||
1,
|
||||
'the Context card on the Context sheet requests the still',
|
||||
);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
requests.at(-1).onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.ok(
|
||||
cardHost.querySelector('.cctv-preview__expand'),
|
||||
'the card shows a frame, not Acquiring frame…',
|
||||
);
|
||||
});
|
||||
|
||||
test('phone: the card on a closed Context sheet waits', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, panelEl } = fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 0);
|
||||
document.body.setAttribute('data-mobile-sheet', 'context');
|
||||
await settle();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
});
|
||||
|
||||
test('phone: the bigger view keeps refreshing after the layout turns phone, and stops once closed', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
const { controls, cardHost, panelEl } = fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
cardHost.querySelector('.cctv-preview__expand').click();
|
||||
await settle();
|
||||
await nextTick();
|
||||
const popup = document.body.querySelector('.cctv-popup');
|
||||
assert.ok(popup);
|
||||
assert.equal(popup.querySelector('img').getAttribute('src'), 'a1.jpg');
|
||||
|
||||
document.body.classList.add('mobile-shell');
|
||||
await settle();
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.ok(document.body.contains(popup));
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'a2.jpg');
|
||||
requests[1].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(popup.querySelector('img').getAttribute('src'), 'a2.jpg');
|
||||
|
||||
popup.querySelector('.cctv-popup__close').click();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(document.body.querySelector('.cctv-popup'), null);
|
||||
controls._renderCctvState(stillState('a3.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, 2);
|
||||
});
|
||||
|
||||
test('desktop: a card that mounts asks for the still', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, panelEl, mountCard } = fixture(t, { card: false });
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, 0);
|
||||
mountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
});
|
||||
|
||||
test('desktop: a card that unmounts stops the still, and a remount resumes it', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, panelEl, mountCard, unmountCard, store } = fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
|
||||
unmountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(store.previewCards, 0);
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, 1);
|
||||
|
||||
mountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'a2.jpg');
|
||||
});
|
||||
|
||||
test('desktop: the bigger view is released when the card unmounts, also in the tick it closes', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, cardHost, panelEl, mountCard, unmountCard, store } =
|
||||
fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
const openPopup = async () => {
|
||||
cardHost.querySelector('.cctv-preview__expand').click();
|
||||
await nextTick();
|
||||
assert.equal(store.previewPopups, 1);
|
||||
};
|
||||
|
||||
await openPopup();
|
||||
unmountCard();
|
||||
await nextTick();
|
||||
assert.equal(document.body.querySelector('.cctv-popup'), null);
|
||||
assert.equal(store.previewPopups, 0);
|
||||
|
||||
mountCard();
|
||||
await nextTick();
|
||||
await openPopup();
|
||||
// Closed and unmounted before the watcher runs, as when one Escape closes
|
||||
// the phone's Context sheet and the popup.
|
||||
document.body.querySelector('.cctv-popup__close').click();
|
||||
unmountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(store.previewPopups, 0);
|
||||
assert.equal(store.previewCards, 0);
|
||||
const before = requests.length;
|
||||
controls._renderCctvState(stillState('a3.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, before);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
export const MOBILE_SHELL_CLASS = 'mobile-shell';
|
||||
export const MOBILE_SHEET_ATTR = 'data-mobile-sheet';
|
||||
|
||||
/**
|
||||
* Panels each sheet expands. A sheet also shows its rail's other panels
|
||||
* collapsed (Scenes under Layers), per styles/mobile-shell.css.
|
||||
*/
|
||||
export const MOBILE_SHEET_PANELS = Object.freeze({
|
||||
layers: Object.freeze(['data-panel']),
|
||||
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
|
||||
context: Object.freeze(['global-context-panel']),
|
||||
missions: Object.freeze(['space-missions-panel']),
|
||||
search: Object.freeze(['location-bar']),
|
||||
more: Object.freeze(['control-panel', 'pp-toggles']),
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} panelId
|
||||
* @returns {string|null} The sheet that presents `panelId`.
|
||||
*/
|
||||
export function sheetForPanelId(panelId) {
|
||||
for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) {
|
||||
if (ids.includes(panelId)) return sheet;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user