Compare commits

..
Author SHA1 Message Date
Said Turksever 83f5a3e2bd docs(changelog): name the TomTom Orbis fragment after its PR 2026-11-20 14:35:46 +00:00
Said Turksever b711e9e412 fix(traffic): fall back to TomTom Orbis flow tiles when the key is refused
TomTom keys are assigned products. A key without the TomTom Maps Traffic
product gets HTTP 403 on traffic/map/4/tile/flow, the only endpoint the
proxy called, so live traffic never loaded and the layer reported
"TomTom upstream unreachable".

- Proxy: on 403, ask the Orbis Maps flow endpoint (apiVersion 2) and keep
  whichever endpoint answered until the key changes.
- Decoder: read Orbis relative_speed and road_category into the existing
  segment shape.
- When both endpoints refuse the key, answer 403 key_rejected, report
  keyRejected on /api/tomtom/status, show "TomTom key rejected" and leave
  upstream alone for five minutes instead of spending the tile budget.

Fixes #1809
2026-11-20 14:33:47 +00:00
136 changed files with 1522 additions and 10158 deletions

No files matched your search

+3
View File
@@ -205,6 +205,9 @@ AISSTREAM_API_KEY=
# Traffic Flow & Incidents tile requests per MONTH, not per day; no credit card
# required. Get a key at https://my.tomtom.com/keys). SERVER-SIDE ONLY:
# the browser fetches same-origin /api/tomtom/* and never sees the key.
# The key needs a traffic product assigned at my.tomtom.com: either the
# TomTom Maps Traffic API or the Orbis Maps one works (the proxy tries the
# first and falls back to Orbis on HTTP 403).
# Keyless fallback: the traffic layer runs its built-in simulation (white dots,
# hardcoded per-road-class speeds) — no key required for the layer to work.
# TOMTOM_API_KEY=
+1 -22
View File
@@ -20,7 +20,6 @@ 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 |
@@ -282,7 +281,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; failed country queries are reported in coverage without blocking a healthy global refresh. Failed/degraded refreshes back off for one minute, with at most three mirrors per query.
- **Radio Browser.** In every installation, including when `RADIO_PRIORITY_COUNTRIES` is unset, each request tries at most three mirror candidates (later fallback candidates are skipped), and failed or partial catalog refreshes back off for 60 seconds. A cold-start failure therefore continues returning 503 during that delay even if upstream recovers. `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; broad/specialist responses whose rows all fail the product's health policy do not count as successful queries. Optional priority-country outcomes are advisory: valid, in-limit responses with no eligible stations succeed as empty results, while failed or malformed country queries report unsuccessful coverage without degrading the global catalog. A usable partial cold catalog is explicitly `DEGRADED`, and non-array or empty broad/specialist payloads are rejected atomically. Individual structurally malformed rows are skipped rather than failing the whole query; the response carries their bounded `rejectedStationCount` (at most 10,000), which the client adds to its own rejected rows and reports as degraded coverage without discarding the accepted generation. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply.
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (from the TomTom Maps Traffic API, or the TomTom Orbis Maps Traffic API when the key is only assigned that product; 120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **Routing (OSRM / FOSSGIS).** `/api/route` proxies the public OSRM instances FOSSGIS e.V. runs for the OpenStreetMap community (car, bike, foot profiles). They are keyless and intended for fair, interactive use — the proxy rate-limits clients (60/min, 200/min total), caps route span and response size, caches each route for 10 minutes, and identifies itself in the User-Agent. Heavy or automated use must run its own OSRM. Routes are computed from OpenStreetMap data (ODbL); the Directions layer and voice routes never redistribute them. A route the router cannot find is reported as such; the Directions layer draws nothing in that case, and voice routes fall back to a clearly labeled straight line.
- **Re:Earth Terrain.** Keyless (no API key). Used two ways: (1) `src/mapStackController.js` swaps in a `Cesium.CesiumTerrainProvider` pointed at Re:Earth's `cesium-mesh/ellipsoid` quantized-mesh endpoint for globe stacks without a Cesium ion token (e.g. OSM), replacing a flat `EllipsoidTerrainProvider`; falls back to the flat provider if the endpoint can't be reached. (2) The server-side `/api/terrain/heights` proxy (disk-cached, serve-stale) resolves per-point ellipsoidal ground height for entity placement. Both are best-effort with a keyless-safe fallback (bundled EGM96 geoid math) if Re:Earth is unreachable.
- **OSRM on the FOSSGIS routing servers.** Keyless (no API key). Every route is requested by a person: clicking A and B in the Directions layer, or a voice "route from A to B". The server-side `/api/route` proxy sends an identifying `User-Agent`, pins the upstream host, accepts 2-12 coordinates, rejects any leg over 600 km or a total over 2,500 km, caps the buffered response at 8 MB, times the upstream out at 12 s, rate-limits per client, caches each route for 10 minutes, and coalesces identical requests that are in flight at the same time. Turn-by-turn maneuvers are asked for only when a caller wants them (`steps=1`), so the callers that do not read them send the smaller request. The "fix the map" link the policy asks for is in the Data attribution popover beside the OpenStreetMap credit.
@@ -710,26 +709,6 @@ 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),
+3 -5
View File
@@ -16,8 +16,6 @@ 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)
@@ -96,7 +94,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 and JTWC 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 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.
@@ -466,11 +464,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 (Atlantic, eastern/central North Pacific); warnings with 34-knot wind danger areas elsewhere | NOAA NHC / CPHC · JTWC | 🟢 |
| 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones for the Atlantic and eastern/central North Pacific | NOAA NHC / CPHC | 🟢 |
</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, 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.
**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.
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.
@@ -1,4 +0,0 @@
- 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,5 @@
- Live traffic works with TomTom keys that are only assigned the Orbis Maps
traffic product: when TomTom refuses the key on the TomTom Maps flow tile
endpoint (HTTP 403), the proxy uses the Orbis one and keeps it. A key both
endpoints refuse now reads "TomTom key rejected" instead of "TomTom upstream
unreachable", and stops spending the daily tile budget on retries (#1809).
@@ -1,3 +0,0 @@
- 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).
@@ -1,3 +0,0 @@
- A voice or chat selection opens its card in the Context panel, as a click
does, and a docked assistant panel steps down so the card shows; the reply
stays until the next one (samehkhamis, #1890).
-5
View File
@@ -1,5 +0,0 @@
- Cyclone advisories show the Joint Typhoon Warning Center's storms beside
NHC's: the western Pacific, the Indian Ocean and the Southern Hemisphere.
JTWC's 34-knot wind danger area is drawn where it publishes no cone, its
cards say the regional centre's warning is the official one, and each storm
now ages out on its own (samehkhamis, #1891).
-4
View File
@@ -1,4 +0,0 @@
- 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).
@@ -1,2 +0,0 @@
- Opening the phone Context tab with an aircraft tracked shows its card and no
longer switches Contacts on (samehkhamis, #1893).
-5
View File
@@ -1,5 +0,0 @@
- A line can show only the part of it within a span of the scene clock
(`LineAgeFade.showMs`, capability `lineTimeWindow`): the renderer cuts it by
time on the GPU as the clock moves, so a moving trail can be sent once as
its whole track; the Cesium renderer draws it, draped or not (samehkhamis,
#1894).
-5
View File
@@ -1,5 +0,0 @@
- 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).
@@ -1,8 +0,0 @@
- Aircraft on the map are shaded sprites that show the view of the aircraft
from where the camera is, instead of flat top-down silhouettes: each class
(and each helicopter rotor frame) is drawn from a sheet rendered from a
sphere of camera angles, laid flat along its course, so a plane seen at an
oblique angle looks solid. Flights, Military Flights (fleet and tracked
contact) and Local ADS-B use it; the TR-3B, airport vehicles, ground
stations and Cockpit's far pips stay flat, and a renderer without view
sheets draws the flat glyphs as before (Mazeyar Moeini Feizabadi, #1903).
-10
View File
@@ -1,10 +0,0 @@
- Vessels on the map are shaded sprites that show the view of the ship from
where the camera is, instead of flat top-down hulls: each hull shape (the
ten vessel kinds, a dredger and a pilot boat) is drawn from a sheet
rendered from straight above down to the horizon, laid flat on the water
along its course, so a ship seen at an oblique angle looks solid. A
vessel keeps its kind's colour; aids to navigation keep their upright buoy,
and a renderer without view sheets draws the flat hulls as before. A
vessel's size now follows the camera's range: larger up close, smaller
than an aircraft from far out, and shrinking and fading toward the
horizon as aircraft do (Mazeyar Moeini Feizabadi, #1907).
+15 -33
View File
@@ -1627,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. 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.
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.
Typed chat sits beside voice in the dock. Chat replies are silent and never
request microphone access. The first message connects with the selected
@@ -1657,12 +1657,6 @@ 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,
@@ -2093,16 +2087,6 @@ 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
@@ -3752,10 +3736,9 @@ 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.
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.
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.
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
@@ -4044,6 +4027,14 @@ The TomTom `/api/tomtom/*` routes run the shared same-site admission gate before
status, cache or upstream work, refusing cross-site browser requests while
preserving same-origin app requests and non-browser local callers. The browser
layers and their rendering remain in their existing modules.
The proxy asks the TomTom Maps flow endpoint (`traffic/map/4/tile/flow/relative`)
first. On HTTP 403, which TomTom answers when a key is not assigned that
product, it asks the Orbis Maps one (`maps/orbis/traffic/flow/vector/tile`,
`apiVersion=2`) and keeps whichever answered until the key changes or the
process restarts; `flowDecode.js` reads both tile schemas into one segment
shape. When both refuse the key, tiles answer `403 {error:'key_rejected'}`
(shown as "TomTom key rejected"), `/api/tomtom/status` reports
`keyRejected: true`, and upstream is left alone for five minutes.
Past the daily tile budget, or while TomTom fails, the proxy answers with its
last copy of a tile (`x-tomtom-cache: STALE-BUDGET` / `STALE-ERROR`) however old
it is, and every tile carries `x-tomtom-fetched-at`, the proxy fetch time
@@ -8909,7 +8900,7 @@ pins and share links already supply complete boxes.
30-second backoff ahead of the current clock are ignored. A smaller rollback
can retain a bounded retry delay of up to 30 seconds.
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the emergency red is mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. Tracking never recolours a model or an icon: the tracked contact draws in the colours it has untracked, and only its alpha changes (faded while stale, clear while its model draws it; `trackedIconColor`, `src/data/trackedAircraftIcon.js`). IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Angle-aware aircraft sprites.** On a renderer with the `viewSheets` capability, each aircraft class (and each of the helicopter's three rotor frames) draws from the aircraft view sheet instead of its flat glyph: `/sprites/aircraft-views.webp`, the classes rendered shaded in neutral grey from a sphere of camera angles (`src/data/viewSheet.js`, baked by `scripts/bake-view-sheet.py --sheet aircraft`, `npm run build:aircraft-views`). The icon lies flat on the earth along its course and the renderer draws the view that matches where the eye is, so an aircraft seen obliquely looks solid; the tints (white fleet, cyan tracked, amber military) multiply the grey as before. `src/data/aircraftViews.js` maps an icon kind and rotor frame to its block of the sheet and registers the sheet once per draw port. Only an icon drawn along its course (`rotationMode: 'course'`) takes a view, and it has no near image (`imageLod`), the sheet having one resolution. Flights and Military Flights draw every fleet contact this way, and their tracked billboard too (drawn along the tracked display course instead of turned on screen, so selecting a contact still changes only its colour); Local ADS-B draws its markers along their track. The TR-3B triangle, airport vehicles, ground stations and Cockpit's far-contact pips keep their flat sprites, and on a renderer without the capability every icon is the flat glyph with its near image, as before. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, milLine truncated
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), in the same colour while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo.
- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
@@ -9100,17 +9091,8 @@ 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, 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.
Cockpit actions, double-click and voice use the same gate; voice entry still
opens Contacts first, as its layer-targeted entry navigates through Contacts.
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)).
+3 -7
View File
@@ -105,13 +105,9 @@ 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 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.
- **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.
- **Satellite clouds:** global infrared is hourly with typically 2–3 hours of
source latency. Clouds only is a brightness filter, not a cloud mask.
- **Wind is a forecast.** The animation flows through one forecast on an
-59
View File
@@ -81,13 +81,6 @@ 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
@@ -122,58 +115,6 @@ 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
-2
View File
@@ -49,8 +49,6 @@
"opensky:import": "./scripts/opensky-import-client.sh",
"build": "vite build",
"build:panel": "node scripts/build-panel.mjs",
"build:aircraft-views": "node scripts/build-view-sheet.mjs --sheet aircraft",
"build:vessel-views": "node scripts/build-view-sheet.mjs --sheet vessels",
"preview": "vite preview",
"test": "node scripts/run-unit-tests.mjs",
"test:perf": "node scripts/run-perf-tests.mjs",
-4
View File
@@ -35,10 +35,6 @@ How the layers use them:
the route or category colour is painted.
- The whole set loads once, up front, when a layer that draws it starts; no
model is fetched while a session runs.
- The aircraft and helicopter models are also rendered from every side into
the aircraft view sheet, the shaded sprites far-away aircraft are drawn
with, and one ship model for each vessel hull shape, cut at its waterline,
into the vessel view sheet ([`../sprites/`](../sprites/README.md)).
`src/data/fleetModels.js` reads the set and chooses each vehicle's model;
`src/data/fleetModels.test.mjs` checks that every model `types.json` names is
-106
View File
@@ -1,106 +0,0 @@
# View Sheets
A view sheet is one image of small shaded sprites: each subject rendered from
a sphere of camera angles. On a renderer with the `viewSheets` capability a
layer lays a contact flat on the earth along its course and the renderer
draws the frame nearest to where the eye is, as a card that tilts as the eye
moves off its direction until the next frame is the nearer (frames are not
blended), so a contact seen at an oblique angle looks solid and turns with
the camera.
- `aircraft-views.webp` holds the far-away aircraft of Flights, Military
Flights and Local ADS-B.
- `vessel-views.webp` holds the vessels of the vessel layer.
Each has a manifest beside it (`.json`).
The sprites are rendered from the project's own procedural fleet models
([`../models/fleet/`](../models/README.md)), so, like them, they contain no
third-party artwork and are covered by the repository's
[MIT license](../../LICENSE).
| Path | What it holds |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aircraft-views.webp` | 4096 × 3648 px, lossless WebP: 64 px cells, 64 a row, 57 rows. Grey: every pixel's red, green and blue are equal. |
| `aircraft-views.json` | The layout (`cellPx`, `columns`, `rows`, `ringStepDeg`, `rings`, `fill`, `grey`) and each subject's first cell, fleet model and bounding radius in metres. |
| `vessel-views.webp` | 4096 × 2496 px, lossless WebP: 64 px cells, 64 a row, 39 rows. Grey. |
| `vessel-views.json` | Its manifest, of the same shape. |
## Layout
A sheet holds each subject as a block of consecutive cells, row-major:
subject `i` starts at cell `i × frames`. Within a block the frames lie in
rings 7.5° apart from straight above (ring 0, one frame) downward. A ring
runs from the eye dead ahead of the nose or bow, round the starboard side, to
dead astern. The renderer mirrors a starboard frame for an eye on the port
side, so the light is symmetric about the subject's centre plane. A frame is
an orthographic view centred on the model's origin, its bounding sphere
spanning 0.92 of the cell, turned so that straight above the nose points up
the image. `src/data/viewSheet.js` holds the layouts (`AIRCRAFT_VIEWS`,
`VESSEL_VIEWS`) and the maths that picks a frame;
`src/data/viewSheet.test.mjs` checks the manifests, the shipped images and
the bake script against them.
| Sheet | Frames a subject | Rings | Subjects, in order |
| -------- | ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Aircraft | 302 | 17, to 30° below the horizon: 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22 | `airliner`, `widebody`, `quadjet`, `turboprop`, `light`, `glider`, `fastjet`, `bizjet`, `uav`, and `helicopter0` to `helicopter2` (the helicopter's three rotor frames, `src/data/rotorFrames.js`) |
| Vessels | 208 | 13, to the horizon (a ship is never seen from below): 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25 | `cargo`, `tanker`, `passenger`, `highspeed`, `fishing`, `tug`, `sailing`, `pleasure`, `military`, `other` (the kinds of `vesselKind`, `src/data/vesselTypes.js`), `dredger`, `pilot` |
The sprites are neutral (light paint, grey shading, dark glass, a dark edge)
so each layer's tint multiplies them, as it does the flat glyphs. They are
exactly grey (`"grey": true`): the renderer keeps a sheet as grey and alpha,
reading its red channel, which halves its memory. The bake refuses a frame
that is not grey, and so does the step that writes the WebP. Every cell keeps
its outer 2 px transparent, so the renderer's mipmaps never pull in a
neighbour.
Thin subjects are thickened a little before their edge so they still read
20 to 30 px wide: the glider, UAV, light aircraft and helicopter, and every
vessel (the container ship, tanker and patrol boat most).
Vessels differ from aircraft in four ways:
- **Waterline.** A ship model's origin is its waterline. Each model is cut
there before it is rendered, so no hull below the water is drawn, even from
the horizon.
- **Paint.** The ship models are many colours (hull paint, decks,
containers). The vessel paint makes every colour a light grey, black hull
paint included, except the windows (a dark colour whose blue stands above
its red), which stay dark.
- **Beam.** Hulls are long and thin, so most are widened across the beam
(1.2 to 1.5 times; the trawler and tug as built). The side view keeps its
true height.
- **Sailboat.** The sailboat's mast is taller than its hull is long. Above
1.2 m it is squashed to 0.4 of its height, so the hull fills its cell from
above and the sail still reads from the side.
## Rebuilding
```
npm run build:aircraft-views # about 7 minutes
npm run build:vessel-views # about 4 minutes
npm run build:vessel-views -- --only tug,sailing --out /tmp/views
```
This needs Blender (`$BLENDER`, else `blender` on the `PATH`, else
`/Applications/Blender.app`). Each runs `scripts/build-view-sheet.mjs`, which
runs `scripts/bake-view-sheet.py --sheet aircraft|vessels` headless (one
script, with each sheet's layout, models, paint and adjustments). The bake
renders every frame with Cycles and refuses a frame whose pixels reach
within 2 px of its cell's edge. `build-view-sheet.mjs` then writes the PNG as
lossless WebP here with the manifest. With `--only`, the other subjects'
cells are left empty, so ship only a full bake. Cycles is not
bit-reproducible, so a rebuild changes the WebP's bytes slightly; rebuild a
sheet only to change it.
To review a bake, write a contact sheet per subject: its rings as rows, plus
a few frames at 40, 30 and 20 px in each tint the layers draw it with.
- Aircraft: over a dark sea, pale land and a mid satellite tone, in the
fleet, tracked and military tints.
- Vessels: over a dark sea, pale shallow water and a satellite ocean tone,
in white and the kind's colour.
```
node scripts/qa-view-sheet.mjs --manifest public/sprites/vessel-views.json [--out qa-shots/vessel-views]
```
-90
View File
@@ -1,90 +0,0 @@
{
"image": "aircraft-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 57,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25,
25,
24,
23,
22
],
"fill": 0.92,
"grey": true,
"subjects": {
"airliner": {
"first": 0,
"model": "aircraft/a320.glb",
"radiusM": 18.883
},
"widebody": {
"first": 302,
"model": "aircraft/b789.glb",
"radiusM": 32.121
},
"quadjet": {
"first": 604,
"model": "aircraft/b744.glb",
"radiusM": 37.959
},
"turboprop": {
"first": 906,
"model": "aircraft/at72.glb",
"radiusM": 14.14
},
"light": {
"first": 1208,
"model": "aircraft/c172.glb",
"radiusM": 5.825
},
"glider": {
"first": 1510,
"model": "aircraft/glider.glb",
"radiusM": 7.506
},
"fastjet": {
"first": 1812,
"model": "aircraft/t38.glb",
"radiusM": 7.408
},
"bizjet": {
"first": 2114,
"model": "aircraft/glf4.glb",
"radiusM": 17.211
},
"uav": {
"first": 2416,
"model": "aircraft/mq9.glb",
"radiusM": 9.811
},
"helicopter0": {
"first": 2718,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter1": {
"first": 3020,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter2": {
"first": 3322,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 MiB

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

Before

Width:  |  Height:  |  Size: 2.2 MiB

-678
View File
@@ -1,678 +0,0 @@
"""Bake a view sheet: each subject of a sheet (an aircraft class, a vessel
kind) seen from a sphere of directions, as one image of small shaded sprites.
blender -b --factory-startup --python scripts/bake-view-sheet.py -- \
--sheet aircraft|vessels --out <dir> [--cell 64] [--supersample 4]
[--only airliner,light] [--preview <dir>]
It writes `<name>.png` and its manifest `<name>.json` to `--out`, `<name>`
being the sheet's name (`aircraft-views`, `vessel-views`). The manifest names
the shipped image, `<name>.webp`, which `npm run build:aircraft-views` or
`npm run build:vessel-views` (scripts/build-view-sheet.mjs) makes from the
PNG (lossless) and writes to `public/sprites/` with the manifest.
The layers draw a contact with the frame that shows it from where the eye is
(`src/data/viewSheet.js` holds the same layouts and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's sheets and the shipped
manifests against it). A frame is an orthographic view of the subject's
fleet model (`public/models/fleet/`, nose or bow toward -X, +Y starboard, +Z
up), centred on the model's origin, the model's bounding sphere filling
`FILL` of the cell.
Directions. `d` is the unit vector from the subject to the eye in the
subject's own frame (forward, right, up), the subject lying flat on the
earth: up is the ground's normal, forward its course. Rings of frames lie
the sheet's `ring_step_deg` apart from straight above (ring 0, one frame)
down to its last ring (30 degrees below the horizon for aircraft, the horizon
for vessels). A ring holds the eye's bearings from dead ahead (first frame)
round the starboard side to dead astern (last frame); the port side is the
starboard frame mirrored, which is why the light is symmetric about the
subject's centre plane.
Roll. A frame's image up is where the subject's forward goes under the
smallest rotation that takes "up" to `d`: straight above, the nose points up
the image, and the roll then changes smoothly all the way round and below
(it has no meaning only from straight below, which no ring reaches).
The sprites are neutral (light paint, grey shading, dark glass and a dark
edge) so a layer's tint multiplies them, as it does the flat glyphs; every
pixel's red, green and blue are equal (`"grey": true` in the manifest), as
the renderer keeps the sheet as grey and alpha, and the bake refuses a frame
that is not. Each sheet has its paint ramp (`PAINTS`), and a subject may
have its own. A helicopter's body and blades are painted light as well (its
blades a solid light grey), and its rotor frames share one scale: each rotor
vertex counts at the farthest point of the circle it sweeps about the
rotor's axis. A vessel is cut at its waterline (its origin, z = 0) before it
is rendered, so no hull below the water is drawn and its bounding sphere is
of what floats; a subject's model may be widened across the beam (`beam`)
or squashed above a height (`squash_above`: a sailboat's mast). Thin
subjects are thickened before their edge (`bold_px`), and every cell keeps
`CLEAR_EDGE_PX` clear at its edges for the renderer's mipmaps; the bake
refuses a frame that does not.
"""
import json
import math
import os
import struct
import sys
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
# --- The sheets (their layouts mirrored in src/data/viewSheet.js) -----------
# A sheet: its name (the files it writes), its rings of frames (each ring's
# frame count, from dead ahead round starboard to dead astern), its paint,
# whether its models are cut at the waterline, and its subjects, in the order
# of their blocks of frames. A subject is (name, model, options); options:
# rotor_deg a helicopter's rotor frame: the rotors turned this far
# paint its own paint ramp (a key of PAINTS)
# bold_px cell pixels it is thickened by before its edge, so thin
# wings, blades and hulls still read 20 to 30 px wide
# beam its model scaled across the beam by this much
# squash_above [z, k]: its model above z metres scaled up by k
AIRCRAFT = {
"name": "aircraft-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22],
"columns": 64,
"paint": "aircraft",
"waterline": False,
"subjects": [
("airliner", "aircraft/a320.glb", {}),
("widebody", "aircraft/b789.glb", {}),
("quadjet", "aircraft/b744.glb", {}),
("turboprop", "aircraft/at72.glb", {}),
("light", "aircraft/c172.glb", {"bold_px": 0.35}),
("glider", "aircraft/glider.glb", {"bold_px": 1.0}),
("fastjet", "aircraft/t38.glb", {}),
("bizjet", "aircraft/glf4.glb", {}),
("uav", "aircraft/mq9.glb", {"bold_px": 1.0}),
# The helicopter has one block for each rotor frame (rotorFrames.js).
("helicopter0", "helicopters/generic_heli.glb", {"rotor_deg": 15, "paint": "helicopter", "bold_px": 0.4}),
("helicopter1", "helicopters/generic_heli.glb", {"rotor_deg": 45, "paint": "helicopter", "bold_px": 0.4}),
("helicopter2", "helicopters/generic_heli.glb", {"rotor_deg": 75, "paint": "helicopter", "bold_px": 0.4}),
],
}
# Vessels: down to the horizon only, as a ship is never seen from below. The
# subjects are the hull kinds of vesselKind (src/data/vesselTypes.js), then
# the dredger (AIS 33) and the pilot boat (pilot, rescue, tender and
# anti-pollution craft).
VESSELS = {
"name": "vessel-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25],
"columns": 64,
"paint": "ship",
"waterline": True,
"subjects": [
("cargo", "ships/container_ship.glb", {"beam": 1.4, "bold_px": 1.0}),
("tanker", "ships/tanker.glb", {"beam": 1.4, "bold_px": 1.0}),
("passenger", "ships/cruise_ship.glb", {"beam": 1.4, "bold_px": 0.5}),
("highspeed", "ships/fast_ferry.glb", {"beam": 1.2, "bold_px": 0.5}),
("fishing", "ships/trawler.glb", {"bold_px": 0.5}),
("tug", "ships/tug.glb", {"bold_px": 0.5}),
("sailing", "ships/sailboat.glb", {"beam": 1.3, "bold_px": 0.5, "squash_above": [1.2, 0.4]}),
("pleasure", "ships/motor_yacht.glb", {"beam": 1.25, "bold_px": 0.5}),
("military", "ships/patrol.glb", {"beam": 1.5, "bold_px": 1.0}),
("other", "ships/generic_vessel.glb", {"beam": 1.3, "bold_px": 0.5}),
("dredger", "ships/dredger.glb", {"beam": 1.3, "bold_px": 0.5}),
("pilot", "ships/pilot_boat.glb", {"beam": 1.2, "bold_px": 0.5}),
],
}
SHEETS = {"aircraft": AIRCRAFT, "vessels": VESSELS}
# How much of a cell the model's bounding sphere spans.
FILL = 0.92
# Cells keep this many pixels at each edge clear: the renderer samples the
# sheet with mipmaps (to level 1), so a neighbour's pixels must not reach
# into a cell's footprint.
CLEAR_EDGE_PX = 2
FORWARD = Vector((-1.0, 0.0, 0.0))
RIGHT = Vector((0.0, 1.0, 0.0))
UP = Vector((0.0, 0.0, 1.0))
def frame_directions(sheet):
"""Every frame's (ring, index, d) with d in the model's axes."""
out = []
for ring, count in enumerate(sheet["rings"]):
alpha = math.radians(ring * sheet["ring_step_deg"])
for i in range(count):
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
d = (
FORWARD * (math.sin(alpha) * math.cos(phi))
+ RIGHT * (math.sin(alpha) * math.sin(phi))
+ UP * math.cos(alpha)
)
out.append((ring, i, d.normalized()))
return out
def frame_up(d):
"""A frame's image up: forward, turned as `UP` turns onto `d`."""
return (UP.rotation_difference(d) @ FORWARD).normalized()
# --- Scene -------------------------------------------------------------------
def args_after_dashes():
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
opts = {
"sheet": "aircraft",
"out": "public/sprites",
"cell": 64,
"supersample": 4,
"only": None,
"preview": None,
"samples": 48,
}
i = 0
while i < len(argv):
key = argv[i].lstrip("-")
if key not in opts:
raise SystemExit(f"unknown option {argv[i]}")
opts[key] = argv[i + 1]
i += 2
opts["cell"] = int(opts["cell"])
opts["supersample"] = int(opts["supersample"])
opts["samples"] = int(opts["samples"])
if opts["sheet"] not in SHEETS:
raise SystemExit(f"--sheet is one of {', '.join(SHEETS)}")
return opts
def setup_scene(render_px, samples):
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = samples
scene.cycles.use_denoising = False
scene.cycles.max_bounces = 3
scene.cycles.pixel_filter_type = "BOX"
scene.cycles.filter_width = 1.0
scene.render.film_transparent = True
scene.render.resolution_x = render_px
scene.render.resolution_y = render_px
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.image_settings.color_depth = "8"
scene.view_settings.view_transform = "Standard"
scene.view_settings.look = "None"
scene.display_settings.display_device = "sRGB"
# Sky: even light from every side, so the underside is lit and the
# wings shade the fuselage softly where they meet.
world = bpy.data.worlds.new("sky")
world.use_nodes = True
background = world.node_tree.nodes["Background"]
background.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)
background.inputs["Strength"].default_value = SKY_STRENGTH
scene.world = world
# Sun: from above, leaning toward the nose, in the aircraft's centre
# plane (so a mirrored frame is lit as its twin).
sun_data = bpy.data.lights.new("sun", "SUN")
sun_data.energy = SUN_STRENGTH
sun_data.angle = math.radians(18)
sun = bpy.data.objects.new("sun", sun_data)
scene.collection.objects.link(sun)
lean = math.radians(28)
to_sun = (UP * math.cos(lean) + FORWARD * math.sin(lean)).normalized()
sun.rotation_euler = to_sun.to_track_quat("Z", "Y").to_euler()
# Fill: a weak light from the eye, so what faces the viewer is lighter
# than what turns away and a round body reads as round from any side.
fill_data = bpy.data.lights.new("fill", "SUN")
fill_data.energy = FILL_STRENGTH
fill_data.angle = math.radians(30)
fill = bpy.data.objects.new("fill", fill_data)
scene.collection.objects.link(fill)
camera_data = bpy.data.cameras.new("camera")
camera_data.type = "ORTHO"
camera_data.clip_start = 0.1
camera_data.clip_end = 10000
camera = bpy.data.objects.new("camera", camera_data)
scene.collection.objects.link(camera)
scene.camera = camera
return scene, camera, fill
# Paint by the model's own colour value (its largest channel, linear), as
# (value, grey) stops. Aircraft: glass and tyres stay dark, a livery's accent
# becomes mid grey, and every body colour a light paint, so a tint reads on
# any model. Ships: windows and the darkest fittings stay dark, and hull
# paint, decks and cargo all become light greys a little apart.
PAINTS = {
"aircraft": [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)],
"helicopter": [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)],
"ship": [(0.0, 0.62), (0.25, 0.78), (0.85, 0.95)],
}
# Glass by its colour, for a paint that lifts even black hull paint: a dark
# colour (value at most `value`) whose blue is at least `blue` and
# `blue_over_red` times its red (the ship models' windows) is painted `grey`.
GLASS = {"ship": {"value": 0.08, "blue": 0.025, "blue_over_red": 2.5, "grey": 0.07}}
SUN_STRENGTH = 1.4
SKY_STRENGTH = 0.38
FILL_STRENGTH = 0.9
def paint_material(paint_ramp, solid=None, glass=None):
"""Neutral paint that keeps the model's light and dark parts apart."""
material = bpy.data.materials.new("paint")
material.use_nodes = True
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = nodes["Principled BSDF"]
bsdf.inputs["Roughness"].default_value = 0.6
if solid is not None:
bsdf.inputs["Base Color"].default_value = (solid, solid, solid, 1.0)
return material
colour = nodes.new("ShaderNodeVertexColor")
colour.layer_name = "Color"
split = nodes.new("ShaderNodeSeparateColor")
links.new(colour.outputs["Color"], split.inputs["Color"])
red_green = nodes.new("ShaderNodeMath")
red_green.operation = "MAXIMUM"
links.new(split.outputs[0], red_green.inputs[0])
links.new(split.outputs[1], red_green.inputs[1])
value = nodes.new("ShaderNodeMath")
value.operation = "MAXIMUM"
links.new(red_green.outputs[0], value.inputs[0])
links.new(split.outputs[2], value.inputs[1])
ramp = nodes.new("ShaderNodeValToRGB")
elements = ramp.color_ramp.elements
while len(elements) < len(paint_ramp):
elements.new(0.5)
for element, (position, grey) in zip(elements, paint_ramp):
element.position = position
element.color = (grey, grey, grey, 1.0)
links.new(value.outputs[0], ramp.inputs["Fac"])
if glass is None:
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
return material
def math_node(operation, a, b, c=None):
node = nodes.new("ShaderNodeMath")
node.operation = operation
for i, x in enumerate((a, b, c)):
if x is None:
continue
if isinstance(x, (int, float)):
node.inputs[i].default_value = x
else:
links.new(x, node.inputs[i])
return node.outputs[0]
dark = math_node("LESS_THAN", value.outputs[0], glass["value"] + 1e-4)
blue = math_node("GREATER_THAN", split.outputs[2], glass["blue"] - 1e-4)
red_scaled = math_node("MULTIPLY", split.outputs[0], glass["blue_over_red"])
over_red = math_node(
"GREATER_THAN", math_node("SUBTRACT", split.outputs[2], red_scaled), -1e-4
)
is_glass = math_node("MULTIPLY", math_node("MULTIPLY", dark, blue), over_red)
ramp_grey = nodes.new("ShaderNodeSeparateColor")
links.new(ramp.outputs["Color"], ramp_grey.inputs["Color"])
to_glass = math_node("SUBTRACT", glass["grey"], ramp_grey.outputs[0])
grey = math_node("MULTIPLY_ADD", is_glass, to_glass, ramp_grey.outputs[0])
combine = nodes.new("ShaderNodeCombineColor")
for i in range(3):
links.new(grey, combine.inputs[i])
links.new(combine.outputs["Color"], bsdf.inputs["Base Color"])
return material
def model_parts(path):
"""The part table in a fleet model's root node (`render/modelParts.js`)."""
with open(path, "rb") as f:
data = f.read()
length = struct.unpack("<I", data[12:16])[0]
document = json.loads(data[20 : 20 + length])
for node in document.get("nodes", []):
parts = (node.get("extras") or {}).get("parts")
if parts:
return parts
return []
def gltf_to_blender(v):
"""A glTF (Y up) vector in Blender's axes (Z up)."""
return Vector((v[0], -v[2], v[1]))
def turn_rotors(mesh, parts, degrees, rotor_material):
"""Pose the rotors and bound each vertex over its entire rotation."""
part_of = mesh.data.attributes.get("_PART")
if part_of is None:
return {}
mesh.data.materials.append(rotor_material)
swept_radii = {}
to_world = mesh.matrix_world
to_local = to_world.inverted()
for index, part in enumerate(parts):
if part.get("kind") != "spin" or not part["name"].startswith("rotor"):
continue
pivot = gltf_to_blender(part["pivot"])
axis = gltf_to_blender(part["axis"]).normalized()
turn = Matrix.Rotation(math.radians(degrees), 4, axis)
move = to_local @ Matrix.Translation(pivot) @ turn @ Matrix.Translation(-pivot) @ to_world
if part_of.domain == "POINT":
members = [i for i, item in enumerate(part_of.data) if item.value == index]
else:
members = sorted(
{
mesh.data.loops[i].vertex_index
for i, item in enumerate(part_of.data)
if item.value == index
}
)
for i in members:
vertex = mesh.data.vertices[i]
relative = to_world @ vertex.co - pivot
axial = relative.dot(axis)
center = pivot + axial * axis
# The sweep lies in a plane perpendicular to the axis. Its
# farthest point adds the circle radius to the projected center.
radial = (relative - axial * axis).length
offset = (center - center.dot(axis) * axis).length
swept_radii[i] = math.hypot(center.dot(axis), offset + radial)
vertex.co = move @ vertex.co
for polygon in mesh.data.polygons:
if all(i in swept_radii for i in polygon.vertices):
polygon.material_index = 1
return swept_radii
def reshape(mesh, waterline, beam, squash_above):
"""Bring a mesh into the scene's axes, cut away what lies below the
waterline (z = 0) and scale it across the beam and above a height."""
world = mesh.matrix_world.copy()
mesh.parent = None
mesh.matrix_world = Matrix.Identity(4)
mesh.data.transform(world)
bm = bmesh.new()
bm.from_mesh(mesh.data)
if waterline:
bmesh.ops.bisect_plane(
bm,
geom=bm.verts[:] + bm.edges[:] + bm.faces[:],
dist=1e-4,
plane_co=(0.0, 0.0, 0.0),
plane_no=(0.0, 0.0, 1.0),
clear_inner=True,
)
for vertex in bm.verts:
vertex.co.y *= beam
if squash_above and vertex.co.z > squash_above[0]:
height, k = squash_above
vertex.co.z = height + (vertex.co.z - height) * k
bm.to_mesh(mesh.data)
bm.free()
def load_model(path, material, rotor_deg, rotor_material, waterline=False, options=None):
options = options or {}
before = set(bpy.data.objects)
bpy.ops.import_scene.gltf(filepath=path)
objects = [o for o in bpy.data.objects if o not in before]
meshes = [o for o in objects if o.type == "MESH"]
bpy.context.view_layer.update()
parts = model_parts(path) if rotor_deg is not None else []
beam = options.get("beam", 1.0)
squash_above = options.get("squash_above")
radius = 0.0
for mesh in meshes:
if waterline or beam != 1.0 or squash_above:
reshape(mesh, waterline, beam, squash_above)
mesh.data.materials.clear()
mesh.data.materials.append(material)
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
for vertex in mesh.data.vertices:
distance = swept_radii.get(vertex.index)
if distance is None:
distance = (mesh.matrix_world @ vertex.co).length
radius = max(radius, distance)
return objects, radius
def aim(camera, fill, d, radius):
fill.rotation_euler = d.to_track_quat("Z", "Y").to_euler()
up = frame_up(d)
right = up.cross(d).normalized()
rotation = Matrix((right, up, d)).transposed()
camera.matrix_world = Matrix.Translation(d * (radius * 4 + 10)) @ rotation.to_4x4()
camera.data.ortho_scale = 2 * radius / FILL
# --- Pixels ------------------------------------------------------------------
def read_pixels(path):
image = bpy.data.images.load(path)
width, height = image.size
pixels = np.array(image.pixels[:], dtype=np.float32).reshape(height, width, 4)
bpy.data.images.remove(image)
return pixels[::-1] # top row first
def dilate(alpha, radius):
out = alpha.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
shifted = np.zeros_like(alpha)
ys = slice(max(dy, 0), alpha.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), alpha.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), alpha.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), alpha.shape[1] + min(-dx, 0))
shifted[ys, xs] = alpha[yd, xd]
np.maximum(out, shifted, out=out)
return out
def disk_sum(values, radius):
"""Each pixel's sum of `values` over a disk of `radius` around it."""
out = values.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
ys = slice(max(dy, 0), values.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), values.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), values.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), values.shape[1] + min(-dx, 0))
out[ys, xs] += values[yd, xd]
return out
# Neutral, as the whole sheet is: the renderer keeps it as grey + alpha.
EDGE_RGB = np.array([0.045, 0.045, 0.045], dtype=np.float32)
EDGE_ALPHA = 0.62
def inside_mask(size, supersample):
"""1 within the disk that keeps CLEAR_EDGE_PX of the cell clear, fading
to 0 over half a cell pixel inside its rim. Only what the bake adds round
the model (its thickening and dark edge) is faded by it: the model's own
bounding sphere ends at FILL, inside it."""
cell = size / supersample
centre = size / 2
y, x = np.mgrid[0:size, 0:size] + 0.5
r = np.hypot(x - centre, y - centre) / supersample
outer = cell / 2 - CLEAR_EDGE_PX
return np.clip((outer - r) / 0.5, 0, 1).astype(np.float32)
def finish(pixels, supersample, bold_px=0.0):
"""Thicken the sprite by `bold_px` cell pixels, put a dark edge round it,
then bring it down to the cell by area."""
rgb = pixels[..., :3]
alpha = pixels[..., 3]
premultiplied = rgb * alpha[..., None]
mask = inside_mask(pixels.shape[0], supersample)
radius = round(supersample * bold_px)
if radius > 0:
# Under the model, its own colour spread outward: each new pixel the
# mean colour of the model round it.
grown = dilate(alpha, radius) * mask
weight = disk_sum(alpha, radius)
spread = disk_sum(premultiplied, radius) / np.maximum(weight, 1e-6)[..., None]
under = grown * (1 - alpha)
premultiplied = premultiplied + spread * under[..., None]
alpha = alpha + under
# About 0.9 cell pixels of edge.
halo = dilate(alpha, max(1, round(supersample * 0.9))) * EDGE_ALPHA * mask
out_alpha = alpha + halo * (1 - alpha)
premultiplied = premultiplied + EDGE_RGB * (halo * (1 - alpha))[..., None]
size = pixels.shape[0] // supersample
def area(a):
return a.reshape(size, supersample, size, supersample, -1).mean(axis=(1, 3))
small_alpha = area(out_alpha[..., None])[..., 0]
small = area(premultiplied)
colour = np.where(
small_alpha[..., None] > 1e-4, small / np.maximum(small_alpha[..., None], 1e-4), 0
)
return np.dstack([np.clip(colour, 0, 1), np.clip(small_alpha, 0, 1)])
# How far a frame's red, green and blue may differ (in 0..1) before the bake
# refuses it as not grey: rendering noise, never a colour.
GREY_TOLERANCE = 1.5 / 255
def to_grey(frame, name, n):
"""The frame with equal red, green and blue (their mean), refusing one
whose channels differ by more than rendering noise: the sheet ships as
grey (`"grey": true`), its red channel read as the grey."""
rgb = frame[..., :3]
lit = frame[..., 3] > 0
spread = (rgb.max(axis=2) - rgb.min(axis=2))[lit]
if spread.size and spread.max() > GREY_TOLERANCE:
raise SystemExit(
f"{name} frame {n}: not grey (its channels differ by "
f"{spread.max() * 255:.1f}/255); the sheet ships as grey"
)
grey = rgb.mean(axis=2, keepdims=True)
return np.dstack([np.repeat(grey, 3, axis=2), frame[..., 3:]])
def check_clear_edge(frame, name, n):
"""Refuse a frame with anything but transparent pixels near its edge."""
e = CLEAR_EDGE_PX
alpha = frame[..., 3]
band = np.concatenate(
[alpha[:e].ravel(), alpha[-e:].ravel(), alpha[:, :e].ravel(), alpha[:, -e:].ravel()]
)
if band.max() >= 0.5 / 255:
raise SystemExit(
f"{name} frame {n}: pixels within {e} px of the cell edge "
f"(alpha {band.max():.3f}); the fill leaves them no room"
)
def save_png(path, pixels):
height, width = pixels.shape[:2]
image = bpy.data.images.new("out", width, height, alpha=True)
image.alpha_mode = "STRAIGHT"
image.pixels.foreach_set(pixels[::-1].astype(np.float32).ravel())
image.filepath_raw = path
image.file_format = "PNG"
image.save()
bpy.data.images.remove(image)
# --- Bake --------------------------------------------------------------------
def main():
opts = args_after_dashes()
config = SHEETS[opts["sheet"]]
name_of_sheet = config["name"]
columns = config["columns"]
subjects = config["subjects"]
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
models = os.path.join(root, "public", "models", "fleet")
cell = opts["cell"]
supersample = opts["supersample"]
only = set(opts["only"].split(",")) if opts["only"] else None
scene, camera, fill = setup_scene(cell * supersample, opts["samples"])
materials = {
key: paint_material(ramp, glass=GLASS.get(key)) for key, ramp in PAINTS.items()
}
rotor_material = paint_material(None, solid=0.82)
directions = frame_directions(config)
frames = len(directions)
tmp = os.path.join(bpy.app.tempdir, "view-frame.png")
rows = math.ceil(len(subjects) * frames / columns)
sheet = np.zeros((rows * cell, columns * cell, 4), dtype=np.float32)
manifest = {
"image": f"{name_of_sheet}.webp",
"cellPx": cell,
"columns": columns,
"rows": rows,
"ringStepDeg": config["ring_step_deg"],
"rings": config["rings"],
"fill": FILL,
# Every pixel's red, green and blue are equal.
"grey": True,
"subjects": {},
}
for index, (name, model, options) in enumerate(subjects):
first = index * frames
manifest["subjects"][name] = {"first": first, "model": model}
if only and name not in only:
continue
objects, radius = load_model(
os.path.join(models, model),
materials[options.get("paint", config["paint"])],
options.get("rotor_deg"),
rotor_material,
config["waterline"],
options,
)
manifest["subjects"][name]["radiusM"] = round(radius, 3)
for n, (ring, i, d) in enumerate(directions):
aim(camera, fill, d, radius)
scene.render.filepath = tmp
bpy.ops.render.render(write_still=True)
frame = finish(read_pixels(tmp), supersample, options.get("bold_px", 0.0))
check_clear_edge(frame, name, n)
frame = to_grey(frame, name, n)
at = first + n
y = (at // columns) * cell
x = (at % columns) * cell
sheet[y : y + cell, x : x + cell] = frame
if opts["preview"]:
os.makedirs(opts["preview"], exist_ok=True)
save_png(
os.path.join(opts["preview"], f"{name}-r{ring}-{i:02d}.png"), frame
)
for obj in objects:
bpy.data.objects.remove(obj, do_unlink=True)
print(f"baked {name}: {frames} frames, radius {radius:.2f} m", flush=True)
out = os.path.join(root, opts["out"]) if not os.path.isabs(opts["out"]) else opts["out"]
os.makedirs(out, exist_ok=True)
save_png(os.path.join(out, f"{name_of_sheet}.png"), sheet)
with open(os.path.join(out, f"{name_of_sheet}.json"), "w") as f:
json.dump(manifest, f, indent=1)
f.write("\n")
print(f"wrote {out}/{name_of_sheet}.png ({columns * cell}x{rows * cell})")
main()
-109
View File
@@ -1,109 +0,0 @@
#!/usr/bin/env node
/**
* build-view-sheet.mjs: bake a view sheet (aircraft or vessels) and ship it.
*
* Runs `scripts/bake-view-sheet.py` in Blender (headless) into a scratch
* directory, then writes the sheet to `public/sprites/` as
* `<name>.webp` (lossless WebP of the baked PNG) and `<name>.json` (its
* manifest): `aircraft-views` or `vessel-views`. See
* `public/sprites/README.md`.
*
* Run: node scripts/build-view-sheet.mjs --sheet aircraft|vessels
* [--only airliner,light] [--out public/sprites]
* (npm run build:aircraft-views, npm run build:vessel-views)
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
const ONLY = opt('--only', null);
const SHEET = opt('--sheet', null);
if (SHEET !== 'aircraft' && SHEET !== 'vessels')
throw new Error('--sheet is aircraft or vessels');
// A bake of some subjects leaves the others' cells empty: it is for looking
// at, never for the sheet the app loads.
if (ONLY && !argv.includes('--out'))
throw new Error(
'--only bakes part of a sheet: give it its own --out, not public/sprites',
);
function blender() {
if (process.env.BLENDER) return process.env.BLENDER;
const which = spawnSync('which', ['blender'], { encoding: 'utf8' });
if (which.status === 0 && which.stdout.trim()) return which.stdout.trim();
const mac = '/Applications/Blender.app/Contents/MacOS/Blender';
if (fs.existsSync(mac)) return mac;
throw new Error('no Blender: set BLENDER to its executable');
}
/**
* Refuse a sheet the manifest calls grey whose red, green and blue differ
* anywhere: the renderer reads its red channel as the grey.
*/
async function assertGrey(file) {
const { data, info } = await sharp(file)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
for (let i = 0; i < data.length; i += info.channels)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
const pixel = i / info.channels;
throw new Error(
`the sheet is not grey at (${pixel % info.width}, ${Math.floor(pixel / info.width)})`,
);
}
}
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'view-sheet-'));
try {
const bake = spawnSync(
blender(),
[
'-b',
'--factory-startup',
'--python',
path.join(root, 'scripts', 'bake-view-sheet.py'),
'--',
'--sheet',
SHEET,
'--out',
scratch,
...(ONLY ? ['--only', ONLY] : []),
],
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8' },
);
for (const line of bake.stdout.split('\n'))
if (/^(baked|wrote)\b/.test(line)) console.log(line);
if (bake.status !== 0) {
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
throw new Error(`the bake failed (exit ${bake.status})`);
}
const [json] = fs.readdirSync(scratch).filter((f) => f.endsWith('.json'));
const name = path.basename(json, '.json');
const manifest = JSON.parse(
fs.readFileSync(path.join(scratch, json), 'utf8'),
);
const png = path.join(scratch, `${name}.png`);
if (manifest.grey) await assertGrey(png);
fs.mkdirSync(OUT, { recursive: true });
const webp = path.join(OUT, manifest.image);
await sharp(png)
.webp({ lossless: true, effort: 6, exact: true })
.toFile(webp);
fs.copyFileSync(path.join(scratch, json), path.join(OUT, json));
const kb = Math.round(fs.statSync(webp).size / 1024);
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
} finally {
fs.rmSync(scratch, { recursive: true, force: true });
}
+1 -2
View File
@@ -80,8 +80,6 @@
"src/render/cesium/tileRequests.test.mjs",
"src/queries/heights.test.mjs",
"src/render/cesium/heights.test.mjs",
"src/render/cesium/drawLineAges.test.mjs",
"src/render/cesium/drawLineBreaks.test.mjs",
"docs/CODE-BOUNDARIES.md",
"src/main.js",
"docs/APPLICATION.md",
@@ -1216,6 +1214,7 @@
"src/sources/militaryTileGeometry.test.mjs",
"src/layers/traffic/surface.test.mjs",
"src/layers/traffic/roadModes.test.mjs",
"src/layers/traffic/flowDecode.test.mjs",
"scripts/qa-traffic-motion.mjs",
"src/layers/traffic/motion.test.mjs",
"scripts/qa-journey-recorder.mjs",
+29 -68
View File
@@ -68,8 +68,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1104,7 +1103,6 @@
"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",
@@ -1304,8 +1302,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/data/viewSheet.js"
"src/layers/satellites/tiangongMounts.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1346,7 +1343,6 @@
"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",
@@ -1717,8 +1713,7 @@
"src/data/liveStreams.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js",
"src/data/viewSheet.js"
"src/ui/liveControls.js"
],
"external": [
"cesium",
@@ -1922,8 +1917,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/scenes/storyTags.js",
"src/scenes/storyThumb.js",
"src/data/viewSheet.js"
"src/scenes/storyThumb.js"
],
"external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"]
},
@@ -2090,9 +2084,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/courseFromFixes.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2238,9 +2230,7 @@
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js",
"src/data/approxDistance.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/approxDistance.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2398,9 +2388,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
"src/data/openVesselPhoto.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2531,8 +2519,7 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/sky/assets.js",
"src/render/cesium/cardPreviews.js",
"src/data/viewSheet.js"
"src/render/cesium/cardPreviews.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2630,8 +2617,7 @@
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/time/frameWait.js",
"src/data/viewSheet.js"
"src/time/frameWait.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2783,8 +2769,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2907,8 +2892,7 @@
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/data/viewSheet.js"
"src/layers/satellites/tiangongArticulation.js"
],
"external": ["cesium", "satellite.js", "kdbush"]
},
@@ -3012,8 +2996,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3125,8 +3108,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3208,8 +3190,7 @@
"src/data/installationFeedback.js",
"src/ui/layerNames.js",
"src/render/cesium/zoomOutGuard.js",
"src/ui/statusText.js",
"src/data/viewSheet.js"
"src/ui/statusText.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3335,8 +3316,7 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
"src/render/vectorBase/expressions.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3530,8 +3510,7 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
"src/render/vectorBase/expressions.js"
],
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3661,8 +3640,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": [
"cesium",
@@ -3755,8 +3733,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3868,8 +3845,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3944,8 +3920,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -4086,8 +4061,7 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
"src/render/vectorBase/expressions.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -4821,7 +4795,6 @@
"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",
@@ -5621,10 +5594,7 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
"src/layers/satellites/tiangongArticulation.js"
],
"external": [
"hls.js",
@@ -6480,10 +6450,7 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js",
"src/data/vesselViews.js"
"src/layers/satellites/tiangongModel.js"
],
"external": [
"hls.js",
@@ -6632,8 +6599,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": [
"cesium",
@@ -6747,8 +6713,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -7583,8 +7548,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "egm96-universal", "pbf", "kdbush"]
},
@@ -7714,8 +7678,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "pbf", "kdbush"]
},
@@ -8027,8 +7990,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -8477,8 +8439,7 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/render/recession.js",
"src/render/modelParts.js",
"src/data/viewSheet.js"
"src/render/modelParts.js"
],
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
},
-382
View File
@@ -1,382 +0,0 @@
#!/usr/bin/env node
/**
* qa-aircraft-views.mjs: screenshots of the aircraft view sheet in the app.
*
* Seeds a grid of synthetic military contacts (every icon class down the
* rows, eight courses across) through a fetch shim, then photographs it from
* straight above, tilted from several sides and from below, so a person can
* check that each sprite shows its aircraft from where the camera is: the
* nose along the course, the far wing foreshortened, the underside from
* below.
*
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
* [--layer military|flights|vessels] [--block-sheet] [--headful]
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
* Needs the dev server (`npm run dev`).
*/
import fs from 'node:fs';
import path from 'node:path';
import puppeteer from 'puppeteer';
import { stubPlanespotters } from './qa-photo-stub.mjs';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const APP_URL = opt('--url', 'http://localhost:4173');
const OUT = path.resolve(opt('--out', 'qa-shots/views'));
const HEADFUL = argv.includes('--headful');
// `military` (amber, every class by type code), `flights` (white, the
// classes an ADS-B emitter category gives) or `vessels` (every hull kind by
// AIS ship type, at sea level).
const LAYER = opt('--layer', 'military');
const VESSELS = LAYER === 'vessels';
// The app's id of the layer.
const LAYER_ID = VESSELS ? 'ais-live-vessels' : LAYER;
// Fail the sheet's request: the contacts should draw their flat glyphs.
const BLOCK_SHEET = argv.includes('--block-sheet');
const GPU = argv.includes('--gpu');
// A type code for each icon class (aircraftClass.js).
const CLASSES = [
['airliner', 'A320'],
['widebody', 'C17'],
['quadjet', 'B744'],
['turboprop', 'C130'],
['light', 'C172'],
['glider', 'DISC'],
['fastjet', 'F16'],
['bizjet', 'GLF4'],
['uav', 'Q9'],
['helicopter', 'H60'],
];
// The classes a flight's emitter category gives (OpenSky has no type code).
const CATEGORIES = [
['airliner', 4],
['widebody', 6],
['light', 2],
['fastjet', 7],
['glider', 9],
['helicopter', 8],
];
// An AIS ship type for each hull kind (vesselTypes.js).
const HULLS = [
['cargo', 70],
['tanker', 80],
['passenger', 60],
['highspeed', 40],
['fishing', 30],
['tug', 52],
['sailing', 36],
['pleasure', 37],
['military', 35],
['other', 90],
['dredger', 33],
['pilot', 50],
];
const ROWS = VESSELS ? HULLS : LAYER === 'flights' ? CATEGORIES : CLASSES;
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
// Aircraft over Austin; vessels on open water in the North Sea.
const CENTRE = VESSELS ? { lon: 3.2, lat: 52.6 } : { lon: -97.74, lat: 30.3 };
const STEP_DEG = 0.03;
const ALT_FT = VESSELS ? 0 : 12000;
const contacts = [];
ROWS.forEach(([klass, type], row) =>
COURSES.forEach((courseDeg, column) =>
contacts.push({
hex: `ee${row.toString(16)}${column.toString(16)}00`.slice(0, 6),
flight: `${klass.slice(0, 4).toUpperCase()}${courseDeg}`,
t: type,
klass,
courseDeg,
lon: CENTRE.lon + (column - (COURSES.length - 1) / 2) * STEP_DEG,
lat: CENTRE.lat - (row - (ROWS.length - 1) / 2) * STEP_DEG,
altFt: ALT_FT,
}),
),
);
// Each shot: where the camera looks from. `heading` is the way it looks
// (degrees clockwise from north), `pitch` down from level, `rangeKm` from
// the grid's centre at the contacts' height.
const SHOTS = [
{ name: '1-above', heading: 0, pitch: -90, rangeKm: 44 },
{ name: '2-tilt30-north', heading: 0, pitch: -60, rangeKm: 46 },
{ name: '3-tilt55-north', heading: 0, pitch: -35, rangeKm: 50 },
{ name: '4-tilt55-east', heading: 90, pitch: -35, rangeKm: 50 },
{ name: '5-tilt55-southwest', heading: 225, pitch: -35, rangeKm: 50 },
{ name: '6-tilt75-north', heading: 0, pitch: -15, rangeKm: 52 },
// From below, looking up at the grid; a vessel is never seen from there,
// so vessels get a shot from just above the water in its place.
VESSELS
? { name: '7-horizon-north', heading: 0, pitch: -5, rangeKm: 30 }
: { name: '7-below-north', heading: 0, pitch: 12, rangeKm: 15.5 },
];
// `--orbit`: the camera swung round the grid a little at a time, a frame
// each step, to watch the sprites turn from one view to the next.
const ORBIT_STEP_DEG = Number(opt('--orbit-step', 2));
const ORBIT_SHOTS = Array.from(
{ length: Math.floor(90 / ORBIT_STEP_DEG) + 1 },
(_, i) => ({
name: `orbit-${String(i).padStart(3, '0')}`,
heading: i * ORBIT_STEP_DEG,
pitch: Number(opt('--orbit-pitch', -35)),
rangeKm: 50,
settleMs: i === 0 ? 6000 : 900,
}),
);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
fs.mkdirSync(OUT, { recursive: true });
const browser = await puppeteer.launch({
headless: HEADFUL ? false : 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
...(GPU ? [] : ['--use-gl=angle', '--use-angle=swiftshader']),
'--disable-web-security',
'--disable-background-timer-throttling',
'--disable-renderer-backgrounding',
'--window-size=1500,1000',
],
});
const errors = [];
try {
const page = await browser.newPage();
await stubPlanespotters(page);
await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 2 });
page.on('console', (msg) => {
if (
msg.type() === 'error' &&
!/Failed to load resource/i.test(msg.text())
)
errors.push(msg.text());
});
page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
if (BLOCK_SHEET) {
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.isInterceptResolutionHandled()) return;
if (/\/sprites\/[a-z]+-views\./.test(request.url())) request.abort();
else request.continue();
});
}
await page.evaluateOnNewDocument(
(seed) => {
const realFetch = window.fetch.bind(window);
// Each contact flies its course, slowly: a feed whose fixes stand
// still while claiming a track makes the layers work a heading out
// of no movement, and the contacts turn north over a run.
const SPEED_MPS = 6;
const started = Date.now();
const at = (c) => {
const flown = (SPEED_MPS * (Date.now() - started)) / 1000;
const course = (c.courseDeg * Math.PI) / 180;
return {
lat: c.lat + (flown * Math.cos(course)) / 111320,
lon:
c.lon +
(flown * Math.sin(course)) /
(111320 * Math.cos((c.lat * Math.PI) / 180)),
};
};
const json = (body) =>
new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
window.fetch = (input, init) => {
const url =
typeof input === 'string' ? input : (input && input.url) || '';
if (url.includes('/api/openai/hud-summary'))
return Promise.resolve(json({ summary: 'view QA' }));
if (url.includes('/api/military/track'))
return Promise.resolve(
json({ timestamp: Math.floor(Date.now() / 1000), trace: [] }),
);
if (url.includes('/api/military'))
return Promise.resolve(
json({
msg: 'No error',
now: Date.now(),
ac: (seed.layer === 'military' ? seed.contacts : []).map(
(c) => ({
hex: c.hex,
flight: c.flight,
...at(c),
alt_baro: c.altFt,
track: c.courseDeg,
gs: SPEED_MPS * 1.9438,
t: c.t,
r: `QA-${c.hex.slice(-3)}`,
ownOp: 'QA',
seen_pos: 0,
}),
),
}),
);
if (url.includes('/api/vessels') && seed.layer === 'vessels') {
const now = Date.now();
return Promise.resolve(
json({
rows: seed.contacts.map((c, i) => ({
...at(c),
name: c.flight,
mmsi: String(235000000 + i),
imo: '0',
type: String(c.t),
destination: 'QA',
length: 120,
beam: 20,
speed: SPEED_MPS * 1.9438,
course: c.courseDeg,
heading: c.courseDeg,
last_position_UTC: new Date(now).toISOString(),
last_position_epoch: Math.floor(now / 1000),
})),
source: 'AISStream',
status: 'live',
error: null,
refreshing: false,
newestPositionAt: now,
lastMessageAt: now,
silentForMs: 0,
reconnectAttempt: 0,
nextAttemptAt: null,
staleAfterMs: 120000,
watchdog: 'armed',
}),
);
}
if (url.includes('/api/flights/track'))
return Promise.resolve(json({ path: [] }));
if (url.includes('/api/flights') && seed.layer === 'flights') {
const now = Math.floor(Date.now() / 1000);
return Promise.resolve(
json({
time: now,
states: seed.contacts.map((c) => [
c.hex,
c.flight,
'QA',
now,
now,
at(c).lon,
at(c).lat,
c.altFt * 0.3048,
false,
SPEED_MPS,
c.courseDeg,
0,
null,
null,
null,
false,
0,
c.t,
]),
}),
);
}
if (url.includes('/api/adsbdb/'))
return Promise.resolve(json({ found: false }));
return realFetch(input, init);
};
},
{ layer: LAYER, contacts },
);
console.log(`Loading ${APP_URL} ...`);
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForFunction(
() => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager,
{ timeout: 60000, polling: 200 },
);
const seeded = await page.evaluate(
async (name, centre) => {
const { dataManager, viewer } = window.__godsEyeView;
// Over the grid first: a layer may ask only for what is in view.
const Cartesian3 = viewer.camera.position.constructor;
viewer.camera.setView({
destination: Cartesian3.fromDegrees(centre.lon, centre.lat, 60000),
});
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) {
await layer.update(viewer);
await new Promise((resolve) => setTimeout(resolve, 500));
}
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
},
LAYER_ID,
CENTRE,
);
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
if (seeded !== contacts.length)
throw new Error(
`the ${LAYER} layer took ${seeded} of ${contacts.length} contacts`,
);
// Past the layer's render delay, so every contact is drawn.
await sleep(20000);
for (const shot of argv.includes('--orbit') ? ORBIT_SHOTS : SHOTS) {
await page.evaluate(
({ shot, centre, altM }) => {
const { viewer } = window.__godsEyeView;
const Cartesian3 = viewer.camera.position.constructor;
const heading = (shot.heading * Math.PI) / 180;
const pitch = (shot.pitch * Math.PI) / 180;
const range = shot.rangeKm * 1000;
// The eye sits `range` back along the way it looks.
const east = -range * Math.sin(heading) * Math.cos(pitch);
const north = -range * Math.cos(heading) * Math.cos(pitch);
const up = -range * Math.sin(pitch);
const lat = centre.lat + north / 111320;
const lon =
centre.lon +
east / (111320 * Math.cos((centre.lat * Math.PI) / 180));
viewer.camera.setView({
destination: Cartesian3.fromDegrees(
lon,
lat,
Math.max(50, altM + up),
),
orientation: { heading, pitch, roll: 0 },
});
viewer.scene.requestRender();
},
{ shot, centre: CENTRE, altM: ALT_FT * 0.3048 },
);
await sleep(shot.settleMs ?? 6000);
// The globe's own canvas, read right after a render: no HUD, dialogs
// or label overlays in the way.
const png = await page.evaluate(() => {
const { viewer } = window.__godsEyeView;
viewer.scene.render();
return viewer.scene.canvas.toDataURL('image/png');
});
const file = path.join(OUT, `${shot.name}.png`);
fs.writeFileSync(file, Buffer.from(png.split(',')[1], 'base64'));
console.log(` wrote ${file}`);
}
} finally {
await browser.close();
}
if (errors.length) {
console.log(`\nConsole errors (${errors.length}):`);
for (const error of errors.slice(0, 20)) console.log(` ${error}`);
process.exitCode = 1;
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
-198
View File
@@ -1,198 +0,0 @@
#!/usr/bin/env node
/**
* qa-view-sheet.mjs: contact sheets of a baked view sheet (aircraft or
* vessels), for reviewing a bake (`scripts/bake-view-sheet.py`) before it
* ships.
*
* For each subject it writes one image: its frames with the rings as rows
* (straight above at the top, the last ring at the bottom, each ring from
* dead ahead to dead astern), in white, over three grounds the subject is
* seen over. Under them, a few frames (above, oblique, abeam, and below or
* low on the horizon) shrunk to the sizes a contact is drawn at, in each
* tint the layers draw it with, to judge whether thin wings and hulls still
* read. Aircraft: a dark sea, pale land and a mid satellite tone; the fleet,
* tracked and military tints. Vessels: a dark sea, pale shallow water and a
* satellite ocean tone; white and the colour of each kind the subject is
* drawn for (`VESSEL_KIND_STYLES`).
*
* Run: node scripts/qa-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/<name>] [--zoom 2] [--sizes 40,30,20]
* [--only airliner,glider]
* `--sheet` defaults to the manifest's `image`, next to it.
*/
import fs from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
import { VESSEL_KIND_STYLES } from '../src/data/vesselTypes.js';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const MANIFEST = path.resolve(
opt('--manifest', 'public/sprites/aircraft-views.json'),
);
const ZOOM = Number(opt('--zoom', '2'));
const SIZES = opt('--sizes', '40,30,20').split(',').map(Number);
const ONLY = opt('--only', '').split(',').filter(Boolean);
const GAP = 8;
const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
const VESSELS = manifest.image.startsWith('vessel');
const OUT = path.resolve(
opt('--out', `qa-shots/${path.basename(manifest.image, '.webp')}`),
);
const WHITE = { name: 'white', rgb: [1, 1, 1] };
/** `#rrggbb` as 0..1 channels. */
const rgbOf = (css) =>
[1, 3, 5].map((i) => parseInt(css.slice(i, i + 2), 16) / 255);
/** Grounds a contact is seen over. */
const GROUNDS = VESSELS
? [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'shallows', css: '#8fc3c1' },
{ name: 'satellite', css: '#0f2e44' },
]
: [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The kinds a vessel shape that is not a kind of its own is coloured as: a
* vessel takes its kind's colour (`vesselKind`), whatever its shape. */
const SHAPE_KINDS = { dredger: ['other'], pilot: ['tug', 'military'] };
/** A subject's tints, multiplied into the neutral sprite as the layers do. */
const tintsOf = (name) =>
VESSELS
? [
WHITE,
...(SHAPE_KINDS[name] ?? [name]).map((kind) => ({
name: kind,
rgb: rgbOf(VESSEL_KIND_STYLES[kind].css),
})),
]
: [
WHITE,
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const sheetPath = path.resolve(
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
);
const { cellPx: cell, columns, rings } = manifest;
const firsts = [];
rings.reduce((at, count) => (firsts.push(at), at + count), 0);
const widest = Math.max(...rings);
/** The ring nearest `offDeg` from straight above. */
const ringAt = (offDeg) =>
Math.min(rings.length - 1, Math.round(offDeg / manifest.ringStepDeg));
const last = rings.length - 1;
/** Frames shown shrunk, as ring and index: straight above, oblique from
* ahead and to the right, abeam on the horizon, and the last ring from
* below abeam or, if the last ring is the horizon, from the bow quarter. */
const PICKS = [
[0, 0],
[ringAt(45), Math.floor((rings[ringAt(45)] - 1) / 3)],
[ringAt(90), Math.round((rings[ringAt(90)] - 1) / 2)],
last === ringAt(90)
? [last, Math.round((rings[last] - 1) / 4)]
: [last, Math.round((rings[last] - 1) / 2)],
];
const sheet = sharp(sheetPath, { limitInputPixels: false });
const { data: pixels, info } = await sheet
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
/** One cell as raw RGBA, tinted. */
function cellPixels(index, tint) {
const out = Buffer.alloc(cell * cell * 4);
const left = (index % columns) * cell;
const top = Math.floor(index / columns) * cell;
for (let y = 0; y < cell; y++)
for (let x = 0; x < cell; x++) {
const from = ((top + y) * info.width + left + x) * 4;
const to = (y * cell + x) * 4;
for (let c = 0; c < 3; c++)
out[to + c] = Math.round(pixels[from + c] * tint.rgb[c]);
out[to + 3] = pixels[from + 3];
}
return out;
}
async function cellImage(index, tint, size) {
let image = sharp(cellPixels(index, tint), {
raw: { width: cell, height: cell, channels: 4 },
});
if (size !== cell) image = image.resize(size, size, { kernel: 'lanczos3' });
else if (ZOOM !== 1)
image = image.resize(cell * ZOOM, cell * ZOOM, { kernel: 'nearest' });
return image.png().toBuffer();
}
async function subjectSheet(name, first) {
const TINTS = tintsOf(name);
const tile = cell * ZOOM;
const panelW = widest * tile;
const panelH = rings.length * tile;
const stripH = Math.max(...SIZES) + GAP;
const blockH = panelH + GAP + TINTS.length * stripH;
const width = GROUNDS.length * (panelW + GAP) + GAP;
const height = blockH + 2 * GAP;
const layers = [];
for (const [g, ground] of GROUNDS.entries()) {
const x0 = GAP + g * (panelW + GAP);
layers.push({
input: {
create: {
width: panelW,
height: blockH,
channels: 4,
background: ground.css,
},
},
left: x0,
top: GAP,
});
// Rings as rows, white.
for (let ring = 0; ring < rings.length; ring++)
for (let i = 0; i < rings[ring]; i++)
layers.push({
input: await cellImage(first + firsts[ring] + i, WHITE, cell),
left: x0 + i * tile,
top: GAP + ring * tile,
});
// The picked frames shrunk to drawn sizes, one row a tint.
for (const [t, tint] of TINTS.entries()) {
let x = x0 + GAP;
const y = GAP + panelH + GAP + t * stripH;
for (const [ring, index] of PICKS)
for (const size of SIZES) {
layers.push({
input: await cellImage(first + firsts[ring] + index, tint, size),
left: x,
top: y + (stripH - GAP - size),
});
x += size + 4;
}
}
}
const file = path.join(OUT, `${name}.png`);
await sharp({
create: { width, height, channels: 4, background: '#111111' },
})
.composite(layers)
.png()
.toFile(file);
return file;
}
fs.mkdirSync(OUT, { recursive: true });
for (const [name, entry] of Object.entries(manifest.subjects)) {
if (ONLY.length && !ONLY.includes(name)) continue;
const first = typeof entry === 'number' ? entry : entry.first;
console.log('wrote', await subjectSheet(name, first));
}
+12 -97
View File
@@ -1,8 +1,4 @@
import {
readResponseBytesCapped,
readResponseTextCapped,
} from './common/http.js';
import { JTWC_USABLE_MS, readJtwcStorms } from './jtwc.js';
import { readResponseTextCapped } from './common/http.js';
const STATUS_URL = 'https://www.nhc.noaa.gov/CurrentStorms.json';
const GIS =
@@ -11,14 +7,7 @@ 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 =
'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;
}
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
const LAYERS = [
{ id: 5, cap: 512 * 1024, count: 500, kind: 'points' },
{ id: 6, cap: 512 * 1024, count: 32, kind: 'track' },
@@ -125,7 +114,6 @@ 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(),
@@ -150,7 +138,6 @@ export function parseCycloneStatus(payload, now = Date.now()) {
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
});
}
@@ -275,13 +262,8 @@ 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) {
@@ -304,64 +286,7 @@ 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(),
@@ -398,14 +323,6 @@ 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;
@@ -448,8 +365,9 @@ export function cycloneProxy({
function describe(value, stale = false) {
return {
schemaVersion: 1,
source: SOURCE,
attribution: ATTRIBUTION,
source: 'NOAA NHC / CPHC',
attribution:
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center',
coverage: COVERAGE,
fetchedAt: value?.fetchedAt ?? null,
stale: stale || !value,
@@ -484,16 +402,13 @@ export function cycloneProxy({
json(200, describe(await acquire(controller.signal)));
} catch (error) {
if (error.status === 429) return json(429, { error: 'cyclone_busy' });
// 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));
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));
}
} finally {
res.removeListener?.('close', close);
-459
View File
@@ -1,459 +0,0 @@
import { inflateRawSync } from 'node:zlib';
/**
* Joint Typhoon Warning Center (JTWC) warnings for the cyclone layer: the
* western North Pacific, North Indian Ocean and Southern Hemisphere, where
* NHC and CPHC issue none. Keyless; US government work.
*
* rss/jtwc.rss current warnings, product links in each item
* products/<prefix>.tcw JMV 3.0 warning data (position, forecast, text)
* products/<prefix>.kmz Google Earth overlay: the 34-knot danger swath
*
* JTWC publishes no schema for any of these. Each reader takes only what it
* recognises and throws on a product that lacks it. The danger swath is the
* swath of 34-knot winds widened by forecast track error; it is drawn as its
* own area (`dangerArea`), never as a cone of centre-track uncertainty.
*/
export const JTWC_ORIGIN = 'https://www.metoc.navy.mil';
export const JTWC_RSS_URL = `${JTWC_ORIGIN}/jtwc/rss/jtwc.rss`;
export const JTWC_PRODUCTS_URL = `${JTWC_ORIGIN}/jtwc/products`;
const WARNING_ITEMS = [
'NWPAC-NIO-WARNINGS',
'EPAC-CPAC-WARNINGS',
'SH-WARNINGS',
];
const NO_WARNINGS = 'No Current Tropical Cyclone Warnings';
const PREFIX = /^(?:wp|io|sh|ep|cp)\d{4}$/;
const HOUR = 3600_000;
/**
* A JTWC warning is usable for 13 hours after issuance: some storms are on
* 12-hourly warnings, and the next one posts shortly before its time.
*/
export const JTWC_USABLE_MS = 13 * HOUR;
const KML_MAX_BYTES = 4 * 1024 * 1024;
function invalid(what) {
return new Error(`invalid_jtwc_data: ${what}`);
}
/** Storm product prefixes (`sh0427`) the feed lists, in feed order. */
export function parseJtwcFeed(feed) {
if (typeof feed !== 'string' || !feed.includes('<rss')) throw invalid('feed');
const prefixes = [];
for (const guid of WARNING_ITEMS) {
const item = feed
.split('<item>')
.slice(1)
.map((part) => part.split('</item>')[0])
.find((part) => part.includes(`<guid>${guid}</guid>`));
if (!item) throw invalid(`feed item ${guid}`);
const found = [
...item.matchAll(
/\/jtwc\/products\/([a-z]{2}\d{4})(?:web\.txt|\.tcw|\.kmz)/g,
),
]
.map((match) => match[1])
.filter((prefix) => PREFIX.test(prefix));
if (!found.length && !item.includes(NO_WARNINGS))
throw invalid(`feed item ${guid}`);
for (const prefix of found)
if (!prefixes.includes(prefix)) prefixes.push(prefix);
}
return prefixes;
}
/** `sh0427` is ATCF `sh042027` (the season year). */
export function jtwcStormId(prefix) {
if (!PREFIX.test(prefix)) throw invalid('prefix');
return `${prefix.slice(0, 4)}20${prefix.slice(4)}`;
}
// JTWC's words for a storm, longest first, and their codes.
const KINDS = [
['SUPER TYPHOON', 'STY'],
['SUBTROPICAL STORM', 'SS'],
['SUBTROPICAL DEPRESSION', 'SD'],
['TROPICAL CYCLONE', 'TC'],
['TROPICAL STORM', 'TS'],
['TROPICAL DEPRESSION', 'TD'],
['TYPHOON', 'TY'],
['HURRICANE', 'HU'],
];
/** `115S` / `1642W` (tenths) or `11.6S` (degrees); south and west negative. */
function coordinate(word, tenths) {
const match = /^(\d+(?:\.\d+)?)([NSEW])$/.exec(word || '');
if (!match || (tenths && match[1].includes('.'))) return null;
const value = Number(match[1]) / (tenths ? 10 : 1);
const limit = 'NS'.includes(match[2]) ? 90 : 180;
if (!(value <= limit)) return null;
return 'SW'.includes(match[2]) ? -value : value;
}
function utc(year, month, day, hour, minute = 0) {
const at = Date.UTC(year, month - 1, day, hour, minute);
const date = new Date(at);
return date.getUTCDate() === day && date.getUTCHours() === hour ? at : NaN;
}
/** `ddhhmm` (optionally `Z`-suffixed) as the time nearest `near`. */
function nearest(dtg, near) {
const match = /^(\d\d)(\d\d)(\d\d)Z?[.,]?$/.exec(dtg || '');
if (!match) return NaN;
const base = new Date(near);
let best = NaN;
for (const offset of [-1, 0, 1]) {
const month = new Date(
Date.UTC(base.getUTCFullYear(), base.getUTCMonth() + offset, 1),
);
const at = utc(
month.getUTCFullYear(),
month.getUTCMonth() + 1,
Number(match[1]),
Number(match[2]),
Number(match[3]),
);
if (
Number.isFinite(at) &&
(!Number.isFinite(best) || Math.abs(at - near) < Math.abs(best - near))
)
best = at;
}
return best;
}
const iso = (ms) => new Date(ms).toISOString();
function titleCase(name) {
return name
.toLowerCase()
.replace(
/(^|[\s-])([a-z])/g,
(_, gap, letter) => gap + letter.toUpperCase(),
);
}
/**
* One storm's warning (`.tcw`) as a cyclone-snapshot storm, its geometry
* pending until `withJtwcDangerArea` gives it the warning's danger swath.
* Throws on a warning without its header, hour 0 or subject.
*/
export function parseJtwcWarning(prefix, text) {
const id = jtwcStormId(prefix);
if (typeof text !== 'string') throw invalid('tcw');
const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, ''));
const dtg = lines[0]?.split(/\s+/)[2];
const headerAt = lines.findIndex((line) => /^\d{10}\s/.test(line));
if (headerAt < 0 || !dtg) throw invalid('tcw header');
const header = lines[headerAt].split(/\s+/);
const synopticAt = utc(
Number(header[0].slice(0, 4)),
Number(header[0].slice(4, 6)),
Number(header[0].slice(6, 8)),
Number(header[0].slice(8, 10)),
);
if (!Number.isFinite(synopticAt)) throw invalid('tcw synoptic time');
const number = header[1];
let at = 2;
const nameWords = [];
while (at < header.length && !/^\d+$/.test(header[at]))
nameWords.push(header[at++]);
const numbers = header.slice(at);
const warningMatch = /^0*(\d{1,3})$/.exec(numbers[0] || '');
if (!warningMatch || !number) throw invalid('tcw warning number');
const advisoryNumber = String(Number(warningMatch[1]));
const issuedAt = nearest(dtg, synopticAt);
if (!Number.isFinite(issuedAt)) throw invalid('tcw message time');
const direction = Number(numbers[2]);
const speed = Number(numbers[3]);
const forecast = [];
for (const line of lines.slice(headerAt + 1)) {
const words = line.trim().split(/\s+/);
const tau = /^T(\d{3})$/.exec(words[0]);
if (!tau) break;
const latitude = coordinate(words[1], true);
const longitude = coordinate(words[2], true);
const windKt = Number(words[3]);
if (latitude === null || longitude === null || !/^\d+$/.test(words[3]))
throw invalid('tcw forecast line');
forecast.push({
position: { longitude, latitude },
tauHours: Number(tau[1]),
windKt,
gustKt: null,
});
}
if (forecast[0]?.tauHours !== 0) throw invalid('tcw hour 0');
const subjectAt = lines.findIndex((line) => /^\s*SUBJ/.test(line));
if (subjectAt < 0) throw invalid('tcw subject');
const subject = lines[subjectAt]
.replace(/^\s*SUBJ[:/]?/, '')
.replace(/\/+$/, '')
.trim();
let end = lines.findIndex((line, i) => i > subjectAt && line.trim() === '//');
if (end < 0) end = lines.length;
const body = lines.slice(subjectAt, end);
let tau = null;
for (const line of body) {
const trimmed = line.trim();
const hours = /^(\d+) HRS, VALID AT:$/.exec(trimmed);
if (trimmed.startsWith('WARNING POSITION')) tau = 0;
else if (hours) tau = Number(hours[1]);
else {
const gust = /GUSTS (\d+) KT/.exec(trimmed);
const point = gust && forecast.find((p) => p.tauHours === tau);
if (point && point.gustKt === null) point.gustKt = Number(gust[1]);
}
}
const remarksAt = body.findIndex((line) => /^\s*REMARKS/.test(line));
const remarks = (remarksAt < 0 ? [] : body.slice(remarksAt))
.join(' ')
.replace(/\s+/g, ' ');
const issue = /(\d{6})Z POSITION NEAR (\d+\.\d)([NS]) (\d+\.\d)([EW])/.exec(
remarks,
);
const issueAt = issue ? nearest(issue[1], synopticAt) : NaN;
const pressure = /CENTRAL PRESSURE AT \d{6}Z IS (\d{3,4}) MB/.exec(remarks);
const kind = KINDS.find(([words]) => subject.includes(words));
const first = forecast[0];
const position =
issue && Number.isFinite(issueAt)
? {
longitude: coordinate(`${issue[4]}${issue[5]}`, false),
latitude: coordinate(`${issue[2]}${issue[3]}`, false),
}
: first.position;
if (position.longitude === null || position.latitude === null)
throw invalid('tcw position');
const basin = id.slice(0, 2);
const longitude = position.longitude;
const outlook =
basin === 'io' || (basin === 'sh' && longitude >= 0 && longitude < 135)
? 'abioweb.txt'
: basin === 'wp' || basin === 'sh'
? 'abpwweb.txt'
: null;
const pressureHpa = pressure ? Number(pressure[1]) : null;
const storm = {
id,
agency: 'jtwc',
name: nameWords.length ? titleCase(nameWords.join(' ')) : number,
classification: kind ? kind[1] : 'TC',
basin: basin.toUpperCase(),
position,
positionAt: iso(Number.isFinite(issueAt) ? issueAt : synopticAt),
advisoryNumber,
issuedAt: iso(issuedAt),
windKt: first.windKt <= 300 ? first.windKt : null,
pressureHpa:
pressureHpa !== null && pressureHpa >= 800 && pressureHpa <= 1100
? pressureHpa
: null,
movement: {
directionDegrees:
Number.isInteger(direction) && direction <= 360 ? direction : null,
speedKt: Number.isInteger(speed) && speed <= 200 ? speed : null,
},
advisoryUrl: `${JTWC_PRODUCTS_URL}/${prefix}web.txt`,
outlookUrl: outlook ? `${JTWC_PRODUCTS_URL}/${outlook}` : null,
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
return { storm, forecast };
}
/**
* The storm with its forecast geometry, current only with the danger swath
* of its own warning number (JTWC posts the overlay before the text).
*/
export function withJtwcDangerArea({ storm, forecast }, overlay) {
if (
!overlay ||
overlay.advisoryNumber !== storm.advisoryNumber ||
!overlay.dangerArea ||
forecast.length < 2
)
return storm;
return {
...storm,
geometryStatus: 'current',
geometryAdvisoryNumber: storm.advisoryNumber,
forecastPoints: forecast.map((point) => ({
position: { ...point.position },
tauHours: point.tauHours,
windKt: point.windKt,
gustKt: point.gustKt,
})),
track: {
type: 'LineString',
coordinates: forecast.map((point) => [
point.position.longitude,
point.position.latitude,
]),
},
dangerArea: overlay.dangerArea,
};
}
/** The warning number and 34-knot danger swath of a warning's KML. */
export function parseJtwcKml(kml) {
if (typeof kml !== 'string') throw invalid('kml');
const number = /WARNING NR\s+0*(\d{1,3})\b/.exec(kml);
if (!number) throw invalid('kml warning number');
const polygons = [];
for (const part of kml.split('<Placemark').slice(1)) {
const placemark = part.split('</Placemark>')[0];
const name = /<name>([^<]*)<\/name>/.exec(placemark)?.[1] || '';
if (!/^\s*34 knot Danger Swath/i.test(name)) continue;
for (const polygonPart of placemark.split('<Polygon').slice(1)) {
const polygon = polygonPart.split('</Polygon>')[0];
const rings = [
...polygon.matchAll(/<coordinates>([\s\S]*?)<\/coordinates>/g),
]
.map((match) => ring(match[1]))
.filter(Boolean);
if (rings.length) polygons.push(rings);
}
}
return {
advisoryNumber: String(Number(number[1])),
dangerArea: !polygons.length
? null
: polygons.length === 1
? { type: 'Polygon', coordinates: polygons[0] }
: { type: 'MultiPolygon', coordinates: polygons },
};
}
/**
* `longitude` in -180..180 (180 stays 180). JTWC writes a ring crossing the
* antimeridian with longitudes past ±180 (`181.5`); wrapped, the ring crosses
* 180° as NHC's cones that cross it do.
*/
export function wrapJtwcLongitude(longitude) {
if (Math.abs(longitude) <= 180) return longitude;
const wrapped = ((((longitude + 180) % 360) + 360) % 360) - 180;
// JTWC writes two decimals; this drops the float noise of the wrap.
return Math.round(wrapped * 1e6) / 1e6;
}
function ring(text) {
const points = [];
for (const tuple of text.trim().split(/\s+/)) {
const [lon, lat] = tuple.split(',').map(Number);
if (
!Number.isFinite(lon) ||
!Number.isFinite(lat) ||
Math.abs(lon) > 540 ||
Math.abs(lat) > 90
)
return null;
points.push([wrapJtwcLongitude(lon), lat]);
}
if (!points.length) return null;
const [a, b] = [points[0], points.at(-1)];
if (a[0] !== b[0] || a[1] !== b[1]) points.push([...a]);
return points.length >= 4 ? points : null;
}
/**
* The first `.kml` entry of a KMZ (a zip), from its central directory.
* Stored and deflated entries only.
*/
export function kmlFromKmz(bytes) {
const data = Buffer.from(bytes);
let end = -1;
for (let i = data.length - 22; i >= Math.max(0, data.length - 65_557); i--)
if (data.readUInt32LE(i) === 0x06054b50) {
end = i;
break;
}
if (end < 0) throw invalid('kmz');
const entries = data.readUInt16LE(end + 10);
let at = data.readUInt32LE(end + 16);
for (let n = 0; n < entries; n++) {
if (at + 46 > data.length || data.readUInt32LE(at) !== 0x02014b50)
throw invalid('kmz directory');
const method = data.readUInt16LE(at + 10);
const compressed = data.readUInt32LE(at + 20);
const size = data.readUInt32LE(at + 24);
const nameLength = data.readUInt16LE(at + 28);
const extra = data.readUInt16LE(at + 30);
const comment = data.readUInt16LE(at + 32);
const local = data.readUInt32LE(at + 42);
const name = data.toString('utf8', at + 46, at + 46 + nameLength);
at += 46 + nameLength + extra + comment;
if (!name.toLowerCase().endsWith('.kml')) continue;
if (size > KML_MAX_BYTES || data.readUInt32LE(local) !== 0x04034b50)
throw invalid('kmz entry');
const start =
local +
30 +
data.readUInt16LE(local + 26) +
data.readUInt16LE(local + 28);
const raw = data.subarray(start, start + compressed);
if (method === 0) return raw.toString('utf8');
if (method === 8)
return inflateRawSync(raw, { maxOutputLength: KML_MAX_BYTES }).toString(
'utf8',
);
throw invalid('kmz compression');
}
throw invalid('kmz holds no kml');
}
/**
* Every storm JTWC lists, through `read(url, kind)` (kind `text` or
* `bytes`). A feed that cannot be read throws. One storm never stops the
* others: a warning that cannot be read or parsed leaves that storm out,
* and only when every listed storm's fails does the read throw. An overlay
* that cannot be read leaves its storm's geometry `unavailable`, and one
* JTWC has not posted yet (`read` resolving null), or posted for another
* warning, leaves it `pending`.
*/
export async function readJtwcStorms(read, now = Date.now()) {
const prefixes = parseJtwcFeed(await read(JTWC_RSS_URL, 'text'));
// Each storm's warning and overlay are read at once, every storm alike.
const readStorm = async (prefix) => {
const [text, overlay] = await Promise.all([
read(`${JTWC_PRODUCTS_URL}/${prefix}.tcw`, 'text'),
read(`${JTWC_PRODUCTS_URL}/${prefix}.kmz`, 'bytes')
.then((bytes) =>
bytes === null ? null : parseJtwcKml(kmlFromKmz(bytes)),
)
.catch((error) => {
if (error?.name === 'AbortError') throw error;
return undefined;
}),
]);
if (text === null) throw invalid(`${prefix}.tcw missing`);
const warning = parseJtwcWarning(prefix, text);
const issued = Date.parse(warning.storm.issuedAt);
// A warning past its use, or dated far ahead of this clock, is left out.
if (now - issued > JTWC_USABLE_MS || issued - now > 90 * 60_000)
return null;
// An overlay that could not be read: the geometry is unavailable.
return overlay === undefined
? { ...warning.storm, geometryStatus: 'unavailable' }
: withJtwcDangerArea(warning, overlay);
};
const results = await Promise.allSettled(prefixes.map(readStorm));
const failed = results.filter((result) => result.status === 'rejected');
const aborted = failed.find((result) => result.reason?.name === 'AbortError');
if (aborted) throw aborted.reason;
if (failed.length && failed.length === results.length) throw failed[0].reason;
const storms = [];
for (const result of results) {
const storm = result.status === 'fulfilled' ? result.value : null;
if (storm && !storms.some((held) => held.id === storm.id))
storms.push(storm);
}
return storms;
}
-332
View File
@@ -1,332 +0,0 @@
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);
});
+99 -7
View File
@@ -18,6 +18,18 @@ import { admitSameSite } from './common/same-site.js';
* "Traffic flow"). The key comes from TOMTOM_API_KEY server-side only — the
* browser fetches same-origin `/api/tomtom/flow/{z}/{x}/{y}.pbf`.
*
* Orbis fallback: TomTom keys are assigned products, and a key without the
* TomTom Maps traffic product gets 403 on the endpoint above while the same
* key works on the TomTom Orbis Maps one,
* https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/{z}/{x}/{y}?apiVersion=2
* (same "Traffic flow" layer; `relative_speed` and `road_category` replace
* `traffic_level` and `road_type`, which the client decoder reads either
* way). On 403 the proxy asks the other endpoint and keeps whichever
* answered for the rest of the process. When both refuse the key, tiles
* answer 403 {error:'key_rejected'} and upstream is left alone for
* KEY_REJECTED_TTL_MS, so a rejected key does not spend the daily budget one
* tile at a time. Changing the key clears both.
*
* Cache: memory + disk (.gev-cache/tomtom/), TTL 120 s (traffic is fresh
* data), single-flight per tile, serve-stale-on-failure — the celestrakProxy
* pattern. Cache hits never count against the budget.
@@ -43,7 +55,7 @@ import { admitSameSite } from './common/same-site.js';
* at distinct tiles, spend the TomTom quota and leave the traffic layer on
* 429 budget for the rest of the UTC day.
*
* GET /api/tomtom/status → {hasKey, dailyCount, budget, date}. Keyless mode:
* GET /api/tomtom/status → {hasKey, keyRejected, dailyCount, budget, date}. Keyless mode:
* status reports hasKey:false and the tile endpoint 503s {error:'no_key'}
* without touching upstream — the traffic layer then stays in simulation mode.
*
@@ -59,6 +71,37 @@ export function tomtomProxy() {
const UPSTREAM_TIMEOUT_MS = 15000;
/** Flow tiles are well under 1 MB; this bounds a runaway body, not a budget. */
const TOMTOM_TILE_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
/** How long a key both endpoints refused is left alone before a retry. */
const KEY_REJECTED_TTL_MS = 5 * 60_000;
/** Upstream flow-tile endpoints, in the order a new key is tried. */
const ENDPOINTS = {
legacy: (z, x, y, key) => ({
url:
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(key)}`,
}),
orbis: (z, x, y, key) => ({
url:
'https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/' +
`${z}/${x}/${y}?apiVersion=2`,
headers: { 'TomTom-Api-Key': key },
}),
};
/**
* What is known about the configured key: the endpoint that last served
* it, and until when both endpoints are known to refuse it. Reset when the
* key changes (Provider Settings rewrites process.env at runtime).
* @type {{key:string, endpoint:'legacy'|'orbis', rejectedUntil:number}}
*/
let keyState = { key: '', endpoint: 'legacy', rejectedUntil: 0 };
function currentKeyState() {
const key = process.env.TOMTOM_API_KEY || '';
if (keyState.key !== key)
keyState = { key, endpoint: 'legacy', rejectedUntil: 0 };
return keyState;
}
const isKeyRejected = () => Date.now() < currentKeyState().rejectedUntil;
/** @type {Map<string, {at:number, buf:Buffer}>} tile key `z/x/y` -> cached tile (kept past TTL for serve-stale). */
const mem = new Map();
@@ -149,14 +192,17 @@ export function tomtomProxy() {
mem.set(key, entry);
}
async function fetchUpstream(z, x, y) {
const url =
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(process.env.TOMTOM_API_KEY)}`;
async function fetchEndpoint(name, z, x, y, key) {
const { url, headers } = ENDPOINTS[name](z, x, y, key);
recordUpstreamFetch(); // attempts count — upstream bills the request either way
const signal = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS);
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const res = await fetch(url, { signal, ...(headers ? { headers } : {}) });
if (!res.ok) {
await res.body?.cancel().catch(() => {});
throw Object.assign(new Error(`HTTP ${res.status}`), {
status: res.status,
});
}
const bytes = await readResponseBytesCapped(
res,
TOMTOM_TILE_MAX_RESPONSE_BYTES,
@@ -167,6 +213,41 @@ export function tomtomProxy() {
return buf;
}
/**
* Fetch one tile from the endpoint this key last worked on, asking the
* other one only when TomTom refuses the key (403). Both refusing marks
* the key rejected; any other failure is an ordinary upstream error.
*/
async function fetchUpstream(z, x, y) {
const state = currentKeyState();
const other = state.endpoint === 'legacy' ? 'orbis' : 'legacy';
try {
return await fetchEndpoint(state.endpoint, z, x, y, state.key);
} catch (err) {
if (err?.status !== 403) throw err;
}
try {
const buf = await fetchEndpoint(other, z, x, y, state.key);
if (keyState === state) {
state.endpoint = other;
console.warn(
`[tomtom-proxy] key refused on the ${other === 'orbis' ? 'TomTom Maps' : 'Orbis'} flow endpoint (HTTP 403); using the ${other === 'orbis' ? 'Orbis' : 'TomTom Maps'} one`,
);
}
return buf;
} catch (err) {
if (err?.status !== 403) throw err;
if (keyState === state)
state.rejectedUntil = Date.now() + KEY_REJECTED_TTL_MS;
throw Object.assign(
new Error(
'HTTP 403 on both flow endpoints: check the products assigned to the key and its domain whitelist at https://my.tomtom.com/keys',
),
{ status: 403 },
);
}
}
const installMiddleware = (server) => {
server.middlewares.use('/api/tomtom', async (req, res) => {
// Gate first: a cross-site <img>/fetch must not reach the budget counter.
@@ -204,6 +285,7 @@ export function tomtomProxy() {
const b = currentBudget();
sendJson(200, {
hasKey,
keyRejected: hasKey && isKeyRejected(),
dailyCount: b.count,
budget: dailyBudgetLimit(),
date: b.date,
@@ -242,6 +324,14 @@ export function tomtomProxy() {
return;
}
// TomTom refused the key on both endpoints: asking again per tile
// would only spend the budget. Last-good data still beats nothing.
if (isKeyRejected()) {
if (entry) sendTile(entry, 'STALE-ERROR');
else sendJson(403, { error: 'key_rejected' });
return;
}
// Budget governor: over the soft cap, last-good data beats a dead layer.
if (isTomTomOverBudget(currentBudget(), dailyBudgetLimit())) {
if (entry) {
@@ -277,6 +367,8 @@ export function tomtomProxy() {
sendTile(fresh, 'MISS');
} else if (entry) {
sendTile(entry, 'STALE-ERROR'); // upstream down — stale beats empty
} else if (isKeyRejected()) {
sendJson(403, { error: 'key_rejected' });
} else {
sendJson(502, { error: 'upstream' });
}
-3
View File
@@ -17,7 +17,6 @@ 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';
@@ -350,8 +349,6 @@ 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 });
+6 -20
View File
@@ -1165,10 +1165,7 @@ 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;/,
@@ -1188,14 +1185,8 @@ 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\(\);/,
@@ -1383,17 +1374,12 @@ test('voice Cockpit entry honours a requested contact layer before it enters', (
const retarget = ui.slice(
ui.indexOf(' _retargetCockpitEntryLayer({'),
ui.indexOf(' controlCockpit(\n'),
ui.indexOf(' * Controls cockpit entry/exit and context navigation.'),
);
assert.match(
retarget,
/layer\.trackById\?\.\(match\.icao24, \{ origin: 'voice' \}\)/,
'retargeting follows the match with durable voice selection authority',
);
assert.doesNotMatch(
retarget,
/militaryAwarenessLayer/,
'retargeting needs nothing from Contacts',
/militaryAwarenessLayer\.navigateNext\(\{\s*targetLayer,\s*aircraftClass,\s*origin: 'voice',\s*\}\)/,
'retargeting reuses filtered navigation with durable voice selection authority',
);
assert.match(
retarget,
+12 -42
View File
@@ -33,7 +33,6 @@ import {
} from './aircraftIcons.js';
import { cockpitContactDotImage } from './cockpitContactDot.js';
import { rotorFrame, rotorTurns } from './rotorFrames.js';
import { registerAircraftViews, withAircraftView } from './aircraftViews.js';
import { aircraftRecedeSpec } from './aircraftRecession.js';
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
@@ -437,8 +436,6 @@ function fixedDelay(ms) {
* Where a host-supplied placement draws a live contact at a wall time,
* written into `out` (`placeAircraftAt`), or null when it does not place
* it; none without a placement.
* @param {(url: string) => string} [options.resolveAsset] The layer's asset
* URL resolver, for the aircraft view sheet's image.
*/
export function createAircraftIcons({
state,
@@ -456,14 +453,10 @@ export function createAircraftIcons({
afterSettle = () => {},
onForget = () => {},
placeAt = null,
resolveAsset = (url) => url,
}) {
const { focusPassIsNeeded } = services.focus;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** Whether the renderer draws icons along their course from the aircraft
* view sheet (`aircraftViews.js`), set when the draw set is made. */
let views = false;
/**
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
* frame each was last drawn at, and the frame it was last judged at
@@ -551,9 +544,9 @@ export function createAircraftIcons({
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
const capabilities = rendererOf(viewer)?.capabilities ?? null;
views = registerAircraftViews(drawOf(viewer), capabilities, resolveAsset);
state._icons = createContactIcons(set, { capabilities });
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
});
return set.id;
}
@@ -562,7 +555,6 @@ export function createAircraftIcons({
state._icons?.dispose();
state._icons = null;
liveSet = null;
views = false;
rotors.clear();
planFrom.clear();
easeEnds.clear();
@@ -970,26 +962,19 @@ export function createAircraftIcons({
* How a contact's icon is drawn outside Cockpit: its image (and the sharper
* one it switches to up close), size, scale and scale by distance. The
* tracked contact's own icon is drawn with this too, so selecting a contact
* changes its colour and nothing else. Drawn along its course
* (`alongCourse`) on a renderer that draws view sheets, a kind with
* rendered views draws from the aircraft view sheet, with no near image
* (`aircraftViews.js`); otherwise it is the flat glyph.
* changes its colour and nothing else.
* @param {string} icao24
* @param {object} [info] Its record.
* @param {number} [frame] A helicopter's rotor frame.
* @param {{alongCourse?: boolean}} [options]
* @returns {{image: string|{views: string, first: number},
* imageLod: {near: string, switchPx: number}|undefined,
* @returns {{image: string, imageLod: {near: string, switchPx: number},
* size: [number, number], scale: number, scaleByDistance: object}}
*/
function _fleetLook(
icao24,
info = state.records.data.get(icao24),
frame = _rotorFrameOf(icao24, info, Date.now()),
{ alongCourse = false } = {},
) {
const rendering = parts.rendering;
const look = {
return {
image: aircraftIcon(
rendering._iconKind(icao24, info?.klass),
FLEET_ICON_PX,
@@ -1007,17 +992,6 @@ export function createAircraftIcons({
scale: rendering._fleetBillboardScale(icao24),
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
};
return withAircraftView(look, {
views,
kind: rendering._iconKind(icao24, info?.klass),
frame,
rotationMode: alongCourse ? 'course' : undefined,
});
}
/** Whether contacts drawn along their course draw from the view sheet. */
function _drawsViews() {
return views;
}
/**
@@ -1077,7 +1051,6 @@ export function createAircraftIcons({
id,
state.records.data.get(id),
frame,
{ alongCourse: icons.item(id)?.rotationMode === 'course' },
);
icons.update(id, { image, imageLod });
}
@@ -1091,11 +1064,6 @@ export function createAircraftIcons({
const rendering = parts.rendering;
const info = state.records.data.get(icao24);
const tracked = icao24 === state._trackedIcao;
// A helicopter's rotor frame, chosen once for its look and its rotor.
const heliFrame = _rotorFrameOf(icao24, info, Date.now());
// A ground station's mast stands upright; every other glyph turns
// along its course.
const station = info?.klass === 'station';
const cockpitDot =
state._cockpitContactMode &&
!tracked &&
@@ -1111,18 +1079,21 @@ export function createAircraftIcons({
rotationMode: 'screen',
}
: {
..._fleetLook(icao24, info, heliFrame, { alongCourse: !station }),
..._fleetLook(icao24, info),
color: rgba(rendering._fleetBillboardColor(icao24, info)),
rotationMode: 'course',
};
if (!cockpitDot && station) {
// A ground station's mast stands upright.
if (!cockpitDot && info?.klass === 'station') {
look.rotationMode = 'screen';
look.rotation = 0;
}
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
icons.update(icao24, look);
// An airborne helicopter drawn as its glyph turns its rotor.
const frame = cockpitDot ? undefined : heliFrame;
const frame = cockpitDot
? undefined
: _rotorFrameOf(icao24, info, Date.now());
if (frame === undefined || !rotorTurns(_rotorState(info))) {
// A tracked helicopter that lands shows the still frame at once.
if (rotors.delete(icao24) && tracked)
@@ -1205,7 +1176,6 @@ export function createAircraftIcons({
_focusIcons,
_applyIconPresentation,
_fleetLook,
_drawsViews,
_turnRotors,
_rotorsTurning,
_addIcon,
-180
View File
@@ -481,183 +481,3 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/**
* An icon layer on a renderer that does (or does not) draw view sheets,
* over contacts `records` (by id), all held at one place.
*/
function viewsFixture(
records,
{ viewSheets = true, kinds = {}, resolveAsset } = {},
) {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer, {
capabilities: new Set(viewSheets ? ['viewSheets'] : []),
});
const state = {
_viewer: viewer,
now: () => Date.now(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (id, klass) => kinds[id] ?? klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1.25,
_cockpitContactColor: () => [1, 0, 0, 1],
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
resolveAsset,
});
icons._createIcons(viewer);
const here = fromDegrees(0, 30, 300);
for (const id of records.keys()) {
state._icons.put(
{ id, pos: here, motion: { kind: 'hold', courseDeg: 0 }, size: [20, 20] },
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons, registered: draw.viewSheets, here, unbind };
}
test('with view sheets, every aircraft class draws from the sheet along its course, with no near image', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const records = new Map([
['p1', { klass: 'airliner' }],
['p2', { klass: 'glider' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, icons, registered, unbind } = viewsFixture(records);
t.after(unbind);
assert.deepEqual(registered, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftViewRef('airliner'));
assert.equal(p1.imageLod, undefined);
assert.equal(p1.rotationMode, 'course');
// Everything else is as the flat glyph draws it.
assert.deepEqual(p1.size, [20, 20]);
assert.equal(p1.scale, 1.25);
assert.deepEqual(p1.color, [1, 1, 1, 1]);
assert.equal(p1.scaleByDistance.nearValue, 3);
assert.equal(state._icons.item('p2').image, aircraftViewRef('glider'));
assert.equal(
state._icons.item('h1').image,
aircraftViewRef('helicopter', ROTOR_STILL_FRAME),
);
// The plain fleet look (the tracked icon's sizing, a screen-rotated
// caller) stays the flat glyph.
assert.equal(
icons._fleetLook('p1').image,
aircraftIcon('airliner', FLEET_ICON_PX),
);
assert.equal(
icons._fleetLook('p1', undefined, undefined, { alongCourse: true }).image,
aircraftViewRef('airliner'),
);
assert.equal(icons._drawsViews(), true);
icons._disposeIcons();
assert.equal(icons._drawsViews(), false);
});
test('without view sheets the icons are the flat glyphs with their near image, as before', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['p1', { klass: 'airliner' }]]);
const { state, icons, registered, unbind } = viewsFixture(records, {
viewSheets: false,
});
t.after(unbind);
assert.deepEqual(registered, [], 'no sheet is registered');
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftIcon('airliner', FLEET_ICON_PX));
assert.equal(p1.imageLod.near, aircraftIcon('airliner', 192));
assert.equal(p1.rotationMode, 'course');
assert.equal(icons._drawsViews(), false);
});
test('with view sheets, the TR-3B, airport vehicles and ground stations stay flat', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['x1', { klass: 'airliner' }],
['v1', { klass: 'vehicle' }],
['s1', { klass: 'station' }],
]);
const { state, unbind } = viewsFixture(records, {
kinds: { x1: 'tr3b' },
});
t.after(unbind);
assert.equal(
state._icons.item('x1').image,
aircraftIcon('tr3b', FLEET_ICON_PX),
);
assert.ok(state._icons.item('x1').imageLod);
assert.equal(
state._icons.item('v1').image,
aircraftIcon('vehicle', FLEET_ICON_PX),
);
const mast = state._icons.item('s1');
assert.equal(mast.image, aircraftIcon('station', FLEET_ICON_PX));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('with view sheets, an airborne helicopter turns its rotor through the sheet’s three blocks', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
const { state, icons, unbind } = viewsFixture(records);
t.after(unbind);
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now());
const item = state._icons.item('h1');
assert.equal(item.imageLod, undefined);
seen.add(item.image);
}
assert.deepEqual(
new Set(seen),
new Set([0, 1, 2].map((frame) => aircraftViewRef('helicopter', frame))),
);
});
test('the layer registers the view sheet at its own asset URL', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const { registered, unbind } = viewsFixture(
new Map([['p1', { klass: 'airliner' }]]),
{ resolveAsset: (url) => `/gev/${url.replace(/^\//, '')}` },
);
t.after(unbind);
assert.equal(registered.length, 1);
assert.equal(registered[0][0], AIRCRAFT_VIEWS.id);
assert.equal(registered[0][1].image, '/gev/sprites/aircraft-views.webp');
});
test('a view carries the contact’s flat glyph as its fallback', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['p1', { klass: 'turboprop' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, unbind } = viewsFixture(records);
t.after(unbind);
assert.equal(
state._icons.item('p1').image.fallback,
aircraftIcon('turboprop', FLEET_ICON_PX),
);
assert.equal(
state._icons.item('h1').image.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
-138
View File
@@ -1,138 +0,0 @@
/**
* @module data/aircraftViews
* @description Which block of the aircraft view sheet (`viewSheet.js`) a
* contact's icon draws from. Each aircraft class is rendered there from a
* sphere of camera angles; a renderer with the `viewSheets` capability lays
* the icon flat on the earth along its course and draws the view that
* matches where the eye is, so an oblique contact looks solid instead of
* like a paper cut-out. Only an icon drawn along its course
* (`rotationMode: 'course'`) can do this: a screen-rotated or upright icon
* keeps its flat glyph. Kinds with no rendered views (the TR-3B triangle,
* airport vehicles, ground stations) keep their flat glyph as well.
*/
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import {
aircraftIcon,
FLEET_ICON_PX,
ROTOR_FRAMES,
ROTOR_STILL_FRAME,
} from './aircraftIcons.js';
/** The renderer capability that draws view sheets. */
export const VIEW_SHEETS_CAPABILITY = 'viewSheets';
/** Kinds drawn from the sheet with one block each (helicopters have three). */
const STILL_KINDS = new Set([
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
]);
/** One frozen image ref per block, so equal refs are the same object. */
const refs = new Map();
/**
* The ref of the block at `first`, with the flat glyph of `kind` (and its
* rotor `frame`) as its fallback: what the renderer draws until the sheet
* has loaded, and for good if it cannot load.
*/
function refAt(first, kind, frame) {
let ref = refs.get(first);
if (!ref) {
ref = Object.freeze({
views: AIRCRAFT_VIEWS.id,
first,
fallback: aircraftIcon(kind, FLEET_ICON_PX, frame),
});
refs.set(first, ref);
}
return ref;
}
/**
* The view image of an icon kind: `{views, first, fallback}`, the sheet's
* id, the first cell of the kind's block and its flat glyph (drawn while
* the sheet loads, or if it fails), or null for a kind with no views.
* @param {string} kind An icon kind (`rendering._iconKind`).
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame otherwise, as `aircraftIcon` takes it).
* @returns {{views: string, first: number, fallback: string}|null}
*/
export function aircraftViewRef(kind, frame) {
const subjects = AIRCRAFT_VIEWS.subjects;
if (kind === 'helicopter') {
const f =
Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME;
const first = subjects[`helicopter${f}`];
return Number.isInteger(first) ? refAt(first, kind, f) : null;
}
if (!STILL_KINDS.has(kind)) return null;
const first = subjects[kind];
return Number.isInteger(first) ? refAt(first, kind) : null;
}
/** Whether an icon image is a view-sheet ref. */
export function isAircraftViewRef(image) {
return Boolean(image) && typeof image === 'object' && 'views' in image;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the aircraft view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerAircraftViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.(VIEW_SHEETS_CAPABILITY)) return false;
if (!registered.has(drawPort)) {
const sheet = AIRCRAFT_VIEWS.sheet;
drawPort.views(AIRCRAFT_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
/**
* An icon's look drawn from the view sheet where it can be: with views on,
* the item drawn along its course and the kind rendered, the image is the
* view ref and there is no near image (`imageLod: undefined`, so an update
* clears it); otherwise the look as given, the very same object.
* @template {{image: unknown, imageLod?: unknown}} T
* @param {T} look
* @param {object} options
* @param {boolean} options.views Whether the renderer draws views
* (`registerAircraftViews`).
* @param {string} options.kind The icon kind.
* @param {number} [options.frame] A helicopter's rotor frame.
* @param {string} [options.rotationMode] How the item is rotated.
* @returns {T}
*/
export function withAircraftView(look, { views, kind, frame, rotationMode }) {
if (!views || rotationMode !== 'course') return look;
const ref = aircraftViewRef(kind, frame);
if (!ref) return look;
return { ...look, image: ref, imageLod: undefined };
}
-175
View File
@@ -1,175 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
aircraftViewRef,
isAircraftViewRef,
registerAircraftViews,
VIEW_SHEETS_CAPABILITY,
withAircraftView,
} from './aircraftViews.js';
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './rotorFrames.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
const STILL_KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
];
test('every aircraft class draws its own block of the view sheet', () => {
for (const kind of STILL_KINDS)
assert.deepEqual(
aircraftViewRef(kind),
{
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects[kind],
fallback: aircraftIcon(kind, FLEET_ICON_PX),
},
kind,
);
const firsts = STILL_KINDS.map((kind) => aircraftViewRef(kind).first);
assert.equal(
new Set(firsts).size,
STILL_KINDS.length,
'no two share a block',
);
assert.equal(
aircraftViewRef('airliner'),
aircraftViewRef('airliner'),
'one ref per block, so an unchanged image writes nothing',
);
assert.ok(Object.isFrozen(aircraftViewRef('airliner')));
});
test('a helicopter draws the block of its rotor frame, the still frame by default', () => {
assert.equal(ROTOR_FRAMES, 3);
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
const ref = aircraftViewRef('helicopter', frame);
assert.equal(
ref.first,
AIRCRAFT_VIEWS.subjects[`helicopter${frame}`],
`frame ${frame}`,
);
assert.equal(
ref.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, frame),
`its fallback is the glyph of rotor frame ${frame}`,
);
}
assert.equal(
aircraftViewRef('helicopter').fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const still = AIRCRAFT_VIEWS.subjects[`helicopter${ROTOR_STILL_FRAME}`];
for (const frame of [undefined, -1, 3, 1.5, NaN])
assert.equal(aircraftViewRef('helicopter', frame).first, still, `${frame}`);
});
test('the TR-3B, airport vehicles, ground stations and unknown kinds have no views', () => {
for (const kind of [
'tr3b',
'tr3bHot',
'vehicle',
'station',
'jet',
'',
undefined,
])
assert.equal(aircraftViewRef(kind), null, String(kind));
assert.equal(
aircraftViewRef('airliner', 1).first,
0,
'a frame means nothing to a fixed wing',
);
});
test('a view ref is told apart from flat images', () => {
assert.equal(isAircraftViewRef(aircraftViewRef('glider')), true);
for (const image of [
'data:image/svg+xml;base64,AAA',
null,
undefined,
{ atlas: 'a', slot: 's' },
])
assert.equal(isAircraftViewRef(image), false, String(image));
});
test('the sheet is registered once per draw port, only with the capability', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
assert.equal(VIEW_SHEETS_CAPABILITY, 'viewSheets');
assert.equal(registerAircraftViews(port, new Set()), false);
assert.equal(registerAircraftViews(port, null), false);
assert.equal(calls.length, 0, 'nothing registered without the capability');
assert.equal(registerAircraftViews(port, caps), true);
assert.equal(registerAircraftViews(port, caps), true);
assert.deepEqual(calls, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const other = { views: (id) => calls.push([id]) };
assert.equal(registerAircraftViews(other, caps), true);
assert.equal(calls.length, 2, 'a second port registers its own');
assert.equal(
registerAircraftViews({}, caps),
false,
'a port without views()',
);
assert.equal(registerAircraftViews(null, caps), false);
});
test('a look takes the view only when views are on and it is drawn along its course', () => {
const look = {
image: 'flat',
imageLod: { near: 'near', switchPx: 30 },
size: [20, 20],
scale: 1.5,
};
const on = { views: true, kind: 'airliner', rotationMode: 'course' };
const viewed = withAircraftView(look, on);
assert.deepEqual(viewed, {
image: aircraftViewRef('airliner'),
imageLod: undefined,
size: [20, 20],
scale: 1.5,
});
assert.ok('imageLod' in viewed, 'imageLod is cleared, so an update drops it');
assert.equal(look.image, 'flat', 'the look given is left as it was');
assert.equal(withAircraftView(look, { ...on, views: false }), look);
assert.equal(withAircraftView(look, { ...on, rotationMode: 'screen' }), look);
assert.equal(
withAircraftView(look, { ...on, rotationMode: undefined }),
look,
);
assert.equal(withAircraftView(look, { ...on, kind: 'tr3b' }), look);
assert.equal(withAircraftView(look, { ...on, kind: 'station' }), look);
assert.equal(
withAircraftView(look, { ...on, kind: 'helicopter', frame: 2 }).image,
aircraftViewRef('helicopter', 2),
);
});
test('the sheet is registered with its image resolved as the layer resolves its assets', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
registerAircraftViews(port, caps, (url) => `https://cdn.example/app${url}`);
assert.equal(calls.length, 1);
const [id, sheet] = calls[0];
assert.equal(id, AIRCRAFT_VIEWS.id);
assert.equal(
sheet.image,
'https://cdn.example/app/sprites/aircraft-views.webp',
);
assert.deepEqual(
{ ...sheet, image: AIRCRAFT_VIEWS.sheet.image },
{ ...AIRCRAFT_VIEWS.sheet },
'the layout as it is',
);
assert.equal(AIRCRAFT_VIEWS.sheet.image, '/sprites/aircraft-views.webp');
});
+2 -161
View File
@@ -74,12 +74,7 @@ function collections(adv = '10') {
}
function install(options = {}, preview = false) {
let handler;
// JTWC has its own tests below; these cover NHC alone.
const plugin = cycloneProxy({
now: () => NOW,
readJtwc: async () => [],
...options,
});
const plugin = cycloneProxy({ now: () => NOW, ...options });
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: {
use(path, callback) {
@@ -302,7 +297,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, /JTWC: western North Pacific/);
assert.match(snapshot.coverage, /not worldwide/);
assert.equal(snapshot.storms[0].geometryStatus, 'current');
assert.equal(snapshot.fetchedAt, NOW);
assert.equal(calls.length, 4);
@@ -496,157 +491,3 @@ test('shared refresh caps waiting consumers and rejects redirects without exposi
});
assert.equal(body(await redirected.request()).unavailable, true);
});
function jtwcStorm(overrides = {}) {
return {
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
position: { longitude: -164.5, latitude: -11.6 },
positionAt: TIME,
advisoryNumber: '15',
issuedAt: TIME,
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
...overrides,
};
}
test('JTWC storms join NHC’s, and NHC’s advisory wins for a storm both list', async () => {
const crossing = jtwcStorm({
id: 'ep152026',
basin: 'EP',
name: 'JTWC copy',
});
const { request } = install({
fetchImpl: fetcher(),
readJtwc: async () => [jtwcStorm(), crossing],
});
const snapshot = body(await request());
assert.deepEqual(
snapshot.storms.map((storm) => [storm.id, storm.agency, storm.name]),
[
['ep152026', 'nhc', 'Fifteen-E'],
['sh042027', 'jtwc', 'Xavier'],
],
);
assert.equal(snapshot.stale, false);
assert.match(snapshot.source, /JTWC/);
assert.match(snapshot.attribution, /Joint Typhoon Warning Center/);
});
test('JTWC reads go through the bounded fetch with no redirects', async () => {
const calls = [];
const { request } = install({
fetchImpl: async (url, options) => {
calls.push({ url, options });
if (url.includes('jtwc.rss'))
return new Response(
'<rss><item><guid>NWPAC-NIO-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>EPAC-CPAC-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>SH-WARNINGS</guid>No Current Tropical Cyclone Warnings</item></rss>',
);
return fetcher()(url, options);
},
readJtwc: undefined,
});
const snapshot = body(await request());
assert.equal(snapshot.stale, false);
const jtwc = calls.filter(({ url }) => url.includes('metoc.navy.mil'));
assert.deepEqual(
jtwc.map(({ url }) => url),
['https://www.metoc.navy.mil/jtwc/rss/jtwc.rss'],
);
assert.equal(jtwc[0].options.redirect, 'error');
});
test('a failed JTWC read keeps its last storms and leaves NHC’s answer fresh', async () => {
let fail = false;
let clock = NOW;
const { request } = install({
fetchImpl: fetcher(),
now: () => clock,
readJtwc: async () => {
if (fail) throw new Error('jtwc down');
return [jtwcStorm()];
},
});
assert.equal(body(await request()).storms.length, 2);
fail = true;
clock += 6 * 60_000;
const kept = body(await request());
assert.equal(kept.stale, false);
assert.equal(kept.reason, null);
assert.deepEqual(
kept.storms.map((storm) => storm.id),
['ep152026', 'sh042027'],
);
// Past their use, both advisories leave the cached answer.
clock = Date.parse(TIME) + 13 * 3600_000 + 60_000;
const later = body(await request());
assert.deepEqual(
later.storms.map((storm) => storm.id),
[],
);
});
test('a cached answer drops each storm whose own advisory is past use, not all of them', async () => {
let up = true;
let clock = NOW;
const { request } = install({
fetchImpl: async (url, options) => {
if (!up) throw new Error('down');
return fetcher()(url, options);
},
now: () => clock,
readJtwc: async () => [
jtwcStorm({ issuedAt: new Date(NOW - 30 * 60_000).toISOString() }),
],
});
assert.equal(body(await request()).storms.length, 2);
up = false;
// 12 h 10 min after the NHC advisory: NHC's is past use, JTWC's is not.
clock = Date.parse(TIME) + 12 * 3600_000 + 10 * 60_000;
const cached = body(await request());
assert.equal(cached.stale, true);
assert.deepEqual(
cached.storms.map((storm) => storm.id),
['sh042027'],
);
});
test('a JTWC that hangs or answers 500 leaves NHC’s answer unchanged', async (t) => {
const nhcOnly = body(await install({ fetchImpl: fetcher() }).request());
assert.equal(nhcOnly.stale, false);
const jtwcCalls = [];
for (const mode of ['500', 'hang']) {
const { request } = install({
readJtwc: undefined,
jtwcTimeoutMs: 20,
fetchImpl: async (url, options) => {
if (!String(url).includes('metoc.navy.mil'))
return fetcher()(url, options);
jtwcCalls.push(mode);
if (mode === '500') return new Response('down', { status: 500 });
// Hangs until its own deadline aborts it.
return new Promise((_, reject) =>
options.signal.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
),
);
},
});
const answer = body(await request());
assert.deepEqual(answer, nhcOnly, `JTWC ${mode}`);
}
assert.deepEqual(jtwcCalls, ['500', 'hang']);
});
+1 -1
View File
@@ -563,7 +563,7 @@ export const DATA_CREDITS = [
},
{
key: 'weather-cyclones',
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific; <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.',
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.',
},
{
key: 'weather-lightning',
+2 -2
View File
@@ -42,8 +42,8 @@ export const MAX_ICON_SLOTS = 176;
export const MIN_ICON_SLOTS = 64;
/**
* Vertex uniform vectors the icon shader keeps for everything else: its own
* and the renderer's (about 45, the view sheet's layout among them), with
* room for drivers that keep constants in uniforms.
* and the renderer's (about 34), with room for drivers that keep constants
* in uniforms.
*/
const OTHER_VERTEX_UNIFORMS = 80;
-6
View File
@@ -100,12 +100,6 @@ export const ICON_RECEDES = 4;
* −31 m before its floor warms) otherwise reads as beyond the limb.
*/
export const ICON_CULL_LIFT = 8;
/**
* The row's image is a subject of the set's view sheet
* ({@link module:viewSheet}): its far image is the subject's first cell, and
* the renderer draws the frame that shows it from the eye.
*/
export const ICON_VIEWS = 16;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/**
-29
View File
@@ -14,35 +14,6 @@ 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
+5 -20
View File
@@ -15,14 +15,8 @@
* pick names the set and the contact's id, as the fleet icons' do.
* `visible` hides the icon while it stays shown (Cockpit flies the
* aircraft from its own seat).
*
* Given a view-sheet image (`aircraftViews.js`) and a course reader, it is
* drawn along that course instead (`rotationMode: 'course'`), as the fleet
* icons are, so the renderer draws the view of the aircraft that matches
* the eye and tracking a contact does not flatten it.
*/
import { findDraw, findFrame } from '../render/rendererOf.js';
import { isAircraftViewRef } from './aircraftViews.js';
/** Uniquifier for the sets' ids. */
let instances = 0;
@@ -111,21 +105,18 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
function draw() {
if (!shown || !set) return;
const pos = shown.position();
const alongCourse =
typeof shown.course === 'function' && isAircraftViewRef(shown.image);
const item = {
id: shown.id,
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
show: Boolean(pos) && visible,
image: shown.image,
...(shown.imageLod && !alongCourse ? { imageLod: shown.imageLod } : {}),
...(shown.imageLod ? { imageLod: shown.imageLod } : {}),
size: [shown.sprite.width, shown.sprite.height],
scale: shown.sprite.scale,
scaleByDistance: shown.sprite.scaleByDistance,
color: shown.color(),
...(alongCourse
? { rotationMode: 'course', course: pos ? shown.course() : 0 }
: { rotationMode: 'screen', rotation: pos ? shown.rotation() : 0 }),
rotationMode: 'screen',
rotation: pos ? shown.rotation() : 0,
disableDepthTest: Number.POSITIVE_INFINITY,
};
if (
@@ -141,9 +132,7 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
written.size[0] === item.size[0] &&
written.size[1] === item.size[1] &&
written.scale === item.scale &&
written.rotationMode === item.rotationMode &&
written.rotation === item.rotation &&
written.course === item.course &&
sameColor(written.color, item.color)
)
return;
@@ -157,17 +146,13 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
* next one on.
* @param {object} target
* @param {string} target.id The contact's id.
* @param {string|{views: string, first: number}} target.image A flat
* glyph, or a view-sheet image (drawn along `course`).
* @param {string} target.image
* @param {{near: string, switchPx: number}} [target.imageLod] The
* sharper image a flat glyph switches to once drawn larger than
* `switchPx`.
* sharper image it switches to once drawn larger than `switchPx`.
* @param {{width: number, height: number, scale: number,
* scaleByDistance: object}} target.sprite Read each frame.
* @param {() => object|null} target.position ECEF this frame; none hides it.
* @param {() => number} target.rotation Screen radians, counter-clockwise.
* @param {() => number} [target.course] Degrees clockwise from north;
* required with a view-sheet image, which only draws along a course.
* @param {() => object} target.color The tint this frame.
*/
show(target) {
-49
View File
@@ -199,52 +199,3 @@ test('the tracked icon keeps its contact\'s colour; only the alpha changes', ()
assert.ok(Object.isFrozen(stale));
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
});
test('given a view-sheet image and a course, the tracked icon is drawn along its course with no near image', async () => {
const { aircraftViewRef } = await import('./aircraftViews.js');
const { viewer, draw, tick } = harness();
const icon = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'flights',
});
let course = 45;
let rotations = 0;
icon.show({
id: 'abc123',
image: aircraftViewRef('airliner'),
imageLod: { near: 'near', switchPx: 30 },
sprite: SPRITE,
position: () => ({ x: 1, y: 2, z: 3 }),
rotation: () => {
rotations++;
return 0.5;
},
course: () => course,
color: () => [0, 1, 1, 1],
});
const set = draw.find('flights-tracked-icon:');
tick();
const item = set.items.get('abc123');
assert.equal(item.image, aircraftViewRef('airliner'));
assert.equal('imageLod' in item, false);
assert.equal(item.rotationMode, 'course');
assert.equal(item.course, 45);
assert.equal('rotation' in item, false);
assert.equal(rotations, 0, 'no screen rotation is projected');
assert.deepEqual(item.size, [28, 28]);
const writes = set.writes;
tick();
assert.equal(set.writes, writes, 'an unchanged frame writes nothing');
course = 50;
tick();
assert.equal(set.items.get('abc123').course, 50);
// A flat image (a TR-3B conversion, a ground station) turns on screen again.
icon.setImage('data:image/svg+xml;base64,AAA', { near: 'near', switchPx: 30 });
tick();
const flat = set.items.get('abc123');
assert.equal(flat.rotationMode, 'screen');
assert.equal(flat.rotation, 0.5);
assert.deepEqual(flat.imageLod, { near: 'near', switchPx: 30 });
assert.equal('course' in flat, false);
icon.dispose();
});
+3
View File
@@ -46,6 +46,9 @@ test('hosted account limits and service failures name their own reason', () => {
assert.equal(failure(429, 'budget'), 'TomTom daily budget reached');
assert.equal(failure(503, 'no_key'), 'TomTom key unavailable');
assert.equal(failure(503, null), 'TomTom key unavailable');
// TomTom refused the key itself: not the generic HTTP 403 line.
assert.equal(failure(403, 'key_rejected'), 'TomTom key rejected');
assert.equal(failure(403, null), 'TomTom flow error (HTTP 403)');
assert.equal(
failure(503, 'USAGE_UNAVAILABLE'),
'Traffic service unavailable',
+2 -53
View File
@@ -59,9 +59,9 @@ const VESSEL_KIND_RULES = [
['fishing', /fishing|trawler/i],
[
'military',
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search\W+(?:and\W+|&\W*)?rescue/i,
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i,
],
['tug', /tug|tow|pilot|tender|supply|service|anti\W?pollution/i],
['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i],
['sailing', /sail/i],
['pleasure', /pleasure|yacht/i],
];
@@ -116,57 +116,6 @@ export function vesselKind(type) {
return kind;
}
/**
* Hull shapes drawn within a kind, where an AIS ship type has a hull of its
* own: a dredger (AIS 33, otherwise `other`), and the small workboats that
* are neither tugs nor patrol craft, drawn as a pilot boat (AIS 50 pilot,
* 51 search and rescue, 53 port tender, 54 anti-pollution). In order: the
* first that matches.
*/
const VESSEL_SHAPE_RULES = [
['dredger', /dredg/i],
[
'pilot',
/pilot|\bsar\b|search\W+(?:and\W+|&\W*)?rescue|port\W?tender|anti\W?pollution/i,
],
];
/** Every hull shape {@link vesselShape} names: the kinds, then the rest. */
export const VESSEL_SHAPES = Object.freeze([
'cargo',
'tanker',
'passenger',
'highspeed',
'fishing',
'tug',
'sailing',
'pleasure',
'military',
'other',
...VESSEL_SHAPE_RULES.map(([shape]) => shape),
]);
const SHAPE_MEMO = new Map();
/**
* The hull a vessel is shown as from the eye's angle (the vessel view
* sheet, `vesselViews.js`): its own where its AIS type has one, else its
* kind's ({@link vesselKind}). Its colour is always its kind's.
* @param {string} type Raw AIS type.
* @returns {string} One of `VESSEL_SHAPES`.
*/
export function vesselShape(type) {
const text = normalizeVesselType(type);
let shape = SHAPE_MEMO.get(text);
if (shape !== undefined) return shape;
shape =
VESSEL_SHAPE_RULES.find(([, pattern]) => pattern.test(text))?.[0] ??
vesselKind(type);
if (SHAPE_MEMO.size >= KIND_MEMO_MAX) SHAPE_MEMO.clear();
SHAPE_MEMO.set(text, shape);
return shape;
}
/**
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
-74
View File
@@ -1,74 +0,0 @@
/**
* @module data/vesselViews
* @description Which block of the vessel view sheet (`viewSheet.js`) a
* vessel's icon draws from. Each hull shape (`vesselShape`, vesselTypes.js)
* is rendered there from a sphere of camera angles, from straight above
* down to the horizon; a renderer with the `viewSheets` capability lays the icon
* flat on the water along its course and draws the view that matches where
* the eye is, so a ship seen at an oblique angle looks solid instead of
* like a flat hull. An aid to navigation keeps its upright buoy.
*/
import { VESSEL_VIEWS } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import { VESSEL_KINDS } from './vesselTypes.js';
/** One frozen image ref per shape and kind, so equal refs are the same. */
const refs = new Map();
/**
* The view image of a vessel: `{views, first, fallback}`, the sheet's id,
* the first cell of its hull shape's block and its kind's flat hull sprite
* (drawn while the sheet loads, or if it fails). A shape the sheet does not
* hold draws its kind's block, and a kind it does not hold `other`'s.
* @param {string} shape One of `VESSEL_SHAPES` (`vesselShape`).
* @param {string} [kind] One of `VESSEL_KINDS` (`vesselKind`); the shape
* itself by default.
* @returns {{views: string, first: number, fallback: string}}
*/
export function vesselViewRef(shape, kind = shape) {
const held = (name) => Number.isInteger(VESSEL_VIEWS.subjects[name]);
const flat = VESSEL_KINDS.includes(kind) ? kind : 'other';
const subject = held(shape) ? shape : held(flat) ? flat : 'other';
const key = `${subject}|${flat}`;
let ref = refs.get(key);
if (!ref) {
ref = Object.freeze({
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[subject],
fallback: vesselSprite(flat),
});
refs.set(key, ref);
}
return ref;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the vessel view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerVesselViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.('viewSheets')) return false;
if (!registered.has(drawPort)) {
const sheet = VESSEL_VIEWS.sheet;
drawPort.views(VESSEL_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
-145
View File
@@ -1,145 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { registerVesselViews, vesselViewRef } from './vesselViews.js';
import { VESSEL_VIEWS, viewLayout } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import {
VESSEL_KINDS,
VESSEL_SHAPES,
vesselKind,
vesselShape,
} from './vesselTypes.js';
test('VESSEL_VIEWS holds a block for every hull shape, each on the sheet', () => {
const layout = viewLayout(VESSEL_VIEWS.sheet);
assert.equal(layout.frames, VESSEL_VIEWS.frames);
// To the horizon and no further: a ship is never seen from below.
assert.equal(
(VESSEL_VIEWS.sheet.rings.length - 1) * VESSEL_VIEWS.sheet.ringStepDeg,
90,
);
// Every shape, in order, a block each: the ten kinds, then the rest.
assert.deepEqual(Object.keys(VESSEL_VIEWS.subjects), [...VESSEL_SHAPES]);
assert.deepEqual(
VESSEL_SHAPES.slice(0, VESSEL_KINDS.length).toSorted(),
[...VESSEL_KINDS].sort(),
);
VESSEL_SHAPES.forEach((shape, i) =>
assert.equal(VESSEL_VIEWS.subjects[shape], i * VESSEL_VIEWS.frames, shape),
);
assert.ok(
VESSEL_SHAPES.length * VESSEL_VIEWS.frames <=
VESSEL_VIEWS.sheet.columns * VESSEL_VIEWS.sheet.rows,
);
});
test('every AIS ship type, 0 to 99, draws a shape the sheet holds, in its kind’s colour', () => {
// ITU-R M.1371: the families by their tens, and the types with a hull of
// their own.
const shapeOf = (code) => vesselShape(String(code));
const kindOf = (code) => vesselKind(String(code));
for (let code = 0; code < 100; code++) {
assert.ok(Number.isInteger(VESSEL_VIEWS.subjects[shapeOf(code)]), code);
assert.ok(VESSEL_KINDS.includes(kindOf(code)), code);
}
const drawn = (codes, shape, kind = shape) =>
codes.forEach((code) =>
assert.deepEqual([shapeOf(code), kindOf(code)], [shape, kind], code),
);
const tens = (ten) => Array.from({ length: 10 }, (_, i) => ten * 10 + i);
drawn(tens(7), 'cargo');
drawn(tens(8), 'tanker');
drawn(tens(6), 'passenger');
drawn(tens(4), 'highspeed');
drawn([30], 'fishing');
drawn([31, 32, 52], 'tug');
drawn([36], 'sailing');
drawn([37], 'pleasure');
drawn([35, 55], 'military');
drawn([33], 'dredger', 'other');
// Pilot, port tender and anti-pollution craft are service boats (the
// tug's colour); search and rescue is a patrol colour. One small hull.
drawn([50, 53, 54], 'pilot', 'tug');
drawn([51], 'pilot', 'military');
// Wing-in-ground craft, diving and medical vessels, the reserved and
// spare codes and "other": the plain hull.
drawn(
[0, 1, 19, ...tens(2), 34, 38, 39, 56, 57, 58, 59, ...tens(9)],
'other',
);
// A feed that names the type in words draws the same shapes.
assert.equal(vesselShape('Dredger'), 'dredger');
assert.equal(vesselShape('Pilot Vessel'), 'pilot');
assert.equal(vesselShape('Search and Rescue'), 'pilot');
// However the words are joined, the hull and the colour are the code's.
for (const text of ['Search & Rescue', 'Search-and-rescue', 'SAR'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'military'],
text,
);
for (const text of ['Anti Pollution', 'Anti-pollution', 'Port Tender'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'tug'],
text,
);
assert.equal(vesselShape('Tug'), 'tug');
assert.equal(vesselShape('Container Ship'), 'cargo');
assert.equal(vesselShape(''), 'other');
});
test('a vessel draws its shape’s block of the sheet, with its kind’s flat hull to fall back on', () => {
for (const kind of VESSEL_KINDS) {
const ref = vesselViewRef(kind);
assert.deepEqual(ref, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[kind],
fallback: vesselSprite(kind),
});
assert.ok(Object.isFrozen(ref));
// One object a shape and kind: an unchanged icon is seen as unchanged.
assert.equal(vesselViewRef(kind), ref);
}
// A shape within a kind: its own block, its kind's flat hull.
assert.deepEqual(vesselViewRef('pilot', 'tug'), {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
assert.notEqual(
vesselViewRef('pilot', 'tug'),
vesselViewRef('pilot', 'military'),
);
assert.equal(
vesselViewRef('dredger', 'other').first,
VESSEL_VIEWS.subjects.dredger,
);
// A shape the sheet does not hold: its kind's block, then `other`'s.
assert.equal(
vesselViewRef('hovercraft', 'highspeed'),
vesselViewRef('highspeed'),
);
assert.equal(vesselViewRef('submarine'), vesselViewRef('other'));
assert.equal(vesselViewRef(undefined), vesselViewRef('other'));
});
test('the sheet is registered once a port, at the layer’s asset URL, on a renderer that draws views', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const views = new Set(['viewSheets']);
const resolve = (url) => `/gev${url}`;
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(calls.length, 1);
assert.equal(calls[0][0], VESSEL_VIEWS.id);
assert.deepEqual(calls[0][1], {
...VESSEL_VIEWS.sheet,
image: '/gev/sprites/vessel-views.webp',
});
// No capability, no port, or a port without `views`: flat hulls.
assert.equal(registerVesselViews(port, new Set(), resolve), false);
assert.equal(registerVesselViews(port, null), false);
assert.equal(registerVesselViews(null, views), false);
assert.equal(registerVesselViews({}, views), false);
});
-295
View File
@@ -1,295 +0,0 @@
/**
* @module viewSheet
* @description A view sheet: one image of small sprites showing a subject
* (an aircraft class) from a sphere of directions, and the maths that picks
* the sprite for where the eye is. Plain JavaScript and GLSL: no DOM, no
* engine. `scripts/bake-view-sheet.py` bakes the aircraft and
* vessel sheets to their layouts here; a renderer with the `viewSheets`
* capability draws them.
*
* **Frames.** A subject lies flat on the earth: up is the ground's normal,
* forward its course. `d` is the direction from the subject to the eye in
* the subject's own axes `[forward, right, up]`. A sheet holds each subject
* as a block of consecutive cells, row-major: rings of frames `ringStepDeg`
* apart, from straight above (ring 0) downward, ring `k` holding `rings[k]`
* frames from the eye dead ahead, round the right side, to dead astern. The
* left side is the right-side frame mirrored, so a sheet's subjects and
* their light are symmetric about their centre plane.
*
* **Roll.** A frame's image up is {@link frameUp}: forward, turned by the
* smallest rotation that takes up onto the frame's direction. Straight
* above, the nose points up the image; the roll then changes smoothly all
* the way round and below. It has no meaning only from straight below, so a
* sheet's last ring stays short of that.
*
* **Between frames.** The frame nearest the eye's direction is drawn
* ({@link viewFrame}), as a card standing where its subject is, square to
* the frame's own direction: seen from a little to one side it is tilted
* (foreshortened and turned) as the subject itself would be, until the next
* frame is the nearer. Frames are not blended.
*/
/** Rings a sheet may hold (the shader's uniform array); even. */
export const VIEW_RINGS_MAX = 18;
/** The aircraft classes' view sheet (`public/sprites/aircraft-views.json`). */
export const AIRCRAFT_VIEWS = Object.freeze({
id: 'aircraft-views',
sheet: Object.freeze({
image: '/sprites/aircraft-views.webp',
cellPx: 64,
columns: 64,
rows: 57,
ringStepDeg: 7.5,
rings: Object.freeze([
1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22,
]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 302,
/** Each subject's first cell. */
subjects: Object.freeze({
airliner: 0,
widebody: 302,
quadjet: 604,
turboprop: 906,
light: 1208,
glider: 1510,
fastjet: 1812,
bizjet: 2114,
uav: 2416,
helicopter0: 2718,
helicopter1: 3020,
helicopter2: 3322,
}),
});
/**
* The vessel hull shapes' view sheet (`public/sprites/vessel-views.json`):
* from straight above down to the horizon, a ship never being seen from
* below.
*/
export const VESSEL_VIEWS = Object.freeze({
id: 'vessel-views',
sheet: Object.freeze({
image: '/sprites/vessel-views.webp',
cellPx: 64,
columns: 64,
rows: 39,
ringStepDeg: 7.5,
rings: Object.freeze([1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 208,
/**
* Each hull shape's first cell (`vesselShape`, vesselTypes.js): the ten
* hull kinds, then the shapes drawn within a kind.
*/
subjects: Object.freeze({
cargo: 0,
tanker: 208,
passenger: 416,
highspeed: 624,
fishing: 832,
tug: 1040,
sailing: 1248,
pleasure: 1456,
military: 1664,
other: 1872,
dredger: 2080,
pilot: 2288,
}),
});
/**
* Check a sheet's layout, and return it with each ring's first frame.
* @param {{image: string, cellPx: number, columns: number, rows: number,
* ringStepDeg: number, rings: readonly number[], grey?: boolean}} sheet
* @returns {{columns: number, rows: number, ringStepRad: number,
* rings: number[], firsts: number[], frames: number}}
*/
export function viewLayout(sheet) {
const whole = (n) => Number.isInteger(n) && n > 0;
if (!sheet || typeof sheet.image !== 'string' || !sheet.image)
throw new TypeError('a view sheet needs its image URL');
if (!whole(sheet.cellPx) || !whole(sheet.columns) || !whole(sheet.rows))
throw new TypeError(
'a view sheet needs whole cellPx, columns and rows above 0',
);
const { rings, ringStepDeg } = sheet;
if (
!Array.isArray(rings) ||
rings.length < 1 ||
rings.length > VIEW_RINGS_MAX ||
!rings.every(whole)
)
throw new TypeError(
`a view sheet needs 1 to ${VIEW_RINGS_MAX} rings of whole frame counts`,
);
if (rings[0] !== 1)
throw new TypeError("a view sheet's first ring is the one frame above");
if (
!(ringStepDeg > 0) ||
!Number.isFinite(ringStepDeg) ||
(rings.length - 1) * ringStepDeg >= 180
)
throw new TypeError("a view sheet's rings stop short of straight below");
const firsts = [];
let frames = 0;
for (const count of rings) {
firsts.push(frames);
frames += count;
}
return {
columns: sheet.columns,
rows: sheet.rows,
ringStepRad: (ringStepDeg * Math.PI) / 180,
rings: [...rings],
firsts,
frames,
};
}
/**
* The frame that shows a subject from `d`.
* @param {ReturnType<typeof viewLayout>} layout
* @param {readonly [number, number, number]} d Toward the eye, as
* `[forward, right, up]`; any length above 0.
* @returns {{frame: number, ring: number, index: number, mirrored: boolean}}
* `frame` counts from the subject's first cell; `mirrored` draws it flipped
* left to right (the eye on the left side).
*/
export function viewFrame(layout, d) {
const length = Math.hypot(d[0], d[1], d[2]);
const up = length > 0 ? Math.min(1, Math.max(-1, d[2] / length)) : 1;
const ring = Math.min(
layout.rings.length - 1,
Math.floor(Math.acos(up) / layout.ringStepRad + 0.5),
);
const span = layout.rings[ring] - 1;
const side = Math.abs(d[1]);
const bearing = side + Math.abs(d[0]) > 0 ? Math.atan2(side, d[0]) : 0;
const index = span > 0 ? Math.floor((bearing / Math.PI) * span + 0.5) : 0;
return {
frame: layout.firsts[ring] + index,
ring,
index,
mirrored: d[1] < 0,
};
}
/**
* The direction a frame shows its subject from: a unit `[forward, right,
* up]`, on the right side (or the left, mirrored).
*/
export function frameDirection(layout, ring, index, mirrored = false) {
const off = ring * layout.ringStepRad;
const span = layout.rings[ring] - 1;
const turn = span > 0 ? (index / span) * Math.PI : 0;
return [
Math.sin(off) * Math.cos(turn),
Math.sin(off) * Math.sin(turn) * (mirrored ? -1 : 1),
Math.cos(off),
];
}
/**
* A frame's image up, for the unit direction `d` it shows its subject from:
* forward, turned as up turns onto `d`. A unit `[forward, right, up]`,
* perpendicular to `d`.
*/
export function frameUp(d) {
const k = 1 / Math.max(1 + d[2], 1e-6);
return [1 - d[0] * d[0] * k, -d[0] * d[1] * k, -d[0]];
}
/**
* A sheet's layout as the shader's uniforms: `grid`, and `rings` as one
* vector for each two rings (`[frames, first, frames, first]`).
*/
export function viewUniforms(layout) {
const rings = [];
for (let k = 0; k < VIEW_RINGS_MAX; k += 2)
rings.push([
layout.rings[k] ?? 1,
layout.firsts[k] ?? 0,
layout.rings[k + 1] ?? 1,
layout.firsts[k + 1] ?? 0,
]);
return {
grid: [
layout.columns,
layout.rows,
layout.ringStepRad,
layout.rings.length,
],
rings,
};
}
/**
* {@link viewFrame}, {@link frameDirection} and {@link frameUp} in GLSL, over `u_viewGrid` (columns, rows, ring step in radians, rings) and
* `u_viewRings` (each ring's frames and first frame, two rings a vector).
*/
export const VIEW_SHEET_GLSL = /* glsl */ `
uniform vec4 u_viewGrid;
uniform vec4 u_viewRings[${VIEW_RINGS_MAX / 2}];
// A ring's frames and its first frame, from the subject's first cell.
vec2 viewRing(float ring) {
vec4 pair = u_viewRings[int(ring * 0.5)];
return ring - 2.0 * floor(ring * 0.5) < 0.5 ? pair.xy : pair.zw;
}
// The frame that shows a subject from d (unit, toward the eye, as forward,
// right, up): its ring, its index in the ring, and 1 when it is drawn
// mirrored (the eye on the left side).
vec3 viewNearest(vec3 d) {
float ring = clamp(
floor(acos(clamp(d.z, -1.0, 1.0)) / u_viewGrid.z + 0.5),
0.0, u_viewGrid.w - 1.0);
float span = viewRing(ring).x - 1.0;
float side = abs(d.y);
float bearing = side + abs(d.x) > 0.0 ? atan(side, d.x) : 0.0;
return vec3(
ring,
span > 0.0 ? floor(bearing / 3.141592653589793 * span + 0.5) : 0.0,
d.y < 0.0 ? 1.0 : 0.0);
}
// The direction a frame shows its subject from (toward the eye, as forward,
// right, up; flip 1 for the left side) and the frame's image up.
void viewFrameAxes(float ring, float index, float flip, out vec3 toEye, out vec3 up) {
float span = viewRing(ring).x - 1.0;
float off = ring * u_viewGrid.z;
float turn = span > 0.0 ? index / span * 3.141592653589793 : 0.0;
toEye = vec3(
sin(off) * cos(turn),
sin(off) * sin(turn) * (1.0 - 2.0 * flip),
cos(off));
float k = 1.0 / max(1.0 + toEye.z, 1.0e-6);
up = vec3(1.0 - toEye.x * toEye.x * k, -toEye.x * toEye.y * k, -toEye.x);
}
`;
/**
* Reading a view sheet's cells in a fragment shader: `viewCell(cell, uv,
* lod)` is the colour of a cell at `uv` (0..1 across it, v down) and that
* level of detail, nothing outside it, from `u_views` over `u_viewGrid`.
*/
export const VIEW_SHEET_FRAGMENT_GLSL = /* glsl */ `
uniform sampler2D u_views;
uniform vec4 u_viewGrid;
vec4 viewCell(float cell, vec2 uv, float lod) {
float at = floor(cell + 0.5);
float row = floor((at + 0.5) / u_viewGrid.x);
float column = at - row * u_viewGrid.x;
vec2 inside = step(vec2(0.0), uv) * step(uv, vec2(1.0));
vec4 color = textureLod(
u_views, (vec2(column, row) + clamp(uv, 0.0, 1.0)) / u_viewGrid.xy, lod);
return color * (inside.x * inside.y);
}
`;
-429
View File
@@ -1,429 +0,0 @@
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import {
AIRCRAFT_VIEWS,
VESSEL_VIEWS,
frameDirection,
frameUp,
viewFrame,
viewLayout,
viewUniforms,
VIEW_RINGS_MAX,
} from './viewSheet.js';
const layout = viewLayout(AIRCRAFT_VIEWS.sheet);
const RAD = Math.PI / 180;
const HORIZON = 12; // the ring at 90° from straight above
/** The pinned layout: rings 7.5° apart, 302 frames a subject. */
const RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22];
const FIRSTS = [
0, 1, 5, 12, 22, 35, 51, 69, 89, 111, 134, 158, 183, 208, 233, 257, 280,
];
/** A unit `[forward, right, up]` `offDeg` from straight above, at `bearingDeg`
* from dead ahead toward the right side. */
function direction(offDeg, bearingDeg) {
const off = offDeg * RAD;
const bearing = bearingDeg * RAD;
return [
Math.sin(off) * Math.cos(bearing),
Math.sin(off) * Math.sin(bearing),
Math.cos(off),
];
}
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const mirror = (v) => [v[0], -v[1], v[2]];
const near = (a, b, eps = 1e-9) =>
a.every((value, i) => Math.abs(value - b[i]) < eps);
/** The smallest rotation taking up onto `d`, applied to forward (Rodrigues). */
function rotatedForward(d) {
const up = [0, 0, 1];
const forward = [1, 0, 0];
const axis = cross(up, d);
const sin = Math.hypot(...axis);
const cos = dot(up, d);
if (sin < 1e-12) return forward;
const k = axis.map((value) => value / sin);
const kxv = cross(k, forward);
const kv = dot(k, forward);
return forward.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
}
test('viewLayout gives the aircraft sheet each ring’s first frame', () => {
assert.deepEqual(layout.rings, RINGS);
assert.deepEqual(layout.firsts, FIRSTS);
assert.equal(layout.frames, 302);
assert.equal(layout.columns, 64);
assert.equal(layout.rows, 57);
assert.equal(layout.ringStepRad, 7.5 * RAD);
assert.notEqual(layout.rings, AIRCRAFT_VIEWS.sheet.rings, 'a copy');
});
test('viewLayout refuses a sheet it cannot draw', () => {
const sheet = AIRCRAFT_VIEWS.sheet;
const bad = [
null,
{ ...sheet, image: '' },
{ ...sheet, image: undefined },
{ ...sheet, cellPx: 63.5 },
{ ...sheet, columns: 0 },
{ ...sheet, rows: -32 },
{ ...sheet, rings: [] },
{ ...sheet, rings: 'many' },
{ ...sheet, rings: Array(VIEW_RINGS_MAX + 1).fill(1) },
{ ...sheet, rings: [3, 5] },
{ ...sheet, rings: [1, 2.5] },
{ ...sheet, rings: [1, 0] },
{ ...sheet, ringStepDeg: 0 },
{ ...sheet, ringStepDeg: -15 },
{ ...sheet, ringStepDeg: Number.NaN },
{ ...sheet, ringStepDeg: Infinity },
// A ring straight below, or past it.
{ ...sheet, rings: [1, 4, 4, 1], ringStepDeg: 60 },
{ ...sheet, rings: Array(13).fill(1), ringStepDeg: 15 },
];
for (const sheetGiven of bad)
assert.throws(
() => viewLayout(sheetGiven),
TypeError,
JSON.stringify(sheetGiven),
);
// Short of straight below, and the most rings there may be, are drawn.
assert.equal(viewLayout({ ...sheet, rings: Array(12).fill(1) }).frames, 12);
assert.equal(
viewLayout({
...sheet,
rings: Array(VIEW_RINGS_MAX).fill(1),
ringStepDeg: 10,
}).rings.length,
VIEW_RINGS_MAX,
);
});
test('straight above is frame 0, whatever the course', () => {
assert.deepEqual(viewFrame(layout, [0, 0, 1]), {
frame: 0,
ring: 0,
index: 0,
mirrored: false,
});
assert.equal(viewFrame(layout, [0, 0, 42]).frame, 0, 'any length');
assert.equal(viewFrame(layout, direction(3.7, 135)).frame, 0);
assert.equal(viewFrame(layout, [0, 0, 0]).frame, 0, 'no direction: above');
});
test('on the horizon, dead ahead, abeam and astern are the first, middle and last frames of ring 12', () => {
const first = layout.firsts[HORIZON];
const ahead = viewFrame(layout, [1, 0, 0]);
assert.deepEqual(ahead, {
frame: first,
ring: 12,
index: 0,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [0, 1, 0]), {
frame: first + 12,
ring: 12,
index: 12,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [-1, 0, 0]), {
frame: first + 24,
ring: 12,
index: 24,
mirrored: false,
});
});
test('the left side draws the right side’s frame mirrored', () => {
for (const [off, bearing] of [
[30, 40],
[90, 90],
[105, 170],
[60, 1],
]) {
const right = viewFrame(layout, direction(off, bearing));
const left = viewFrame(layout, mirror(direction(off, bearing)));
assert.equal(left.frame, right.frame, `${off}/${bearing}`);
assert.equal(right.mirrored, false);
assert.equal(left.mirrored, true);
}
// Exactly on the centre plane it is not mirrored.
assert.equal(viewFrame(layout, [1, 0, 0]).mirrored, false);
assert.equal(viewFrame(layout, [1, -0, 0]).mirrored, false);
});
test('below the last ring the eye takes the last ring', () => {
const last = layout.rings.length - 1;
for (const off of [120, 126, 135, 170, 180]) {
const view = viewFrame(layout, direction(off, 90));
assert.equal(view.ring, last, `${off}°`);
}
assert.equal(viewFrame(layout, [0, 0, -1]).frame, layout.firsts[last]);
});
test('frames round to the nearest, between rings and between bearings', () => {
// Rings are 7.5° apart: 3.75° from straight above is between ring 0 and 1.
assert.equal(viewFrame(layout, direction(3.7, 0)).ring, 0);
assert.equal(viewFrame(layout, direction(3.8, 0)).ring, 1);
assert.equal(viewFrame(layout, direction(86.2, 0)).ring, 11);
assert.equal(viewFrame(layout, direction(86.3, 0)).ring, 12);
// The horizon ring's 25 frames are 7.5° of bearing apart.
assert.equal(viewFrame(layout, direction(90, 3.7)).index, 0);
assert.equal(viewFrame(layout, direction(90, 3.8)).index, 1);
assert.equal(viewFrame(layout, direction(90, 176.2)).index, 23);
assert.equal(viewFrame(layout, direction(90, 176.3)).index, 24);
// Ring 1's 4 frames are 60° apart.
assert.equal(viewFrame(layout, direction(7.5, 29.9)).index, 0);
assert.equal(viewFrame(layout, direction(7.5, 30.1)).index, 1);
});
test('frameDirection is where viewFrame finds each frame of the sheet', () => {
let frames = 0;
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-12, 'unit');
const view = viewFrame(layout, d);
assert.equal(view.ring, ring, `${ring}/${index}`);
assert.equal(view.index, index, `${ring}/${index}`);
assert.equal(view.frame, layout.firsts[ring] + index);
// A frame on the centre plane is its own mirror image: either way
// draws it.
if (Math.abs(d[1]) > 1e-12) assert.equal(view.mirrored, mirrored);
}
frames++;
}
assert.equal(frames, AIRCRAFT_VIEWS.frames);
});
test('frameUp is a unit vector across the view, forward from straight above, and turns as the smallest rotation does', () => {
assert.ok(near(frameUp([0, 0, 1]), [1, 0, 0]), 'nose up the image');
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++)
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
const up = frameUp(d);
const at = `${ring}/${index}${mirrored ? ' mirrored' : ''}`;
assert.ok(Math.abs(Math.hypot(...up) - 1) < 1e-9, `unit at ${at}`);
assert.ok(Math.abs(dot(up, d)) < 1e-9, `across the view at ${at}`);
assert.ok(
near(up, rotatedForward(d)),
`the smallest rotation at ${at}`,
);
// Mirroring the eye mirrors the image's up.
assert.ok(near(frameUp(mirror(d)), mirror(up)), `mirrored at ${at}`);
}
// On the horizon, abeam: the nose still points up the image.
assert.ok(near(frameUp([0, 1, 0]), [1, 0, 0]));
// Dead ahead on the horizon: the image's up is straight down the aircraft.
assert.ok(near(frameUp([1, 0, 0]), [0, 0, -1]));
});
test('viewUniforms packs the layout as the shader reads it', () => {
const { grid, rings } = viewUniforms(layout);
assert.deepEqual(grid, [64, 57, 7.5 * RAD, 17]);
// Two rings a vector: each ring's frames and its first frame.
assert.equal(rings.length, VIEW_RINGS_MAX / 2);
const pairs = [];
for (let k = 0; k < RINGS.length; k += 2)
pairs.push([RINGS[k], FIRSTS[k], RINGS[k + 1] ?? 1, FIRSTS[k + 1] ?? 0]);
assert.deepEqual(rings.slice(0, pairs.length), pairs);
for (const pair of rings.slice(pairs.length))
assert.deepEqual(pair, [1, 0, 1, 0], 'padding');
});
test('AIRCRAFT_VIEWS is consistent: a block a subject, every block on the sheet', () => {
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(
frames,
sheet.rings.reduce((a, b) => a + b, 0),
);
assert.equal(frames, 302);
assert.equal(sheet.cellPx * sheet.columns, 4096);
assert.equal(sheet.cellPx * sheet.rows, 3648);
assert.equal(sheet.grey, true, 'kept as grey and alpha');
const firsts = Object.values(subjects);
firsts.forEach((first, i) => {
assert.equal(first, i * frames, 'in order, one block after another');
assert.equal(first % frames, 0);
assert.ok(first + frames <= sheet.columns * sheet.rows, 'on the sheet');
});
assert.ok(Object.isFrozen(AIRCRAFT_VIEWS));
assert.ok(Object.isFrozen(sheet));
assert.ok(Object.isFrozen(sheet.rings));
assert.ok(Object.isFrozen(subjects));
});
const BAKE = new URL('../../scripts/bake-view-sheet.py', import.meta.url);
/** The sheets the bake script bakes: its config name, the layout it must
* match, the files it ships and the size the layout pins. */
const SHEETS = [
{
config: 'AIRCRAFT',
views: AIRCRAFT_VIEWS,
name: 'aircraft-views',
frames: 302,
size: [4096, 3648],
},
{
config: 'VESSELS',
views: VESSEL_VIEWS,
name: 'vessel-views',
frames: 208,
size: [4096, 2496],
},
];
/** A sheet's entry in the bake script: `NAME = { ... }`. */
function bakeConfig(script, config) {
const block = new RegExp(`^${config} = \\{([\\s\\S]*?)^\\}`, 'm').exec(
script,
);
assert.ok(block, `${config} in the bake script`);
const field = (key) => {
const match = new RegExp(`^\\s*"${key}": (.+),$`, 'm').exec(block[1]);
assert.ok(match, `${config}.${key} in the bake script`);
return JSON.parse(match[1]);
};
const names = [...block[1].matchAll(/^\s*\("(\w+)", "([\w/.]+)"/gm)];
return {
field,
names: names.map((m) => m[1]),
models: names.map((m) => m[2]),
};
}
for (const { config, views, name, frames, size } of SHEETS) {
test(`${views.id} is pinned: ${frames} frames a subject, ${size.join(' × ')} px`, () => {
const { sheet } = views;
assert.equal(views.frames, frames);
assert.equal(viewLayout(sheet).frames, frames);
assert.equal(sheet.cellPx * sheet.columns, size[0]);
assert.equal(sheet.cellPx * sheet.rows, size[1]);
assert.equal(sheet.image, `/sprites/${name}.webp`);
assert.equal(sheet.grey, true);
});
test(`the bake script lays ${views.id} out as the layout says`, () => {
const { field, names } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(field('name'), name);
assert.equal(field('ring_step_deg'), sheet.ringStepDeg);
assert.deepEqual(field('rings'), [...sheet.rings]);
assert.equal(field('columns'), sheet.columns);
assert.deepEqual(
names,
Object.keys(subjects),
'the same subjects in order',
);
// The script's rows: as many as its subjects' blocks take.
assert.equal(
Math.ceil((names.length * frames) / sheet.columns),
sheet.rows,
);
});
const manifestUrl = new URL(
`../../public/sprites/${name}.json`,
import.meta.url,
);
test(`the baked manifest matches ${views.id}`, () => {
// Shipped with the app: a missing manifest fails, it does not skip.
assert.ok(existsSync(manifestUrl), `public/sprites/${name}.json`);
const manifest = JSON.parse(readFileSync(manifestUrl, 'utf8'));
const { models } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(manifest.cellPx, sheet.cellPx);
assert.equal(manifest.columns, sheet.columns);
assert.equal(manifest.rows, sheet.rows);
assert.equal(manifest.ringStepDeg, sheet.ringStepDeg);
assert.deepEqual(manifest.rings, [...sheet.rings]);
assert.equal(manifest.grey, true);
assert.equal(manifest.image, `${name}.webp`);
assert.deepEqual(Object.keys(manifest.subjects), Object.keys(subjects));
Object.entries(subjects).forEach(([subject, first], i) => {
assert.equal(manifest.subjects[subject].first, first, subject);
assert.equal(manifest.subjects[subject].model, models[i], subject);
assert.ok(manifest.subjects[subject].radiusM > 0, `${subject} baked`);
});
});
const sheetUrl = new URL(
`../../public/sprites/${name}.webp`,
import.meta.url,
);
test(`the shipped ${name}.webp is the size the layout says, grey, and clear at every cell’s edge`, async () => {
assert.ok(existsSync(sheetUrl), `public/sprites/${name}.webp`);
const { default: sharp } = await import('sharp');
const { sheet, subjects } = views;
const { data, info } = await sharp(fileURLToPath(sheetUrl))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
assert.equal(info.width, sheet.columns * sheet.cellPx);
assert.equal(info.height, sheet.rows * sheet.cellPx);
const at = (x, y) => (y * info.width + x) * 4;
// Grey: the renderer reads the red channel as the grey.
for (let i = 0; i < data.length; i += 4)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2])
assert.fail(`not grey at pixel ${i / 4}`);
// Each used cell keeps its outer 2 px transparent (the mipmaps), and
// has something in it.
const used = Object.keys(subjects).length * frames;
const c = sheet.cellPx;
for (let n = 0; n < used; n++) {
const left = (n % sheet.columns) * c;
const top = Math.floor(n / sheet.columns) * c;
let drawn = 0;
for (let y = 0; y < c; y++)
for (let x = 0; x < c; x++) {
const alpha = data[at(left + x, top + y) + 3];
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) drawn += alpha;
else if (alpha !== 0)
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
}
assert.ok(drawn > 0, `cell ${n} is empty`);
}
});
}
test('in the bake’s axes (nose −X, starboard +Y, up +Z) a frame has the same up and direction', () => {
// The bake turns forward by Blender's rotation_difference(UP, d), in its
// own axes, which are mirrored from [forward, right, up]: the smallest
// rotation is the same rotation in either.
const toBake = (v) => [-v[0], v[1], v[2]];
const minimal = (from, to, v) => {
const axis = cross(from, to);
const sin = Math.hypot(...axis);
const cos = dot(from, to);
if (sin < 1e-12) return v;
const k = axis.map((value) => value / sin);
const kxv = cross(k, v);
const kv = dot(k, v);
return v.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
};
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
const d = frameDirection(layout, ring, index);
const bakeUp = minimal([0, 0, 1], toBake(d), toBake([1, 0, 0]));
assert.ok(near(toBake(frameUp(d)), bakeUp), `${ring}/${index}`);
}
});
/** A blend's weight by frame (a frame listed twice counts once, summed). */
+8 -14
View File
@@ -1521,6 +1521,7 @@
"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": "إعصار مداري محتمل",
@@ -1548,12 +1549,17 @@
"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": "مشي",
@@ -1977,6 +1983,7 @@
"Moving dots colored by live flow": "نقاط متحركة ملوّنة حسب التدفق المباشر",
"Moving dots": "نقاط متحركة",
"TomTom key unavailable": "مفتاح TomTom غير متاح",
"TomTom key rejected": "تم رفض مفتاح TomTom",
"TomTom daily budget reached": "بلغت الحصة اليومية لـ TomTom",
"Monthly traffic allowance used": "تم استهلاك حصة حركة المرور الشهرية",
"Traffic rate limit reached": "تم بلوغ حد طلبات حركة المرور",
@@ -4843,18 +4850,5 @@
"Telemetry reads while the model is on screen": "تُقرأ القياسات أثناء ظهور النموذج على الشاشة",
"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.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط.",
"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}"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
}
+8 -14
View File
@@ -1436,6 +1436,7 @@
"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",
@@ -1459,12 +1460,17 @@
"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",
@@ -1854,6 +1860,7 @@
"Moving dots colored by live flow": "Bewegte Punkte nach Live-Verkehrsfluss gefärbt",
"Moving dots": "Bewegte Punkte",
"TomTom key unavailable": "TomTom-Schlüssel nicht verfügbar",
"TomTom key rejected": "TomTom-Schlüssel abgelehnt",
"TomTom daily budget reached": "TomTom-Tagesbudget erreicht",
"Monthly traffic allowance used": "Monatliches Verkehrskontingent aufgebraucht",
"Traffic rate limit reached": "Verkehrs-Anfragelimit erreicht",
@@ -4419,18 +4426,5 @@
"Telemetry reads while the model is on screen": "Telemetrie wird gelesen, solange das Modell zu sehen ist",
"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.",
"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}"
"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."
}
+8 -14
View File
@@ -1342,6 +1342,7 @@
"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",
@@ -1364,12 +1365,17 @@
"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",
@@ -2457,6 +2463,7 @@
"Military area": "Zona militar",
"SIMULATED — {reason}": "SIMULADO — {reason}",
"TomTom key unavailable": "Clave de TomTom no disponible",
"TomTom key rejected": "Clave de TomTom rechazada",
"TomTom daily budget reached": "Se alcanzó el límite diario de TomTom",
"Monthly traffic allowance used": "Cupo mensual de tráfico agotado",
"Traffic rate limit reached": "Límite de peticiones de tráfico alcanzado",
@@ -4525,18 +4532,5 @@
"Telemetry reads while the model is on screen": "La telemetría se lee mientras el modelo está en pantalla",
"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.",
"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}"
"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."
}
+8 -14
View File
@@ -644,6 +644,7 @@
"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",
@@ -668,12 +669,17 @@
"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",
@@ -1241,6 +1247,7 @@
"Moving dots colored by live flow": "Points mobiles colorés selon le trafic en direct",
"Moving dots": "Points mobiles",
"TomTom key unavailable": "Clé TomTom indisponible",
"TomTom key rejected": "Clé TomTom refusée",
"TomTom daily budget reached": "Quota quotidien TomTom atteint",
"Monthly traffic allowance used": "Quota mensuel de trafic épuisé",
"Traffic rate limit reached": "Limite de requêtes de trafic atteinte",
@@ -4525,18 +4532,5 @@
"Telemetry reads while the model is on screen": "La télémétrie est lue tant que le modèle est à l'écran",
"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.",
"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}"
"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."
}
+8 -14
View File
@@ -532,6 +532,7 @@
"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": "ציקלון טרופי פוטנציאלי",
@@ -556,12 +557,17 @@
"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": "נסיעה",
@@ -1086,6 +1092,7 @@
"TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "כבישי TomTom קודם; OpenStreetMap משלים את היתר, מדומים (דורש מפתח TomTom)",
"Hybrid": "היברידי",
"TomTom key unavailable": "מפתח TomTom אינו זמין",
"TomTom key rejected": "מפתח TomTom נדחה",
"TomTom daily budget reached": "תקציב TomTom היומי אזל",
"TomTom upstream unreachable": "שירות TomTom אינו נגיש",
"TomTom flow unavailable": "זרימת TomTom אינה זמינה",
@@ -4525,18 +4532,5 @@
"Telemetry reads while the model is on screen": "הטלמטריה נקראת כל עוד הדגם מוצג על המסך",
"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.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד.",
"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}"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
}
+8 -14
View File
@@ -644,6 +644,7 @@
"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",
@@ -668,12 +669,17 @@
"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",
@@ -1241,6 +1247,7 @@
"Moving dots colored by live flow": "Punti in movimento colorati in base al flusso live",
"Moving dots": "Punti in movimento",
"TomTom key unavailable": "Chiave TomTom non disponibile",
"TomTom key rejected": "Chiave TomTom rifiutata",
"TomTom daily budget reached": "Budget giornaliero TomTom esaurito",
"Monthly traffic allowance used": "Quota mensile del traffico esaurita",
"Traffic rate limit reached": "Limite di richieste del traffico raggiunto",
@@ -4525,18 +4532,5 @@
"Telemetry reads while the model is on screen": "La telemetria viene letta finché il modello è sullo schermo",
"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.",
"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}"
"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."
}
+8 -14
View File
@@ -616,6 +616,7 @@
"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,12 +639,17 @@
"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": "徒歩",
@@ -1195,6 +1201,7 @@
"Moving dots colored by live flow": "ライブの交通流で色分けした移動ドット",
"Moving dots": "移動ドット",
"TomTom key unavailable": "TomTomキーを利用できません",
"TomTom key rejected": "TomTomキーが拒否されました",
"TomTom daily budget reached": "TomTomの1日の上限に達しました",
"Monthly traffic allowance used": "今月の交通情報の上限に達しました",
"Traffic rate limit reached": "交通情報のリクエスト上限に達しました",
@@ -4313,18 +4320,5 @@
"Telemetry reads while the model is on screen": "テレメトリはモデルが画面にある間に読み取られます",
"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基のアンテナは動かず、アームは説明用にゆっくり動きます。",
"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} 発表"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
}
+8 -14
View File
@@ -644,6 +644,7 @@
"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",
@@ -668,12 +669,17 @@
"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É",
@@ -1239,6 +1245,7 @@
"Moving dots colored by live flow": "Pontos em movimento coloridos pelo fluxo ao vivo",
"Moving dots": "Pontos em movimento",
"TomTom key unavailable": "Chave do TomTom indisponível",
"TomTom key rejected": "Chave do TomTom recusada",
"TomTom daily budget reached": "Limite diário do TomTom atingido",
"Monthly traffic allowance used": "Cota mensal de trânsito esgotada",
"Traffic rate limit reached": "Trânsito: limite de requisições atingido",
@@ -4525,18 +4532,5 @@
"Telemetry reads while the model is on screen": "A telemetria é lida enquanto o modelo está no ecrã",
"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.",
"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}"
"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."
}
+8 -14
View File
@@ -1369,6 +1369,7 @@
"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": "Ураган",
@@ -1392,12 +1393,17 @@
"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": "ЩЁЛКНИТЕ ПО КАРТЕ",
@@ -2506,6 +2512,7 @@
"Military area": "Военная зона",
"SIMULATED — {reason}": "СИМУЛЯЦИЯ — {reason}",
"TomTom key unavailable": "Ключ TomTom недоступен",
"TomTom key rejected": "Ключ TomTom отклонён",
"TomTom daily budget reached": "Исчерпан дневной лимит TomTom",
"Monthly traffic allowance used": "Месячный лимит данных о трафике исчерпан",
"Traffic rate limit reached": "Достигнут лимит запросов данных о трафике",
@@ -4631,18 +4638,5 @@
"Telemetry reads while the model is on screen": "Телеметрия читается, пока модель на экране",
"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 в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации.",
"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}"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
}
+8 -14
View File
@@ -1352,6 +1352,7 @@
"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",
@@ -1375,12 +1376,17 @@
"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",
@@ -1770,6 +1776,7 @@
"Moving dots colored by live flow": "Rörliga punkter färgade efter trafikflödet live",
"Moving dots": "Rörliga punkter",
"TomTom key unavailable": "TomTom-nyckel otillgänglig",
"TomTom key rejected": "TomTom-nyckeln avvisades",
"TomTom daily budget reached": "TomTom-dagsbudgeten är förbrukad",
"Monthly traffic allowance used": "Månadens trafikkvot är förbrukad",
"Traffic rate limit reached": "Trafiktjänsten har nått gränsen för förfrågningar",
@@ -4419,18 +4426,5 @@
"Telemetry reads while the model is on screen": "Telemetri läses medan modellen syns på skärmen",
"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.",
"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}"
"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."
}
+8 -14
View File
@@ -658,6 +658,7 @@
"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": "Потенційний тропічний циклон",
@@ -683,12 +684,17 @@
"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": "ПІШКИ",
@@ -1263,6 +1269,7 @@
"Moving dots colored by live flow": "Рухомі точки, забарвлені за потоком онлайн",
"Moving dots": "Рухомі точки",
"TomTom key unavailable": "Ключ TomTom недоступний",
"TomTom key rejected": "Ключ TomTom відхилено",
"TomTom daily budget reached": "Вичерпано денний ліміт TomTom",
"Monthly traffic allowance used": "Місячний ліміт даних про дорожній рух вичерпано",
"Traffic rate limit reached": "Перевищено ліміт запитів до сервісу руху",
@@ -4631,18 +4638,5 @@
"Telemetry reads while the model is on screen": "Телеметрія читається, поки модель на екрані",
"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 в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації.",
"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}"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
}
+8 -14
View File
@@ -615,6 +615,7 @@
"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": "潜在热带气旋",
@@ -637,12 +638,17 @@
"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": "步行",
@@ -1172,6 +1178,7 @@
"Moving dots colored by live flow": "按实时路况着色的移动圆点",
"Moving dots": "移动圆点",
"TomTom key unavailable": "TomTom 密钥不可用",
"TomTom key rejected": "TomTom 密钥被拒绝",
"TomTom daily budget reached": "已达 TomTom 每日配额",
"Monthly traffic allowance used": "本月交通数据配额已用完",
"Traffic rate limit reached": "已达到交通数据请求频率上限",
@@ -4313,18 +4320,5 @@
"Telemetry reads while the model is on screen": "模型显示在屏幕上时读取遥测",
"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 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。",
"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}"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
}
+8 -14
View File
@@ -615,6 +615,7 @@
"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": "潛在熱帶氣旋",
@@ -637,12 +638,17 @@
"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": "步行",
@@ -1172,6 +1178,7 @@
"Moving dots colored by live flow": "按實時路況著色的移動圓點",
"Moving dots": "移動圓點",
"TomTom key unavailable": "TomTom 密鑰不可用",
"TomTom key rejected": "TomTom 密鑰被拒絕",
"TomTom daily budget reached": "已達 TomTom 每日配額",
"Monthly traffic allowance used": "本月交通數據配額已用完",
"Traffic rate limit reached": "已達到交通數據請求頻率上限",
@@ -4313,18 +4320,5 @@
"Telemetry reads while the model is on screen": "模型顯示在屏幕上時讀取遙測",
"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 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。",
"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}"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
}
+1 -1
View File
@@ -541,7 +541,7 @@
"Conversation",
"Country",
"Cyan",
"Cyclones · NHC / CPHC · JTWC",
"Cyclones · NHC / CPHC",
"DENSE",
"DEST ---°",
"DEST {bearing}",
+24 -2
View File
@@ -4,7 +4,6 @@ import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
findByDoublingRadius,
AWARENESS_RADIUS_M,
aircraftClassMatches,
} from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_EXAMPLES,
@@ -53,7 +52,29 @@ export function createNavigation({
return layerId === 'flights' || layerId === 'military';
}
const aircraftClassMatchesFilter = aircraftClassMatches;
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),
);
}
function selectNavigationTargets(
sourceCohorts,
@@ -244,6 +265,7 @@ export function createNavigation({
summarizeAwarenessCohortForNavigation,
resetNavigationVisitedCycle,
isFlightLayer,
normalizeAircraftClass,
aircraftClassMatchesFilter,
selectNavigationTargets,
alternativeFlightAvailable,
-24
View File
@@ -1,4 +1,3 @@
import { findCamera } from '../../render/rendererOf.js';
import {
FRAME_SIGNATURE_W,
FRAME_SIGNATURE_H,
@@ -42,11 +41,6 @@ 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
@@ -242,22 +236,6 @@ 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.
@@ -291,8 +269,6 @@ export function createFrames({ state: layerState, services, parts, source }) {
// bypass a provider's explicit minimum between image requests.
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
if (!force && sinceLastRefresh < refreshMs) return;
// Skip before stamping lastImageRefreshAt, so the first tick back in view fetches.
if (!force && !projectionInView(record)) return;
runtime.lastImageRefreshAt = now;
const frameUrl = frameUrlFor(record.camera, refreshMs);
-108
View File
@@ -3,7 +3,6 @@
// 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,
@@ -171,110 +170,3 @@ test('a failed pixel signature redraws rather than assuming equal content', () =
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
const MOUNT = { x: 0, y: 0, z: 0 };
function planeRecord() {
return {
camera: { id: 'plane' },
position: MOUNT,
frustumPositions: {
mount: MOUNT,
capCenter: { x: 1, y: 0, z: 0 },
tl: { x: 1, y: -1, z: 1 },
tr: { x: 1, y: 1, z: 1 },
br: { x: 1, y: 1, z: -1 },
bl: { x: 1, y: -1, z: -1 },
},
projection: {
mode: 'image',
image: {},
imageLoading: false,
imageReady: false,
lastImageRefreshAt: 0,
},
};
}
function framesFor(viewer) {
const state = {
_viewer: viewer,
_healthById: new Map(),
_activeCameraId: 'plane',
};
return createFrames({
state,
services: {},
parts: {
model: {
safeNumber: (value, fallback) =>
Number.isFinite(Number(value)) ? Number(value) : fallback,
},
},
source: { getFrameUrl: () => '/api/cctv/frame?id=plane' },
});
}
function framesWithCamera(t, camera) {
const host = {};
t.after(bindRenderer(host, { camera }));
return framesFor(host);
}
test('a plane the renderer may show fetches its picture', (t) => {
const visiblePoints = t.mock.fn(() => true);
const frames = framesWithCamera(t, { visiblePoints });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(
record.projection.image.src,
/^\/api\/cctv\/frame\?id=plane&projTs=/,
);
assert.equal(record.projection.imageLoading, true);
assert.equal(visiblePoints.mock.callCount(), 1);
const [points, margin] = visiblePoints.mock.calls[0].arguments;
const { mount, tl, tr, br, bl } = record.frustumPositions;
assert.deepEqual(points, [mount, tl, tr, br, bl]);
assert.equal(points[0], mount);
assert.equal(margin, 200);
});
test('a plane the renderer cannot show is not fetched, but a forced refresh is', (t) => {
const frames = framesWithCamera(t, { visiblePoints: () => false });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
assert.equal(record.projection.lastImageRefreshAt, 0);
frames.refreshProjectionImage(record, true);
assert.match(record.projection.image.src, /projTs=/);
});
test('a skipped refresh does not use up the interval', (t) => {
let visible = false;
const frames = framesWithCamera(t, { visiblePoints: () => visible });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
visible = true;
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
});
test('what cannot be judged counts as visible', (t) => {
for (const frames of [
framesWithCamera(t, { visiblePoints: () => null }),
framesWithCamera(t, { pose: () => ({}) }),
framesFor(null),
]) {
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
}
const noGeometry = planeRecord();
delete noGeometry.frustumPositions;
const visiblePoints = t.mock.fn(() => false);
framesWithCamera(t, { visiblePoints }).refreshProjectionImage(noGeometry);
assert.equal(visiblePoints.mock.callCount(), 0);
assert.match(noGeometry.projection.image.src, /projTs=/);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { setLocale, t } from '../../i18n/index.js';
// The exact string the server sends (COVERAGE in server/providers/cyclones.js).
const SERVER_COVERAGE =
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
const time = '2026-09-16T03:00:00.000Z';
const storm = {
id: 'ep152026',
+30 -71
View File
@@ -32,14 +32,8 @@ const utc = (value) =>
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${isolate(value.slice(11, 16))}\u00a0UTC`
: t('Unavailable');
const COVERAGE = msg(
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.',
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
);
// 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) =>
@@ -50,9 +44,7 @@ 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. JTWC
// warns of typhoons (TY), super typhoons (STY), tropical cyclones (TC) and
// subtropical storms and depressions (SS, SD).
// potential tropical cyclone, and subtropical systems are STS and STD.
const CLASSIFICATION_NAMES = Object.freeze({
PC: msg('Potential tropical cyclone'),
PTC: msg('Post-tropical cyclone'),
@@ -61,11 +53,6 @@ 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)
@@ -136,7 +123,7 @@ export function createCyclonesLayer({
id: contextId,
layerId: 'weather-cyclones',
layerName: 'Cyclone advisories',
source: sourceOf(storm),
source: 'NOAA NHC / CPHC',
label: storm.name,
latitude: storm.position.latitude,
longitude: storm.position.longitude,
@@ -150,7 +137,6 @@ export function createCyclonesLayer({
? CLASSIFICATION_NAMES[storm.classification]
: undefined,
basin: storm.basin,
agency: storm.agency,
advisoryNumber: storm.advisoryNumber,
issuedAt: storm.issuedAt,
positionAt: storm.positionAt,
@@ -160,7 +146,7 @@ export function createCyclonesLayer({
movementDirectionDegrees: storm.movement?.directionDegrees,
movementSpeedKt: storm.movement?.speedKt,
advisoryUrl: storm.advisoryUrl,
// Only while the proxy serves its cache because a source is unreachable.
// Only while the proxy serves its cache because NHC is unreachable.
staleCacheFetchedAt:
snapshot.stale && Number.isFinite(snapshot.fetchedAt)
? new Date(snapshot.fetchedAt).toISOString()
@@ -219,7 +205,7 @@ export function createCyclonesLayer({
id: 'weather-cyclones',
name: 'Cyclone advisories',
icon: '◉',
source: SOURCE,
source: 'NOAA NHC / CPHC',
updateInterval: 300_000,
init(nextViewer) {
viewer = nextViewer;
@@ -375,28 +361,13 @@ export function createCyclonesLayer({
snapshot && !snapshot.unavailable && snapshot.storms.length === 0;
const geometry =
storm &&
(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.',
)
: '';
(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'));
const status =
errorText(error) ||
(snapshot?.stale
@@ -417,21 +388,14 @@ export function createCyclonesLayer({
: '';
const intensity = storm ? intensityText(storm) : '';
const detail = storm
? 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),
})
? 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 tropical cyclone warnings')
? t('No active NHC/CPHC systems')
: stormCount
? activeStorms
: loading
@@ -440,8 +404,8 @@ export function createCyclonesLayer({
const controls = {
readout: true,
summary: {
label: t('Cyclones · NHC / CPHC · JTWC'),
coverage: t('All tropical basins'),
label: t('Cyclones · NHC / CPHC'),
coverage: t('Atlantic · E/C Pacific'),
compact: stormCount
? storm
? t('{storms} · {name} selected', {
@@ -454,9 +418,7 @@ export function createCyclonesLayer({
? [
{
id: 'advisory',
label: isJtwc(storm)
? t('JTWC warning ↗')
: t('Official advisory ↗'),
label: t('Official advisory ↗'),
href: storm.advisoryUrl,
},
]
@@ -474,7 +436,6 @@ export function createCyclonesLayer({
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
{ id: 'note', text: note, muted: true },
].filter((line) => line.text)
: [],
detail,
@@ -482,7 +443,7 @@ export function createCyclonesLayer({
units: 'kt',
},
list: {
ariaLabel: t('Active cyclone advisories and warnings'),
ariaLabel: t('Active NHC and CPHC cyclone advisories'),
items: (snapshot?.storms || []).map((item, index) => ({
id: item.id,
ordinal: index + 1,
@@ -500,19 +461,17 @@ export function createCyclonesLayer({
label: t('Advisory center / forecast track'),
color: '#7fe6ed',
},
isJtwc(storm)
? { label: t(DANGER_AREA), color: '#ffb15c44' }
: {
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
{
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
]
: [],
info: storm
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}${note ? '\n' + note : ''}\n${coverageText(snapshot.coverage)}`
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\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 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.',
'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.',
),
};
return controls;
@@ -559,7 +518,7 @@ export function createCyclonesLayer({
loading,
error,
stale: Boolean(snapshot?.stale),
source: storm ? sourceOf(storm) : SOURCE,
source: 'NOAA NHC / CPHC',
advisoryAt: storm?.issuedAt || null,
empty: Boolean(
snapshot && !snapshot.unavailable && !snapshot.storms.length,
+3 -66
View File
@@ -861,7 +861,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
const controls = h.layer.getRowControls();
assert.equal(controls.readout, true);
assert.deepEqual(controls.chips, []);
assert.equal(controls.summary.coverage, 'All tropical basins');
assert.equal(controls.summary.coverage, 'Atlantic · E/C Pacific');
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, /cyclone advisories and warnings/);
assert.match(controls.list.ariaLabel, /NHC/);
assert.equal(controls.list.items.length, 2);
assert.equal(controls.list.items[0].active, true);
assert.match(controls.info, /awaiting advisory 10/);
@@ -912,10 +912,7 @@ 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 tropical cyclone warnings/,
);
assert.match(h.layer.getRowControls().summary.detail, /No active NHC\/CPHC/);
next = { ...snapshot(), stale: true };
await h.layer.update();
assert.match(h.layer.getRowControls().summary.status, /stale/);
@@ -990,63 +987,3 @@ 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 -35
View File
@@ -3,7 +3,6 @@ import {
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
import { t } from '../../i18n/index.js';
/**
* @module cyclones/labels
@@ -20,8 +19,6 @@ 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. */
@@ -115,32 +112,7 @@ function cycloneLeadEntry(stormId, point) {
}
/**
* 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.
* Storm cards for every storm and lead-hour labels for the selected one.
* @param {Array<object>} storms Renderer anchors with `forecasts`.
* @param {?string} selectedId
* @returns {Array<object>}
@@ -153,17 +125,13 @@ 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, lead-hour or area label id, else null. */
/** Storm id behind a published card or lead-hour label id, else null. */
export function cycloneStormIdFromEntryId(entryId) {
const match = /^(?:storm|lead|area):([^:]+)(?::|$)/.exec(
String(entryId ?? ''),
);
const match = /^(?:storm|lead):([^:]+)(?::|$)/.exec(String(entryId ?? ''));
return match ? match[1] : null;
}
-4
View File
@@ -198,7 +198,3 @@ 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');
});
+34 -94
View File
@@ -3,7 +3,6 @@ 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,
@@ -25,29 +24,6 @@ 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);
@@ -88,14 +64,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
const emptyCounts = () => ({
storms: 0,
tracks: 0,
cones: 0,
dangerAreas: 0,
forecastPoints: 0,
});
let counts = emptyCounts();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
let itemCount = 0;
function centerItem(storm) {
@@ -135,7 +104,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = emptyCounts();
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
@@ -161,7 +130,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
windKt: storm.windKt,
position: center,
forecasts: [],
dangerArea: null,
};
nextLabels.push(label);
nextCounts.storms++;
@@ -183,66 +151,38 @@ export function createCycloneRendering({ viewer, overlayHost }) {
});
nextCounts.tracks++;
});
// 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,
);
}
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),
},
});
});
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
@@ -312,7 +252,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = emptyCounts();
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
},
destroy() {
if (destroyed) return;
-49
View File
@@ -210,7 +210,6 @@ 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,
@@ -376,7 +375,6 @@ 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,
@@ -453,50 +451,3 @@ 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();
});
+17 -42
View File
@@ -45,33 +45,22 @@ const position = (value) => {
};
};
/** 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) {
function officialLink(value, outlook = false) {
if (value === null) return null;
const url = new URL(text(value, 256));
if (url.origin !== rules.origin || url.username || url.password || url.hash)
if (
url.origin !== 'https://www.nhc.noaa.gov' ||
url.username ||
url.password ||
url.hash
)
throw malformed();
if (
outlook
? !rules.outlook.test(url.pathname + url.search)
: url.search || !rules.advisory.test(url.pathname)
? !/^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/.test(
url.pathname + url.search,
)
: url.search || !/^\/text\/[A-Z0-9]+\.shtml$/.test(url.pathname)
)
throw malformed();
return url.href;
@@ -133,14 +122,8 @@ 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 (
!rules ||
!rules.id.test(raw?.id) ||
!/^(?:al|ep|cp)\d{6}$/.test(raw?.id) ||
seen.has(raw.id) ||
!['current', 'pending', 'unavailable'].includes(raw.geometryStatus)
)
@@ -175,27 +158,20 @@ export function validateCycloneSnapshot(value) {
};
});
const track = geometry(raw.track, 'track', 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();
cone = geometry(raw.cone, 'cone', budget);
if (
raw.geometryStatus !== 'current' &&
(track || area || forecastPoints.length)
(track || cone || forecastPoints.length)
)
throw malformed();
if (
raw.geometryStatus === 'current' &&
(!track || !area || !forecastPoints.length)
(!track || !cone || !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,
@@ -209,14 +185,13 @@ export function validateCycloneSnapshot(value) {
directionDegrees: number(raw.movement?.directionDegrees, 0, 360),
speedKt: number(raw.movement?.speedKt, 0, 200),
},
advisoryUrl: officialLink(raw.advisoryUrl, rules),
outlookUrl: officialLink(raw.outlookUrl, rules, true),
advisoryUrl: officialLink(raw.advisoryUrl),
outlookUrl: officialLink(raw.outlookUrl, true),
geometryStatus: raw.geometryStatus,
geometryAdvisoryNumber,
forecastPoints,
track,
cone,
dangerArea,
};
});
if (value.unavailable && storms.length) throw malformed();
-66
View File
@@ -230,69 +230,3 @@ 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',
);
});
+1 -2
View File
@@ -21,12 +21,11 @@ const PIN_TURN_DEG = 0.1;
* the grounded floor: a floor-pinned row holds a CPU position, so it is not
* planned, and settling a grounded contact puts it straight onto the floor.
*/
export function createIcons({ flightState, services, parts, resolveAsset }) {
export function createIcons({ flightState, services, parts }) {
const icons = createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'flights',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+1 -9
View File
@@ -948,12 +948,7 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
return parts.icons._fleetLook(flightState._trackedIcao);
}
/**
@@ -1135,9 +1130,6 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up.
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+15 -34
View File
@@ -1,9 +1,5 @@
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
aircraftViewRef,
registerAircraftViews,
} from '../../data/aircraftViews.js';
import { rotorFrame } from '../../data/rotorFrames.js';
import { KNOT_MPS } from '../../data/units.js';
import {
@@ -17,7 +13,6 @@ import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
@@ -153,9 +148,6 @@ export function createLocalAdsbLayer({
* @type {{markers: object, rings: object}|null}
*/
let sets = null;
/** Whether the renderer draws markers from the aircraft view sheet
* (`aircraftViews.js`), set at `init`. */
let views = false;
let enabled = false;
let unsubscribe = null;
let unsubscribeFeeds = null;
@@ -363,36 +355,31 @@ export function createLocalAdsbLayer({
/**
* A marker's icon, where and how it now draws: a helicopter's rotor frame
* at `at` (still on the ground), an airport vehicle in its own tint, a
* ground station's mast upright. On a renderer that draws view sheets, a
* kind with rendered views is drawn from the sheet along its course;
* every other marker is its flat glyph turned on screen.
* ground station's mast upright.
*/
function markerItem(marker, basis, at) {
const kind = marker.iconKind ?? 'airliner';
const frame =
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined;
const view = views ? aircraftViewRef(kind, frame) : null;
return {
id: marker.id,
pos: marker.position,
image: view ?? aircraftIcon(kind, undefined, frame),
image: aircraftIcon(
kind,
undefined,
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined,
),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color: kind === 'vehicle' ? vehicleColor : color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
...(view
? { rotationMode: 'course', course: marker.courseDeg ?? 0 }
: {
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
}),
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -786,11 +773,6 @@ export function createLocalAdsbLayer({
init(nextViewer) {
viewer = nextViewer;
const draw = drawOf(viewer);
views = registerAircraftViews(
draw,
rendererOf(viewer)?.capabilities ?? null,
resolveAsset,
);
const prefix = `${LAYER_ID}:${++instances}`;
sets = {
markers: draw.icons({
@@ -890,7 +872,6 @@ export function createLocalAdsbLayer({
models = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
views = false;
viewer = null;
void receiver.destroy?.();
},
-58
View File
@@ -223,7 +223,6 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
feeds,
services: { ...services, ...options.services },
now: () => clock.now,
...(options.resolveAsset ? { resolveAsset: options.resolveAsset } : {}),
});
layer.init(viewer);
await layer.enable();
@@ -320,63 +319,6 @@ test('local aircraft use their class silhouette at one size in magenta', async (
assert.equal(detectable.type, 'AIR');
});
test('on a renderer that draws view sheets, local aircraft draw their view along their track; vehicles and masts stay flat', async (t) => {
const { aircraftViewRef } = await import('../../data/aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
const viewer = { scene: {} };
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, {
camera: camera.port,
query: { drillPick: () => [] },
capabilities: new Set(['viewSheets']),
});
fakeInput(viewer);
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { draw, viewer },
resolveAsset: (url) => `/gev${url}`,
});
t.after(() => layer.destroy());
// Registered once, at the layer's own asset URL.
assert.deepEqual(draw.viewSheets, [
[
AIRCRAFT_VIEWS.id,
{ ...AIRCRAFT_VIEWS.sheet, image: '/gev/sprites/aircraft-views.webp' },
],
]);
receiver.set({
aircraft: [
record({ trackDeg: 0 }),
record({ icao: 'a0b702', category: 'A7' }),
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
],
});
await layer.update();
const icon = iconOf(draw, 'local-adsb:abc123');
assert.equal(icon.image, aircraftViewRef('airliner'));
assert.equal(icon.rotationMode, 'course');
assert.equal(icon.course, 0);
assert.equal('rotation' in icon, false);
assert.deepEqual(icon.size, [20, 20]);
assert.deepEqual(icon.color, MAGENTA);
assert.equal(
iconOf(draw, 'local-adsb:a0b702').image,
aircraftViewRef('helicopter', rotorFrame('local-adsb:a0b702', clock.now)),
'the rotor turns through the sheet',
);
const vehicle = iconOf(draw, 'local-adsb:a0c001');
assert.equal(vehicle.image, aircraftIcon('vehicle'));
assert.equal(vehicle.rotationMode, 'screen');
const mast = iconOf(draw, 'local-adsb:a0c003');
assert.equal(mast.image, aircraftIcon('station'));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
+1 -2
View File
@@ -8,12 +8,11 @@ import {
} from './policy.js';
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
export function createIcons({ flightState, services, parts, resolveAsset }) {
export function createIcons({ flightState, services, parts }) {
return createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'military',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+1 -9
View File
@@ -396,12 +396,7 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
return parts.icons._fleetLook(flightState._trackedIcao);
}
/**
@@ -1092,9 +1087,6 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up (ready + shown).
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+3 -51
View File
@@ -21,11 +21,6 @@ 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;
@@ -75,14 +70,7 @@ function fakeFollowCamera() {
camera.flightsCancelled += 1;
},
flyTo() {},
pose: () => ({
lon: 0,
lat: 0,
height: 2e7,
heading: 0,
pitch: -1.57,
position: { x: 2.6378e7, y: 0, z: 0 },
}),
pose: () => ({ lon: 0, lat: 0, height: 2e7, heading: 0, pitch: -1.57 }),
on(event, cb) {
if (event !== 'followChanged') return () => {};
listeners.add(cb);
@@ -147,13 +135,7 @@ const SENSORS = indexImagingSensors({
],
});
/**
* @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 } = {}) {
async function fixture(t) {
const source = {
async readGroup(group) {
const text = GROUP_TEXT[group] || '';
@@ -183,9 +165,6 @@ async function fixture(t, { realFocus = false } = {}) {
getFocusTarget: () => null,
focusNowMs: (now) => now,
focusPassIsNeeded: () => false,
...(realFocus
? { clearFocusTarget, getFocusTarget, publishFocusTargetAt }
: {}),
},
context: {
clearTrackedSubjectContext: noop,
@@ -224,12 +203,7 @@ async function fixture(t, { realFocus = false } = {}) {
const viewer = { canvas: new EventTarget(), scene: {} };
const camera = fakeFollowCamera();
const frame = fakeFrame();
const query = { project: () => ({ x: 720, y: 450 }) };
const { draw, unbind } = bindFakeDraw(viewer, {
camera,
frame,
...(realFocus ? { query } : {}),
});
const { draw, unbind } = bindFakeDraw(viewer, { camera, frame });
const input = fakeInput(viewer);
let frameNumber = 1;
const { log, warn } = console;
@@ -247,7 +221,6 @@ async function fixture(t, { realFocus = false } = {}) {
console.log = log;
input.destroy();
unbind();
if (realFocus) clearFocusTarget();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
@@ -439,27 +412,6 @@ 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);
+8 -11
View File
@@ -90,18 +90,18 @@ export function createTracking({ state: layerState, services, parts, source }) {
return;
}
const clearedNorad = layerState._trackedNorad;
clearFocusTarget('satellites', clearedNorad);
clearFocusTarget('satellites', layerState._trackedNorad);
// 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(
clearedNorad,
layerState._trackedNorad,
parts.controls._pointStyleFor(
clearedNorad,
layerState._catalog.get(clearedNorad)?.group,
layerState._trackedNorad,
layerState._catalog.get(layerState._trackedNorad)?.group,
),
// Back to its class's visibility: a hidden class stays hidden.
parts.controls._classVisible(clearedNorad),
parts.controls._classVisible(layerState._trackedNorad),
);
// Invalidate the per-frame tracked-position cache (WS-D2)
@@ -109,13 +109,9 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedFrameGeo = null;
// Remove the tracked dot and orbit path (unless ISS — keep its path)
if (clearedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(clearedNorad);
if (layerState._trackedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(layerState._trackedNorad);
}
// 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;
@@ -123,6 +119,7 @@ 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?.();
+2
View File
@@ -50,6 +50,8 @@ export function createFlow({ state: layerState, services, parts, source }) {
if (code === 'RATE_LIMITED') return msg('Traffic rate limit reached');
if (status === 503 && code && code !== 'no_key')
return msg('Traffic service unavailable');
// TomTom refused the key on both of its flow endpoints.
if (code === 'key_rejected') return msg('TomTom key rejected');
if (status === 503) return msg('TomTom key unavailable');
if (status === 429) return msg('TomTom daily budget reached');
if (status === 502 || status === 504)
+45 -4
View File
@@ -15,6 +15,15 @@ import { VectorTile } from '@mapbox/vector-tile';
* ratio (1 = free flow). Features with a missing/non-finite `traffic_level`
* are skipped unless `road_closure` is true (closures decode with level 0).
*
* The proxy serves tiles from either TomTom flow endpoint, and they name
* things differently. TomTom Maps (`traffic/map/4`, style `relative`):
* `traffic_level`, `road_type` ("Motorway", "Major road", …) and
* `traffic_road_coverage` (`full` when one line carries both directions).
* TomTom Orbis Maps (`maps/orbis/traffic`, apiVersion 2): `relative_speed`
* (the same ratio), `road_category` (OpenStreetMap-style, with `_link`
* ramps) and one line per travel direction. Orbis features are decoded into
* the TomTom Maps vocabulary, so nothing downstream tells them apart.
*
* Deps: `pbf@5` (PbfReader) + `@mapbox/vector-tile@3` — both tiny and
* tree-shakeable; decoding happens client-side so the proxy stays a dumb
* binary cache.
@@ -23,6 +32,35 @@ import { VectorTile } from '@mapbox/vector-tile';
*/
const FLOW_LAYER_NAME = 'Traffic flow';
/**
* Orbis `road_category` → the TomTom Maps `road_type` and `road_category`
* the traffic layer classifies roads by. A ramp takes its road's class;
* service roads and tracks stay unmapped, as TomTom Maps tiles left
* parking and private roads out of the drivable set.
*/
const ORBIS_ROAD_CATEGORIES = Object.freeze({
motorway: ['Motorway', 'motorway'],
trunk: ['International road', 'trunk'],
primary: ['Major road', 'primary'],
secondary: ['Secondary road', 'secondary'],
tertiary: ['Connecting road', 'tertiary'],
street: ['Local road', 'street'],
});
/** Road class of a feature, in TomTom Maps terms, from either schema. */
function roadClassOf(props) {
if (typeof props.road_type === 'string')
return [props.road_type, props.road_category ?? null];
const category =
typeof props.road_category === 'string'
? props.road_category.replace(/_link$/, '')
: null;
if (category && Object.hasOwn(ORBIS_ROAD_CATEGORIES, category))
return ORBIS_ROAD_CATEGORIES[category];
// Kept as sent, so the drivable filter drops it by category.
return ['', props.road_category ?? null];
}
/** Decode flow geometry; strict mode distinguishes damaged tiles from valid empty coverage. */
export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
let layer;
@@ -49,13 +87,15 @@ export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
const props = feature.properties || {};
const closure =
props.road_closure === true || props.road_closure === 'true';
const rawLevel = props.traffic_level;
const orbis =
props.traffic_level === undefined && props.road_type === undefined;
const rawLevel = orbis ? props.relative_speed : props.traffic_level;
const hasLevel = typeof rawLevel === 'number' && Number.isFinite(rawLevel);
// Skip features we can't color — unless closed (closures render dot-free
// regardless of level, so they stay useful without one).
if (!hasLevel && !closure) continue;
const trafficLevel = hasLevel ? Math.min(1, Math.max(0, rawLevel)) : 0;
const roadType = typeof props.road_type === 'string' ? props.road_type : '';
const [roadType, roadCategory] = roadClassOf(props);
const lines =
geometry.type === 'LineString'
@@ -69,10 +109,11 @@ export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
coords,
trafficLevel,
roadType,
roadCategory: props.road_category ?? null,
roadCategory,
roadSubcategory: props.road_subcategory ?? null,
closure,
coverage: props.traffic_road_coverage ?? null,
// Orbis draws each travel direction as its own line.
coverage: props.traffic_road_coverage ?? (orbis ? 'one_side' : null),
leftHandTraffic:
props.left_hand_traffic === true ||
props.left_hand_traffic === 'true',
+136
View File
@@ -0,0 +1,136 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import { decodeFlowTile } from './flowDecode.js';
import { flowSegmentsToRoads, isDrivableFlowSegment } from './roadModes.js';
/**
* One "Traffic flow" layer; each feature is a two-point line carrying the
* given properties (string, number or boolean values).
*/
function flowTile(features) {
const keys = [];
const values = [];
const tags = features.map((props) =>
Object.entries(props).flatMap(([key, value]) => {
if (!keys.includes(key)) keys.push(key);
values.push(value);
return [keys.indexOf(key), values.length - 1];
}),
);
const writer = new PbfWriter();
writer.writeMessage(
3,
(_, layer) => {
layer.writeVarintField(15, 2);
layer.writeStringField(1, 'Traffic flow');
layer.writeVarintField(5, 4096);
for (const key of keys) layer.writeStringField(3, key);
for (const value of values)
layer.writeMessage(
4,
(_, out) => {
if (typeof value === 'string') out.writeStringField(1, value);
else if (typeof value === 'boolean')
out.writeBooleanField(7, value);
else out.writeDoubleField(3, value);
},
null,
);
tags.forEach((featureTags, i) =>
layer.writeMessage(
2,
(_, feature) => {
feature.writeVarintField(3, 2);
feature.writePackedVarint(2, featureTags);
// MoveTo (100, 100 + i), LineTo +200 east.
feature.writePackedVarint(4, [9, 200, 200 + 2 * i, 10, 400, 0]);
},
null,
),
);
},
null,
);
return writer.finish();
}
const decode = (features) => decodeFlowTile(flowTile(features), 12, 935, 1686);
test('TomTom Maps flow features decode as before', () => {
const [segment] = decode([
{
traffic_level: 0.6,
road_type: 'Major road',
road_category: 'primary',
traffic_road_coverage: 'full',
},
]);
assert.equal(segment.trafficLevel, 0.6);
assert.equal(segment.roadType, 'Major road');
assert.equal(segment.roadCategory, 'primary');
assert.equal(segment.coverage, 'full');
// A TomTom Maps line with no coverage tag still reports none.
assert.equal(
decode([{ traffic_level: 1, road_type: 'Motorway' }])[0].coverage,
null,
);
});
test('Orbis flow features decode into the TomTom Maps road vocabulary', () => {
const segments = decode([
{ relative_speed: 0.42, road_category: 'motorway' },
{ relative_speed: 0.9, road_category: 'trunk_link' },
{
relative_speed: 0.7,
road_category: 'street',
road_subcategory: 'residential',
left_hand_traffic: true,
},
{ relative_speed: 1.4, road_category: 'tertiary' },
{ road_category: 'secondary', road_closure: true },
]);
assert.deepEqual(
segments.map((s) => [s.roadType, s.roadCategory, s.trafficLevel]),
[
['Motorway', 'motorway', 0.42],
['International road', 'trunk', 0.9],
['Local road', 'street', 0.7],
['Connecting road', 'tertiary', 1], // clamped like traffic_level
['Secondary road', 'secondary', 0], // closures need no speed
],
);
assert.equal(segments[2].roadSubcategory, 'residential');
assert.equal(segments[2].leftHandTraffic, true);
assert.equal(segments[4].closure, true);
// Orbis draws one line per travel direction.
assert.ok(segments.every((s) => s.coverage === 'one_side'));
assert.ok(segments.every(isDrivableFlowSegment));
assert.deepEqual(
flowSegmentsToRoads(segments).map((road) => [road.type, road.oneway]),
[
['motorway', 1],
['trunk', 1],
['residential', 1],
['tertiary', 1],
['secondary', 1],
],
);
});
test('Orbis service roads, tracks and speedless lines never become traffic', () => {
const segments = decode([
{ relative_speed: 0.5, road_category: 'service' },
{ relative_speed: 0.5, road_category: 'track' },
{ relative_speed: 0.5 },
{ road_category: 'primary' }, // no speed and not closed: nothing to draw
]);
assert.deepEqual(
segments.map((s) => [s.roadType, s.roadCategory]),
[
['', 'service'],
['', 'track'],
['', null],
],
);
assert.equal(segments.filter(isDrivableFlowSegment).length, 0);
});
+2 -72
View File
@@ -3,8 +3,6 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createVesselLayer } from './index.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { VESSEL_VIEWS } from '../../data/viewSheet.js';
// Following the world clock on a renderer that moves icons along motion
// segments on its own clock, each vessel's icon is drawn along its track
@@ -12,7 +10,7 @@ import { VESSEL_VIEWS } from '../../data/viewSheet.js';
const noop = () => {};
function setup(t, { capabilities = new Set(['motionSegments']), fleet } = {}) {
function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
@@ -37,7 +35,6 @@ function setup(t, { capabilities = new Set(['motionSegments']), fleet } = {}) {
clearOverlaySource: noop,
},
geoid: {},
...(fleet ? { fleet } : null),
sprites: {},
focus: {
focusNowMs: () => 0,
@@ -71,7 +68,7 @@ function setup(t, { capabilities = new Set(['motionSegments']), fleet } = {}) {
[...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
);
return { layer, viewer, icons, draw };
return { layer, viewer, icons };
}
const T = 1_000_000;
@@ -285,70 +282,3 @@ test('going live, a vessel a live update has drawn since stays where that drew i
assert.deepEqual(icons().items.get(id).pos, visual.position);
}
});
test('on a renderer that draws view sheets a vessel is a view of its hull, an aid still its buoy', (t) => {
const { layer, viewer, icons, draw } = setup(t, {
capabilities: new Set(['motionSegments', 'viewSheets']),
fleet: { resolveAsset: (url) => `/gev${url}` },
});
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
{ ...row(minuteFixes), mmsi: '222', type: '36' },
{ ...row(minuteFixes), mmsi: '333', type: '50' },
{ ...row(minuteFixes), mmsi: '993672001', type: 'Port Hand Mark' },
]);
// The sheet, once, at the layer's asset URL.
assert.deepEqual(draw.viewSheets, [
[
VESSEL_VIEWS.id,
{ ...VESSEL_VIEWS.sheet, image: '/gev/sprites/vessel-views.webp' },
],
]);
const set = icons();
const cargo = set.items.get('111');
assert.deepEqual(cargo.image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.cargo,
fallback: vesselSprite('cargo'),
});
assert.equal(cargo.rotationMode, 'course', 'a view lies along its course');
assert.equal(cargo.imageLod, undefined);
assert.equal(set.items.get('222').image.first, VESSEL_VIEWS.subjects.sailing);
// A pilot boat: its own hull from the sheet, a service boat's flat hull.
assert.deepEqual(set.items.get('333').image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
const buoy = set.items.get('993672001');
assert.equal(buoy.image, aidSprite());
assert.equal(buoy.rotationMode, 'screen');
});
test('without view sheets a vessel keeps its flat hull', (t) => {
const { layer, viewer, icons, draw } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
]);
assert.deepEqual(draw.viewSheets, []);
assert.equal(icons().items.get('111').image, vesselSprite('cargo'));
});
test('a vessel is drawn larger near than far, under an aircraft at every range, and recedes toward the horizon', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
// The fastest step of a vessel's own scale.
{ ...row(minuteFixes), type: 'Cargo', speed: 20 },
]);
const set = icons();
assert.deepEqual(set.spec.recede, {}, "the renderer's own recession");
const item = set.items.get('111');
const curve = item.scaleByDistance;
const px = (value) => item.size[0] * item.scale * value;
assert.ok(px(curve.nearValue) > px(1), 'larger up close than it was');
// An aircraft icon: 20 px, three times that near and half of it far, over
// the same range (aircraftIconLayer.js).
assert.deepEqual([curve.near, curve.far], [1000, 8000000]);
assert.ok(px(curve.nearValue) < 20 * 3);
assert.ok(px(curve.farValue) < 20 * 0.5);
});
+12 -56
View File
@@ -44,13 +44,8 @@ import {
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { vesselPartState } from '../../data/modelPartDrivers.js';
import {
isAidToNavigation,
vesselKind,
vesselShape,
} from '../../data/vesselTypes.js';
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { registerVesselViews, vesselViewRef } from '../../data/vesselViews.js';
import { cssColor } from '../../render/color.js';
import { KNOT_MPS } from '../../data/units.js';
@@ -66,19 +61,6 @@ const HIDDEN_FOLLOW_MS = 250;
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
const SHIP_ICON_PX = 32;
/**
* How a vessel or aid sprite's size follows its range from the eye, on the
* aircraft icons' range (`aircraftIconLayer.js`): half as large again up
* close, where a hull's shape reads; as it was drawn before at some
* 1,000 km; and a third from 8,000 km out. Under an aircraft's icon at every
* range, so a world of ships is a field of small marks.
*/
const SHIP_SCALE_BY_DISTANCE = Object.freeze({
near: 1000,
nearValue: 1.5,
far: 8000000,
farValue: 0.35,
});
let instances = 0;
@@ -246,7 +228,6 @@ export function createRendering({
advanceSpriteFocus,
focusAlphaNeedsWrite,
spriteFocusAtRest,
nearFarScalarValueAtDistance,
} = services.focus;
const {
holdContinuousRender,
@@ -284,22 +265,12 @@ export function createRendering({
const capabilities = rendererOf(viewer)?.capabilities ?? null;
iconMotion = capabilities?.has('motionSegments') === true;
segmentsWere = segmentsOn();
// On a renderer that draws view sheets a vessel is the view of its
// hull from where the eye is, not the flat hull.
iconViews = registerVesselViews(
drawOf(viewer),
capabilities,
services.fleet?.resolveAsset,
);
const set = drawOf(viewer).icons({
id: `ais-vessels:${++instances}`,
// Translucent, as its billboards were: overlapping chevrons keep
// their outlines rather than the first one's fill.
blend: 'translucent',
horizonCull: true,
// Toward the horizon a vessel shrinks and fades, as an aircraft does
// (the renderer's defaults, which are the aircraft sets').
recede: {},
drawOrder: spriteDrawOrder?.('ais') ?? 0,
...(iconMotion ? { motionClock: motionClock(segmentsWere) } : null),
});
@@ -315,8 +286,6 @@ export function createRendering({
// segments on its own clock.
let iconSet = null;
let iconMotion = false;
// Whether a vessel's icon is drawn from the vessel view sheet.
let iconViews = false;
// Whether the icons last moved on the renderer's clock.
let segmentsWere = false;
// The record drawn under each icon id, for replanning an id.
@@ -412,7 +381,6 @@ export function createRendering({
state.icons?.dispose();
state.icons = null;
iconSet = null;
iconViews = false;
iconRecords.clear();
planFrom.clear();
replannedAtMs = -Infinity;
@@ -462,7 +430,6 @@ export function createRendering({
// Tinted by type; selection changes neither the colour nor the size.
color: shipTint(record),
scale: shipScale(record),
scaleByDistance: SHIP_SCALE_BY_DISTANCE,
// An aid's buoy stands upright on screen; a vessel turns with course.
rotationMode: aid ? 'screen' : 'course',
rotation: 0,
@@ -562,22 +529,18 @@ export function createRendering({
}
/**
* The sprite a vessel is drawn as: on a renderer that draws view sheets,
* the view of its kind's hull (`vesselKind`) from where the eye is
* (`vesselViews.js`), with the flat hull to fall back on; else the flat
* white hull, bow up so the row's course turns it to its heading. An aid
* to navigation is the buoy either way. The layer tints it (`shipTint`).
* The sprite a vessel is drawn as: the white hull of its kind
* (`vesselKind`), bow up so the row's course turns it to its heading, or
* for an aid to navigation the buoy. The layer tints it
* (`shipTint`), so each shape takes one icon-atlas slot.
* @param {Object} record - Vessel record.
* @returns {string|{views: string, first: number, fallback: string}} SVG
* data URL, or a view of the vessel sheet.
* @returns {string} SVG data URL.
*/
function shipIcon(record) {
if (isAidToNavigation(record)) return aidSprite();
const kind = vesselKind(record.type);
return iconViews
? vesselViewRef(vesselShape(record.type), kind)
: vesselSprite(kind);
return isAidToNavigation(record)
? aidSprite()
: vesselSprite(vesselKind(record.type));
}
/**
@@ -1345,25 +1308,18 @@ export function createRendering({
!focusAlphaNeedsWrite(icons.focus(id), 1, params)
)
continue;
const cameraDistance = cameraDistanceFor(position);
// The sprite's half size as drawn at that range.
const half =
(item.scale ?? 1) *
(nearFarScalarValueAtDistance?.(item.scaleByDistance, cameraDistance) ??
1) *
0.5;
const focus = advanceSpriteFocus(sprite, {
// Hidden/far-side icons still finish any pending release so the active
// count remains truthful and they cannot reappear with stale dim alpha.
screenPosition: visual.visible ? screenPositionFor(position) : null,
cameraDistance,
cameraDistance: cameraDistanceFor(position),
nowMs,
target,
params,
// Vessel artwork is 32 px before scale. Including the ambient
// chevron's own rendered extent prevents edge-overlap misses.
spriteHalfWidthPx: item.size[0] * half,
spriteHalfHeightPx: item.size[1] * half,
spriteHalfWidthPx: item.size[0] * (item.scale ?? 1) * 0.5,
spriteHalfHeightPx: item.size[1] * (item.scale ?? 1) * 0.5,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
-56
View File
@@ -86,62 +86,6 @@ 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>,
+1 -142
View File
@@ -19,7 +19,7 @@ import {
headlessCamera,
withVirtualClock,
} from './cameraGoldens.js';
import { createCesiumCamera, createPointsVisibility } from './camera.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { bindRenderer, cameraOf } from '../rendererOf.js';
@@ -337,147 +337,6 @@ 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,8 +321,6 @@ 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']);
+74 -712
View File
File diff suppressed because it is too large. Load diff
-36
View File
@@ -8873,39 +8873,3 @@ test('a disposed set, and every set once the port is disposed, does nothing on l
restore();
}
});
test('a draw port registers view sheets only with viewSheets, each port its own', async () => {
const { PORTS } = await import('../contract/index.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
assert.equal(PORTS.draw.views, 'viewSheets', 'an optional port method');
const report = (error) => assert.fail(error);
const without = createCesiumDraw({
scene: fakeScene(),
report,
capabilities: new Set(['motionSegments']),
});
assert.equal(typeof without.port.views, 'undefined');
// Two viewers: a sheet registered on one is not drawn by the other.
const one = createCesiumDraw({ scene: fakeScene(), report });
const two = createCesiumDraw({ scene: fakeScene(), report });
assert.equal(typeof one.port.views, 'function');
const view = {
id: 'a',
pos: { ...Cesium.Cartesian3.fromDegrees(4, 52, 1000) },
image: { views: AIRCRAFT_VIEWS.id, first: AIRCRAFT_VIEWS.subjects.uav },
size: [20, 20],
rotationMode: 'course',
course: 0,
};
const setOne = one.port.icons({ id: 'views:one' });
const setTwo = two.port.icons({ id: 'views:two' });
setOne.set([view]);
setTwo.set([view]);
one.port.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const rowsOne = one.sets.get('views:one').gpu.set;
const rowsTwo = two.sets.get('views:two').gpu.set;
assert.equal(rowsOne.imageFar(rowsOne.row('a')), AIRCRAFT_VIEWS.subjects.uav);
assert.equal(rowsTwo.imageFar(rowsTwo.row('a')), -1, 'not on this port');
setOne.dispose();
setTwo.dispose();
});
-416
View File
@@ -1,416 +0,0 @@
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;
}
});
-375
View File
@@ -1,375 +0,0 @@
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);
});
+13 -122
View File
@@ -31,14 +31,6 @@
* root's larger `width`/`height`, as a billboard rasterises it), any other
* image at the item's larger side.
*
* A view (`{views, first}`, `viewSheets`) is not in that atlas: its sheet is
* a texture of its own, and its row draws the frame that shows its subject
* from the eye (`data/viewSheet.js`), lying flat on the ground along its
* course. Until the sheet is registered and loaded, and if it cannot load,
* the row draws the view's `fallback` image along its course (nothing
* without one). A set draws views from one sheet; a view of another is
* refused.
*
* Choices the contract leaves open, taken conservatively:
* - `horizonCull` judges each row no lower than `ICON_CULL_HEIGHT_M` above
* the ellipsoid, as the layers drawing their own icon sets do for sea
@@ -61,7 +53,6 @@ import {
ICON_GROUND_RELATIVE,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import {
writeArcSegment,
@@ -86,26 +77,6 @@ export const GPU_ICON_CAPABILITIES = Object.freeze([
'courseGlide',
]);
/**
* The capabilities GPU icon sets bring on `scene`: `viewSheets` too, but on
* WebGL 1, where a set that draws views could not also draw what its rows
* read from their extras (a display range, a fade, an offset), and a layer
* that uses those would lose its icons to the sheet.
* @param {object} [scene] A Cesium scene; none (a test's) is taken as WebGL 2.
*/
export function gpuIconCapabilities(scene) {
return scene?.context?.webgl2 === false
? [...GPU_ICON_CAPABILITIES]
: [...GPU_ICON_CAPABILITIES, 'viewSheets'];
}
/** Whether an image is a subject of a view sheet (`{views, first}`). */
const isView = (image) => typeof image?.views === 'string';
/** Whether a subject's block of frames, from its first cell, is in `layout`. */
const blockFits = (first, layout) =>
first + layout.frames <= layout.columns * layout.rows;
const nonZero = (v) =>
Boolean(v) && (v.x !== 0 || v.y !== 0 || (v.z ?? 0) !== 0);
@@ -233,12 +204,10 @@ function rasterPxOf(url, item) {
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* viewsOf?: (id: string) => ({image: string, layout: object}|undefined),
* requestRender: (reason: string) => void}} options `date` is the epoch
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it;
* `viewsOf` reads a registered view sheet (undefined while it is not).
* noting that the set draws from it; `peekImage` only reads it.
*/
export function createGpuIcons({
scene,
@@ -247,15 +216,9 @@ export function createGpuIcons({
toColor,
imageOf,
peekImage,
viewsOf = () => undefined,
requestRender,
}) {
const can = (capability) => capabilities.has(capability);
/** Whether a view's frames are in its sheet (true while not registered). */
const viewFits = (view) => {
const sheet = viewsOf(view.views);
return !sheet || blockFits(view.first, sheet.layout);
};
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
function wants(items, spec = {}) {
@@ -265,10 +228,7 @@ export function createGpuIcons({
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.pickProxy ||
item.imageLod ||
// A view turns along its course: an item that does not is not asked
// for its image here.
(item.rotationMode === 'course' && isView(item.image))
item.imageLod
)
return true;
}
@@ -276,33 +236,13 @@ export function createGpuIcons({
}
/** Refuse what a GPU icon set cannot draw, before anything changes. */
function check(items, spec = {}, record = null) {
function check(items, spec = {}) {
// Atlas slots these items would take anew: they must all fit.
const fresh = new Set();
// The one sheet the set draws views from: its record's, else the first
// of these items'.
let sheet = record?.views ?? null;
for (const item of items) {
const refuse = (what) => {
throw new Error(`the Cesium renderer's GPU icons have no ${what}`);
};
if (isView(item.imageLod?.near)) refuse('views as near images');
if (isView(item.image?.fallback)) refuse('views as fallbacks');
if (isView(item.image)) {
if (!can('viewSheets')) refuse('view sheets');
if (!Number.isInteger(item.image.first) || item.image.first < 0)
throw new TypeError("a view's first cell is a whole number from 0");
if (!viewFits(item.image))
throw new RangeError("a view's frames run past its sheet");
if (item.rotationMode !== 'course')
refuse("views but along a course (rotationMode: 'course')");
if (item.imageLod) refuse('imageLod for a view');
sheet ??= item.image.views;
if (item.image.views !== sheet)
refuse(
`views from two sheets in a set (${sheet}, ${item.image.views})`,
);
}
if (item.offsetScalesByDistance && nonZero(item.pixelOffset))
refuse('pixel offsets scaled by distance');
// What a row reads from its extras texture, which WebGL 1 has not.
@@ -318,12 +258,7 @@ export function createGpuIcons({
if (item.rotationMode === 'screen' && (item.rotation ?? 0) !== 0)
refuse('screen rotation on WebGL 1');
}
for (const given of [
// A view is not in the atlas; the image it falls back to is.
isView(item.image) ? item.image.fallback : item.image,
item.imageLod?.near,
]) {
if (given === undefined) continue;
for (const given of [item.image, item.imageLod?.near]) {
// An atlas slot as what it holds now (none yet draws once it does).
const image =
typeof given?.atlas === 'string' ? peekImage(given) : given;
@@ -381,7 +316,6 @@ export function createGpuIcons({
cull: () => spec.horizonCull === true,
recede: () => spec.recede,
translucent: () => spec.blend === 'translucent',
views: () => (record.views ? (viewsOf(record.views) ?? null) : null),
// Picked as the draw port's other items are: `{set, id, meta}` as
// the item now is, hidden row by row for drill picks.
pickObject: (id, _set, primitive) => ({
@@ -477,34 +411,14 @@ export function createGpuIcons({
const added = row < 0;
if (added) row = set.add(item.id);
const [width = 0, height = 0] = item.size ?? [];
const view = isView(item.image);
if (view) {
// Its subject's first cell, once its sheet is registered, and the
// slot of the image drawn in its place until the sheet has loaded.
// (A subject past the sheet, registered since, draws no cell.)
record.views ??= item.image.views;
const sheet = viewsOf(item.image.views);
const first =
sheet && blockFits(item.image.first, sheet.layout)
? item.image.first
: -1;
const fallback =
item.image.fallback === undefined
? -1
: slotOf(item.image.fallback, item);
set.setImage(row, first, fallback);
set.setImageSwitch(row, 0);
} else {
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
}
set.setFlag(row, ICON_VIEWS, view);
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
set.setSize(row, width, height);
set.setScale(row, item.scale ?? 1);
set.setAlpha(row, item.alpha ?? 1);
@@ -833,21 +747,11 @@ export function createGpuIcons({
reatlas(id) {
const drawing = [];
for (const item of record.items.values())
if (
item.image?.atlas === id ||
item.image?.fallback?.atlas === id ||
item.imageLod?.near?.atlas === id
)
if (item.image?.atlas === id || item.imageLod?.near?.atlas === id)
drawing.push(item);
if (fresh) return sync();
for (const item of drawing) writeRow(item);
},
/** Rewrite the rows drawing views, once their sheet is registered. */
reviews() {
if (fresh) return sync();
for (const item of record.items.values())
if (isView(item.image)) writeRow(item);
},
/**
* After a frame: sample the ground under clamped rows' segment ends,
* from `budget` (`{ends, surface}`, spent). Whether a row's ground
@@ -975,19 +879,6 @@ export function createGpuIcons({
let loading = false;
for (let row = 0; row < set.count; row++) {
if (!set.shown(row)) continue;
if (set.flags(row) & ICON_VIEWS) {
// Its sheet, or while that is not drawn, the image it falls
// back to.
const views = host.viewsState();
if (views === 'ready' && set.imageFar(row) >= 0) continue;
const fallback = set.imageNear(row);
if (fallback < 0) {
if (views === 'failed') return 'failed';
loading = true;
} else if (iconAtlas.failed(fallback)) return 'failed';
else if (!iconAtlas.ready(fallback)) loading = true;
continue;
}
for (const slot of [set.imageFar(row), set.imageNear(row)]) {
if (slot < 0) continue;
if (iconAtlas.failed(slot)) return 'failed';
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more