mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-24 04:02:19 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4ff9b1e07 | ||
|
|
efdac0ba70 |
No files matched your search
+1
-1
@@ -44,7 +44,7 @@ How to read this:
|
||||
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
|
||||
| **Environment and Climate Change Canada** (MSC GeoMet OGC API) | Air quality (AQHI) — Canadian station observations | [ECCC Data Servers End-use Licence](https://eccc-msc.github.io/open-data/licence/readme_en/) (open, attribution required, no endorsement implied) | "Contains information licensed under the Environment and Climate Change Canada Data Servers End-use Licence" |
|
||||
| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) |
|
||||
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts; perimeters are coloured by when they were mapped (`poly_PolygonDateTime`, else the record's last edit `poly_DateCurrent`, which also moves when only the incident's attributes are edited, so such a fire can look newly grown) | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
|
||||
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
|
||||
| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app |
|
||||
| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer, both sections: the last 24 h of reports from many publishers. Set, the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to it and Core reads none of the three sources below. Which providers stand behind its feed is the news server's to state | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. The Data attribution popover states that places, categories, severity and English headlines are derived automatically and can be wrong |
|
||||
| **GDELT 2.0 events and GKG** (`data.gdeltproject.org/gdeltv2/`; no key; used only without a news server) | News layer, Conflicts: the last 24 h of GDELT's 15-minute event exports (`*.export.CSV.zip`, about 100 KB each), read server-side as they appear. Physical violence only (CAMEO roots 18–20); one report per story, copies of one agency story merged; placed at GDELT's location for it (a town the article's words name beats a bare country). Titled by the article's page title from the GKG export of the same quarter hour (`*.gkg.csv.zip`, about 6 MB each) for the newest 3 h, else by the words of the article's address. GDELT's actor coding is never shown. Categories, relevance and severity by bundled rules | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic, commercial and governmental use, with citation and a link to the GDELT Project. Coded events, page titles and article links only; linked articles keep their publishers' terms | "GDELT Project" with a link to gdeltproject.org in the Data attribution popover; "via GDELT Project", the publisher's domain and the article link on every card |
|
||||
|
||||
@@ -443,7 +443,7 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
|
||||
| ✈️ **Live Flights** | 11,000+ live aircraft + route history | OpenSky + adsb.lol | 🟢 (🟡 optional for more polling credits) |
|
||||
| 🎖️ **Military Flights** | ADS-B military traffic in amber, emergency broadcasts in red | adsb.lol | 🟢 |
|
||||
| 📡 **GNSS Integrity** | Regional navigation accuracy scores; anomalies do not confirm interference | adsb.lol, GPSJAM aggregation | 🟢 |
|
||||
| 🔥 **Fire Perimeters** | Incident boundaries coloured by how recently they were mapped; size, containment and cause on each card when the source reports them | WFIGS / NIFC | 🟢 |
|
||||
| 🔥 **Fire Perimeters** | Incident boundaries and reported containment | WFIGS / NIFC | 🟢 |
|
||||
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
|
||||
| 🛰️ **Satellites** | About 1,300 objects in six classes (Stations, Imaging, Telecom, Starlink, Probes, Debris) with a toggle and a live count each; Starlink loads its whole shell | CelesTrak | 🟢 |
|
||||
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
- Recent Imagery takes a box dragged across the dateline as the short box across
|
||||
±180° instead of refusing it as about 360° wide. A day counts when either side
|
||||
has imagery. A side confirmed empty is not draped, and the VIIRS overview
|
||||
drapes only a side confirmed to have data. Voice accepts named areas across
|
||||
the dateline. EXPORT and `get_recent_imagery` refuse such a box, since
|
||||
Worldview Snapshots cannot draw one (Byrd-IT, #1540).
|
||||
@@ -0,0 +1,8 @@
|
||||
- Aircraft on the map are shaded sprites that show the view of the aircraft
|
||||
from where the camera is, instead of flat top-down silhouettes: each class
|
||||
(and each helicopter rotor frame) is drawn from a sheet rendered from a
|
||||
sphere of camera angles, laid flat along its course, so a plane seen at an
|
||||
oblique angle looks solid. Flights, Military Flights (fleet and tracked
|
||||
contact) and Local ADS-B use it; the TR-3B, airport vehicles, ground
|
||||
stations and Cockpit's far pips stay flat, and a renderer without view
|
||||
sheets draws the flat glyphs as before (Mazeyar Moeini Feizabadi, #1903).
|
||||
@@ -1,8 +0,0 @@
|
||||
- Color Fire Perimeters by how recently each area was mapped instead of by
|
||||
containment: each burned-area piece is yellow under 6 hours old, orange at
|
||||
6–24 hours, red at 1–3 days and dark red when older or of unknown age, with
|
||||
no line along the cuts between pieces. The legend counts fires by their last
|
||||
growth, the card adds "last growth … ago" and keeps containment, and
|
||||
`get_fire_perimeters` returns `last_growth`. A perimeter source now has one
|
||||
`getSnapshot` method, and `perimeterOptions: { inciweb: false }` turns off
|
||||
InciWeb links (gekh, #1910).
|
||||
@@ -1,4 +0,0 @@
|
||||
- Stop restyling the whole page on every DOM change. Rules that checked
|
||||
`body:has(...)` now read classes on the page root that the components owning
|
||||
that state set, and the Intel HUD runs no timers and writes nothing while it
|
||||
is not displayed (samehkhamis, #1911).
|
||||
@@ -1,3 +0,0 @@
|
||||
- Leave the clock at live when Play is pressed at live. Play used to jump to
|
||||
the start of the track and play the whole range from there; paused in the
|
||||
past it still plays from that time (samehkhamis, #1915).
|
||||
+17
-27
@@ -1123,18 +1123,17 @@ Catalog calls check their cancellation signal immediately before executing a
|
||||
tool. Already-cancelled queries do not start; cancellation after execution starts
|
||||
continues to follow the existing tool and caller behavior.
|
||||
|
||||
Fire-perimeter queries test the polygon interiors and holes of each fire's
|
||||
pieces on continuous unwrapped longitudes, matching the short-edge convention
|
||||
used for boundary intersections: a fire is in the area when one of its pieces
|
||||
is. An outline crossing ±180° contains nearby boxes and radius areas without
|
||||
also containing their counterparts near Greenwich. A fire is returned at its
|
||||
card anchor, which the source gives; for WFIGS it is a circular longitude mean
|
||||
over the largest outer ring (excluding its repeated closing vertex), with the
|
||||
relative-area comparison following short longitude edges so a small
|
||||
dateline-crossing part cannot outweigh a larger ordinary part. Context's
|
||||
hazard list measures distance to the same anchor. Regression coverage lives in
|
||||
`src/tools/area.test.mjs`, `src/tools/queries/environment.test.mjs` and
|
||||
`src/layers/perimeters/records.test.mjs`.
|
||||
Fire-perimeter queries test polygon interiors and holes on continuous unwrapped
|
||||
longitudes, matching the short-edge convention used for boundary intersections.
|
||||
An outline crossing ±180° contains nearby boxes and radius areas without also
|
||||
containing their counterparts near Greenwich. Returned perimeter coordinates
|
||||
use a circular mean for longitude, including multipart outlines. Incident cards
|
||||
also use a circular longitude mean over the largest outer ring (excluding its
|
||||
repeated closing vertex). Their relative-area comparison follows short longitude
|
||||
edges so a small dateline-crossing part cannot outweigh a larger ordinary part.
|
||||
Regression coverage lives in `src/tools/area.test.mjs`,
|
||||
`src/tools/queries/environment.test.mjs` and
|
||||
`src/layers/perimeters/cards.test.mjs`.
|
||||
|
||||
## Scope display controls
|
||||
|
||||
@@ -6327,12 +6326,7 @@ Historical planning documents may not match runtime behavior.
|
||||
## Runtime Stack
|
||||
|
||||
- Vite + CesiumJS app with Google Photorealistic 3D Tiles
|
||||
- Scene/HUD/style systems in `src/ui/` and `src/hud.js`. While `#intel-hud` is
|
||||
not displayed (it or a parent has `display: none`, or its view is
|
||||
unmounted), the Intel HUD runs no timers, drops a summary it was working
|
||||
out and publishes no readouts, only its own `active`, variant and colors,
|
||||
which stylesheets and layout elsewhere read; it shows current readouts, and
|
||||
a reply that was typing out in full, as soon as it is displayed again.
|
||||
- Scene/HUD/style systems in `src/ui/` and `src/hud.js`
|
||||
- Layer management in `src/data/manager.js`
|
||||
- Map stack switching in `src/mapStackController.js`
|
||||
- Voice control in `src/voice/` (OpenAI Realtime over WebRTC)
|
||||
@@ -6410,11 +6404,7 @@ MLAT-positioned GPS loss, derived-field exclusions and the NIC 0 exception.
|
||||
anchors, recovery, keyboard and mobile states; emergency repainting is covered
|
||||
by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
|
||||
|
||||
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Link checks cancel on disable or selection change.
|
||||
|
||||
Fire Perimeters draws the fires and burned-area pieces of its source's snapshot. The `getSnapshot` contract is documented in the JSDoc of `createFirePerimetersLayer` (`src/layers/perimeters/index.js`). Pieces are coloured by age at `at` (or now). Areas under 6 hours old are yellow, 6–24 hours orange, and 1–3 days red. Older areas, areas of unknown age and areas dated after `at` are dark red. The layer redraws when `revision` changes or a piece moves to another age band. A snapshot without a string `revision` is redrawn on every read. The legend counts fires by `lastGrowthTime` at the moment of the last successful read, matching the map, and shows the source's `note`. A failed read keeps the last picture and the row shows the error. For a snapshot with a past `at`, a card can link only to an InciWeb incident that began by that time. Of several same-name incidents in the fire's state, it links the one that began nearest the fire's discovery. If none of them began by then, or the ones that did failed to load, it links the fire's complex page by the same rule. A page that fails to load is skipped until the fire is selected again or a read finds its card without a link. `analyst_query` counts `ageHours` from `at` too and treats times after `at` as unknown.
|
||||
|
||||
WFIGS keeps one current perimeter per fire, so each of its polygons is one piece. Colour shows the age of the perimeter based on `poly_PolygonDateTime`. When that field is empty (8 of 54 fires on 2026-11-20), the source falls back to `poly_DateCurrent`, which changes with any edit to the record. A time more than 10 minutes ahead of the browser clock counts as unknown, a nearer one as now. The `revision` follows fire ids and `poly_DateCurrent`. For a fire without `poly_DateCurrent`, it follows the mapping time and outline. WFIGS snapshots always have `at: null`.
|
||||
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
|
||||
|
||||
The incident card rounds the WFIGS size to whole acres, except under one acre,
|
||||
where it keeps the reported hundredths: a 0.25-acre fire reads `0.25 ac`, not
|
||||
@@ -8900,10 +8890,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool,
|
||||
pins and share links already supply complete boxes.
|
||||
|
||||
- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room.
|
||||
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
|
||||
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
|
||||
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
|
||||
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
|
||||
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
|
||||
- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
|
||||
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
|
||||
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
|
||||
- **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
|
||||
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
|
||||
@@ -8919,7 +8909,7 @@ pins and share links already supply complete boxes.
|
||||
30-second backoff ahead of the current clock are ignored. A smaller rollback
|
||||
can retain a bounded retry delay of up to 30 seconds.
|
||||
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the emergency red is mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. Tracking never recolours a model or an icon: the tracked contact draws in the colours it has untracked, and only its alpha changes (faded while stale, clear while its model draws it; `trackedIconColor`, `src/data/trackedAircraftIcon.js`). IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
|
||||
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), in the same colour while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo.
|
||||
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Angle-aware aircraft sprites.** On a renderer with the `viewSheets` capability, each aircraft class (and each of the helicopter's three rotor frames) draws from the aircraft view sheet instead of its flat glyph: `/sprites/aircraft-views.webp`, the classes rendered shaded in neutral grey from a sphere of camera angles (`src/data/viewSheet.js`, baked by `scripts/build-aircraft-view-sheet.py`). 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, military, law enforcement and rescue 35, 5Line truncated
|
||||
- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before.
|
||||
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
|
||||
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
|
||||
|
||||
+1
-1
@@ -310,7 +310,7 @@ and the development server's internal routes. See SECURITY.md.
|
||||
| `get_bhote_koshi_flood` | `events` | The 2026 Bhote Koshi flood: evidence trail in story order, flood path and imagery dates (CC BY-NC 4.0) |
|
||||
| `get_regional_brief` | `regional` | What and where a location is, its weather and recent headlines |
|
||||
| `get_cyclones` | `cyclones` | Active NHC/CPHC tropical cyclones, optionally in an area |
|
||||
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first, with when each was last mapped (WFIGS mapping time, else the record's last edit) |
|
||||
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first |
|
||||
| `get_terrain_height` | `terrain` | Ground, geoid and ellipsoid heights at up to 20 points |
|
||||
| `find_military_installations` | `installations` | OpenStreetMap military sites in an area of at most 10° per side |
|
||||
| `get_map_features` | `features` | Administrative areas, named places or monuments at a location (needs Overpass) |
|
||||
|
||||
+1
-28
@@ -629,12 +629,7 @@ slot whenever its view is drawn.
|
||||
store, which IntelHUD publishes to through its `publish` option: the
|
||||
readouts, the typing summary, the REC blink, visibility, layout variant
|
||||
and style colors; the vessel layer presents the selected vessel's
|
||||
readout through `src/hudReadouts.js` instead of writing into the HUD;
|
||||
the view reports through the store whether `#intel-hud` is displayed
|
||||
(not displayed once it is unmounted), and while it is not IntelHUD runs
|
||||
no timers and publishes only the root's `active`, variant and colors,
|
||||
then shows current readouts as soon as it is; the readouts that change many times a
|
||||
second keep their text node through `v-text-data`),
|
||||
readout through `src/hudReadouts.js` instead of writing into the HUD),
|
||||
the first-run mission launcher (the welcome view renders the card's
|
||||
visibility, busy state, status line, copy and scroll fade from the
|
||||
`gev-first-run` store that `initFirstRunExperience` publishes to, and its
|
||||
@@ -705,28 +700,6 @@ slot whenever its view is drawn.
|
||||
hosts to register panels and rail items is deferred until a host needs
|
||||
one.
|
||||
|
||||
## Page-root state classes
|
||||
|
||||
A stylesheet that styles one surface by the state of another, in a different
|
||||
view (the dock and credits while the Omnibar is on the page, the Stories
|
||||
entry while the loading screen shows), selects a class on `<html>` rather
|
||||
than `body:has(...)`. Chrome checks a `:has()` on body again after every node
|
||||
added or removed anywhere on the page and restyles the whole page when it
|
||||
does; a class changes only with the state it names. `src/ui/rail/rootClass.js`
|
||||
holds them: `v-root-class` on the element whose presence or state it names
|
||||
(the Omnibar, the voice control in the dock, `#intel-hud`, the first-run
|
||||
launcher, the World Timeline, the language picker), its hooks running inside
|
||||
Vue's patch so the class changes with the element; `followSelectorRootClass()`
|
||||
for markup Vue does not render (the loading screen, followed by the Stories
|
||||
view wherever in body it is added, removed or shown, as `:has()` would); and
|
||||
`followRootClass()` for nodes that move at run time (the left panel stack's
|
||||
own panels, followed by the layer panels view). They live on `<html>`, not
|
||||
`<body>`, whose class changes several owners follow to lay the page out
|
||||
again. A rule selects one as `body:is(.has-omnibar *, #gev-omnibar)`: the
|
||||
second argument never matches body and keeps the specificity the
|
||||
`:has(#gev-omnibar)` it replaced had. `src/ui/pageRootClasses.test.mjs`
|
||||
holds each class to its state and every stylesheet to the pattern.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit tests: stores and components run under `npm test`. Single-file
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
"opensky:import": "./scripts/opensky-import-client.sh",
|
||||
"build": "vite build",
|
||||
"build:panel": "node scripts/build-panel.mjs",
|
||||
"build:aircraft-views": "node scripts/build-aircraft-views.mjs",
|
||||
"preview": "vite preview",
|
||||
"test": "node scripts/run-unit-tests.mjs",
|
||||
"test:perf": "node scripts/run-perf-tests.mjs",
|
||||
|
||||
@@ -35,6 +35,9 @@ 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 ([`../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
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Aircraft View Sheet
|
||||
|
||||
`aircraft-views.webp` is the sheet of shaded sprites far-away aircraft are
|
||||
drawn with in Flights, Military Flights and Local ADS-B, on a renderer with the
|
||||
`viewSheets` capability. Each aircraft class is rendered from a sphere of
|
||||
camera angles; the renderer lays a contact flat on the earth along its course
|
||||
and 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 an aircraft seen at an oblique angle looks solid and turns
|
||||
with the camera. `aircraft-views.json` is its manifest.
|
||||
|
||||
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. |
|
||||
|
||||
## Layout
|
||||
|
||||
Each subject owns 302 consecutive cells, row-major: subject `i` starts at
|
||||
cell `i × 302`. The subjects, in order, are `airliner`, `widebody`, `quadjet`,
|
||||
`turboprop`, `light`, `glider`, `fastjet`, `bizjet`, `uav`, and `helicopter0`
|
||||
to `helicopter2` (the helicopter's three rotor frames, `src/data/rotorFrames.js`).
|
||||
|
||||
Within a block the frames lie in 17 rings 7.5° apart, from straight above
|
||||
(ring 0, one frame) to 30° below the horizon, of 1, 4, 7, 10, 13, 16, 18, 20,
|
||||
22, 23, 24, 25, 25, 25, 24, 23 and 22 frames. A ring runs from the eye dead
|
||||
ahead of the nose, 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 aircraft'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 same layout and the maths that picks a frame
|
||||
(`AIRCRAFT_VIEWS`); `src/data/viewSheet.test.mjs` checks the manifest and the
|
||||
bake script against it.
|
||||
|
||||
The sprites are neutral (white 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 the 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. The thin
|
||||
glider, UAV, light aircraft and helicopter are thickened a little before
|
||||
their edge so they still read 20 to 30 px wide. Every cell keeps its outer
|
||||
2 px transparent, so the renderer's mipmaps never pull in a neighbour.
|
||||
|
||||
## Rebuilding
|
||||
|
||||
```
|
||||
npm run build:aircraft-views # about 7 minutes
|
||||
npm run build:aircraft-views -- --only glider,uav --out /tmp/views
|
||||
```
|
||||
|
||||
This needs Blender (`$BLENDER`, else `blender` on the `PATH`, else
|
||||
`/Applications/Blender.app`). It runs `scripts/build-aircraft-view-sheet.py`
|
||||
headless, which renders every frame with Cycles and refuses a frame whose
|
||||
pixels reach within 2 px of its cell's edge, then
|
||||
`scripts/build-aircraft-views.mjs` 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.
|
||||
|
||||
To review a bake, write a contact sheet per subject (its rings as rows over a
|
||||
dark sea, pale land and a mid satellite tone, plus a few frames at 40, 30 and
|
||||
20 px in the fleet, tracked and military tints):
|
||||
|
||||
```
|
||||
node scripts/qa-aircraft-view-sheet.mjs [--manifest public/sprites/aircraft-views.json] [--out qa-shots/aircraft-views]
|
||||
```
|
||||
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"image": "aircraft-views.webp",
|
||||
"cellPx": 64,
|
||||
"columns": 64,
|
||||
"rows": 57,
|
||||
"ringStepDeg": 7.5,
|
||||
"rings": [
|
||||
1,
|
||||
4,
|
||||
7,
|
||||
10,
|
||||
13,
|
||||
16,
|
||||
18,
|
||||
20,
|
||||
22,
|
||||
23,
|
||||
24,
|
||||
25,
|
||||
25,
|
||||
25,
|
||||
24,
|
||||
23,
|
||||
22
|
||||
],
|
||||
"fill": 0.92,
|
||||
"grey": true,
|
||||
"subjects": {
|
||||
"airliner": {
|
||||
"first": 0,
|
||||
"model": "aircraft/a320.glb",
|
||||
"radiusM": 18.883
|
||||
},
|
||||
"widebody": {
|
||||
"first": 302,
|
||||
"model": "aircraft/b789.glb",
|
||||
"radiusM": 32.121
|
||||
},
|
||||
"quadjet": {
|
||||
"first": 604,
|
||||
"model": "aircraft/b744.glb",
|
||||
"radiusM": 37.959
|
||||
},
|
||||
"turboprop": {
|
||||
"first": 906,
|
||||
"model": "aircraft/at72.glb",
|
||||
"radiusM": 14.14
|
||||
},
|
||||
"light": {
|
||||
"first": 1208,
|
||||
"model": "aircraft/c172.glb",
|
||||
"radiusM": 5.825
|
||||
},
|
||||
"glider": {
|
||||
"first": 1510,
|
||||
"model": "aircraft/glider.glb",
|
||||
"radiusM": 7.506
|
||||
},
|
||||
"fastjet": {
|
||||
"first": 1812,
|
||||
"model": "aircraft/t38.glb",
|
||||
"radiusM": 7.408
|
||||
},
|
||||
"bizjet": {
|
||||
"first": 2114,
|
||||
"model": "aircraft/glf4.glb",
|
||||
"radiusM": 17.211
|
||||
},
|
||||
"uav": {
|
||||
"first": 2416,
|
||||
"model": "aircraft/mq9.glb",
|
||||
"radiusM": 9.811
|
||||
},
|
||||
"helicopter0": {
|
||||
"first": 2718,
|
||||
"model": "helicopters/generic_heli.glb",
|
||||
"radiusM": 7.556
|
||||
},
|
||||
"helicopter1": {
|
||||
"first": 3020,
|
||||
"model": "helicopters/generic_heli.glb",
|
||||
"radiusM": 7.556
|
||||
},
|
||||
"helicopter2": {
|
||||
"first": 3322,
|
||||
"model": "helicopters/generic_heli.glb",
|
||||
"radiusM": 7.556
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.1 MiB |
@@ -0,0 +1,561 @@
|
||||
"""Bake the aircraft view sheet: every aircraft class seen from a sphere of
|
||||
directions, as one image of small shaded sprites.
|
||||
|
||||
blender -b --factory-startup --python scripts/build-aircraft-view-sheet.py -- \
|
||||
--out <dir> [--cell 64] [--supersample 4] [--only airliner,light]
|
||||
[--preview <dir>]
|
||||
|
||||
It writes `aircraft-views.png` and its manifest `aircraft-views.json` to
|
||||
`--out`. The manifest names the shipped image, `aircraft-views.webp`, which
|
||||
`npm run build:aircraft-views` (scripts/build-aircraft-views.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 layout and maths; its test,
|
||||
`src/data/viewSheet.test.mjs`, checks this script's constants and the shipped
|
||||
manifest against it). A frame is an orthographic view of the class's
|
||||
fleet model (`public/models/fleet/`, nose 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 aircraft to the eye in the
|
||||
aircraft's own frame (forward, right, up), the aircraft lying flat on the
|
||||
earth: up is the ground's normal, forward its course. Rings of frames lie
|
||||
`RING_STEP_DEG` apart from straight above (ring 0, one frame) down to
|
||||
`RINGS[-1]` below the horizon. 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 aircraft's centre plane.
|
||||
|
||||
Roll. A frame's image up is where the aircraft'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 (white 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. 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. 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 bpy
|
||||
import numpy as np
|
||||
from mathutils import Matrix, Vector
|
||||
|
||||
# --- The sheet's layout (mirrored in src/data/viewSheet.js) -----------------
|
||||
|
||||
RING_STEP_DEG = 7.5
|
||||
# Frames in each ring, from dead ahead round starboard to dead astern.
|
||||
RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22]
|
||||
FRAMES = sum(RINGS)
|
||||
COLUMNS = 64
|
||||
# How much of a cell the model's bounding sphere spans.
|
||||
FILL = 0.92
|
||||
|
||||
# Each class's model, in the order of its block of frames in the sheet. A
|
||||
# helicopter has one block for each rotor frame (rotorFrames.js).
|
||||
ROTOR_ANGLES_DEG = [15, 45, 75]
|
||||
SUBJECTS = [
|
||||
("airliner", "aircraft/a320.glb", None),
|
||||
("widebody", "aircraft/b789.glb", None),
|
||||
("quadjet", "aircraft/b744.glb", None),
|
||||
("turboprop", "aircraft/at72.glb", None),
|
||||
("light", "aircraft/c172.glb", None),
|
||||
("glider", "aircraft/glider.glb", None),
|
||||
("fastjet", "aircraft/t38.glb", None),
|
||||
("bizjet", "aircraft/glf4.glb", None),
|
||||
("uav", "aircraft/mq9.glb", None),
|
||||
("helicopter0", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[0]),
|
||||
("helicopter1", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[1]),
|
||||
("helicopter2", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[2]),
|
||||
]
|
||||
|
||||
# Cell pixels each subject is thickened by before its dark edge, so thin
|
||||
# wings and rotor blades still read when a contact is drawn 20 to 30 px
|
||||
# wide. The big aircraft read as they are and are not thickened.
|
||||
BOLD_PX = {
|
||||
"light": 0.35,
|
||||
"glider": 1.0,
|
||||
"uav": 1.0,
|
||||
"helicopter0": 0.4,
|
||||
"helicopter1": 0.4,
|
||||
"helicopter2": 0.4,
|
||||
}
|
||||
# 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():
|
||||
"""Every frame's (ring, index, d) with d in the model's axes."""
|
||||
out = []
|
||||
for ring, count in enumerate(RINGS):
|
||||
alpha = math.radians(ring * 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 = {
|
||||
"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"])
|
||||
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): 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.
|
||||
PAINT_RAMP = [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)]
|
||||
HELICOPTER_PAINT_RAMP = [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)]
|
||||
SUN_STRENGTH = 1.4
|
||||
SKY_STRENGTH = 0.38
|
||||
FILL_STRENGTH = 0.9
|
||||
|
||||
|
||||
def paint_material(paint_ramp=PAINT_RAMP, solid=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"])
|
||||
links.new(ramp.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 load_model(path, material, rotor_deg, rotor_material):
|
||||
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 []
|
||||
radius = 0.0
|
||||
for mesh in meshes:
|
||||
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()
|
||||
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"])
|
||||
material = paint_material()
|
||||
helicopter_material = paint_material(HELICOPTER_PAINT_RAMP)
|
||||
rotor_material = paint_material(solid=0.82)
|
||||
directions = frame_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": "aircraft-views.webp",
|
||||
"cellPx": cell,
|
||||
"columns": COLUMNS,
|
||||
"rows": rows,
|
||||
"ringStepDeg": RING_STEP_DEG,
|
||||
"rings": RINGS,
|
||||
"fill": FILL,
|
||||
# Every pixel's red, green and blue are equal.
|
||||
"grey": True,
|
||||
"subjects": {},
|
||||
}
|
||||
|
||||
for index, (name, model, rotor_deg) 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),
|
||||
material if rotor_deg is None else helicopter_material,
|
||||
rotor_deg,
|
||||
rotor_material,
|
||||
)
|
||||
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, BOLD_PX.get(name, 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, "aircraft-views.png"), sheet)
|
||||
with open(os.path.join(out, "aircraft-views.json"), "w") as f:
|
||||
json.dump(manifest, f, indent=1)
|
||||
f.write("\n")
|
||||
print(f"wrote {out}/aircraft-views.png ({COLUMNS * cell}x{rows * cell})")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* build-aircraft-views.mjs: bake the aircraft view sheet and ship it.
|
||||
*
|
||||
* Runs `scripts/build-aircraft-view-sheet.py` in Blender (headless) into a
|
||||
* scratch directory, then writes `public/sprites/aircraft-views.webp`
|
||||
* (lossless WebP of the baked PNG) and `public/sprites/aircraft-views.json`
|
||||
* (its manifest). See `public/sprites/README.md`.
|
||||
*
|
||||
* Run: npm run build:aircraft-views [-- --only airliner,light] [--out public/sprites]
|
||||
* 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);
|
||||
|
||||
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(), 'aircraft-views-'));
|
||||
try {
|
||||
const bake = spawnSync(
|
||||
blender(),
|
||||
[
|
||||
'-b',
|
||||
'--factory-startup',
|
||||
'--python',
|
||||
path.join(root, 'scripts', 'build-aircraft-view-sheet.py'),
|
||||
'--',
|
||||
'--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 manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(scratch, 'aircraft-views.json'), 'utf8'),
|
||||
);
|
||||
const png = path.join(scratch, 'aircraft-views.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, 'aircraft-views.json'),
|
||||
path.join(OUT, 'aircraft-views.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 });
|
||||
}
|
||||
@@ -469,8 +469,6 @@
|
||||
"src/layers/perimeters/cards.test.mjs",
|
||||
"src/layers/perimeters/inciweb.test.mjs",
|
||||
"src/layers/perimeters/ownership.test.mjs",
|
||||
"src/app/layers/perimeters.test.mjs",
|
||||
"src/ui/spotConditions.test.mjs",
|
||||
"src/layers/droneAirspace/index.js",
|
||||
"src/layers/droneAirspace/records.js",
|
||||
"src/layers/droneAirspace/source.js",
|
||||
@@ -1449,7 +1447,6 @@
|
||||
"src/hudReadouts.js",
|
||||
"src/ui/stores/hud.js",
|
||||
"src/ui/views/intelHudView.test.mjs",
|
||||
"src/ui/pageRootClasses.test.mjs",
|
||||
"src/testSupport/hudReadouts.mjs",
|
||||
"src/ui/stores/firstRun.js",
|
||||
"src/firstRunLauncherView.test.mjs",
|
||||
|
||||
@@ -68,7 +68,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -194,8 +195,6 @@
|
||||
"src/ui/stores/owners.js",
|
||||
"src/ui/rail/rangeValue.js",
|
||||
"src/ui/rail/classToggle.js",
|
||||
"src/ui/rail/rootClass.js",
|
||||
"src/ui/rail/textData.js",
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/rail/fieldValue.js",
|
||||
"src/ui/rail/statusText.js",
|
||||
@@ -281,7 +280,6 @@
|
||||
"src/i18n/marker.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/layers/perimeters/source.js",
|
||||
"src/layers/perimeters/records.js",
|
||||
"src/ui/spotConditions.js",
|
||||
"src/ui/views/panels/SpotConditions.vue",
|
||||
"src/data/wikidataCities.js",
|
||||
@@ -1306,7 +1304,8 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/satellites/issMounts.js",
|
||||
"src/layers/satellites/tiangongMounts.js"
|
||||
"src/layers/satellites/tiangongMounts.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -1718,7 +1717,8 @@
|
||||
"src/data/liveStreams.js",
|
||||
"src/data/youtubeApi.js",
|
||||
"src/data/youtubeLivePlayer.js",
|
||||
"src/ui/liveControls.js"
|
||||
"src/ui/liveControls.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"cesium",
|
||||
@@ -1922,7 +1922,8 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/scenes/storyTags.js",
|
||||
"src/scenes/storyThumb.js"
|
||||
"src/scenes/storyThumb.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"]
|
||||
},
|
||||
@@ -2089,7 +2090,9 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/flights/placed.js",
|
||||
"src/data/courseFromFixes.js"
|
||||
"src/data/courseFromFixes.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2235,7 +2238,9 @@
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/flights/placed.js",
|
||||
"src/data/courseFromFixes.js",
|
||||
"src/data/approxDistance.js"
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2393,7 +2398,8 @@
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/layers/vessels/photos.js",
|
||||
"src/data/openVesselPhoto.js"
|
||||
"src/data/openVesselPhoto.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2524,7 +2530,8 @@
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/sky/assets.js",
|
||||
"src/render/cesium/cardPreviews.js"
|
||||
"src/render/cesium/cardPreviews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -2622,7 +2629,8 @@
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/time/frameWait.js"
|
||||
"src/time/frameWait.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -2774,7 +2782,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -2897,7 +2906,8 @@
|
||||
"src/layers/satellites/tiangongModel.js",
|
||||
"src/layers/satellites/tiangongStation.js",
|
||||
"src/layers/satellites/tiangongJoints.js",
|
||||
"src/layers/satellites/tiangongArticulation.js"
|
||||
"src/layers/satellites/tiangongArticulation.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "satellite.js", "kdbush"]
|
||||
},
|
||||
@@ -3001,7 +3011,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -3113,7 +3124,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -3195,7 +3207,8 @@
|
||||
"src/data/installationFeedback.js",
|
||||
"src/ui/layerNames.js",
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/ui/statusText.js"
|
||||
"src/ui/statusText.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -3321,7 +3334,8 @@
|
||||
"src/render/vectorBase/index.js",
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js"
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -3515,7 +3529,8 @@
|
||||
"src/render/vectorBase/index.js",
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js"
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -3645,7 +3660,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"cesium",
|
||||
@@ -3738,7 +3754,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -3850,7 +3867,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -3925,7 +3943,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -4066,7 +4085,8 @@
|
||||
"src/render/vectorBase/index.js",
|
||||
"src/render/vectorBase/style.js",
|
||||
"src/render/vectorBase/paint.js",
|
||||
"src/render/vectorBase/expressions.js"
|
||||
"src/render/vectorBase/expressions.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
@@ -4855,7 +4875,6 @@
|
||||
"src/ui/layerRowText.js",
|
||||
"src/ui/layerPanel/LayerRows.vue",
|
||||
"src/ui/rail/classToggle.js",
|
||||
"src/ui/rail/rootClass.js",
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/layerPanel/RowText.vue",
|
||||
"src/ui/layerPanel/RowSwitch.vue",
|
||||
@@ -5601,7 +5620,9 @@
|
||||
"src/layers/satellites/tiangongStation.js",
|
||||
"src/layers/satellites/tiangongModel.js",
|
||||
"src/layers/satellites/tiangongJoints.js",
|
||||
"src/layers/satellites/tiangongArticulation.js"
|
||||
"src/layers/satellites/tiangongArticulation.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"hls.js",
|
||||
@@ -6457,7 +6478,9 @@
|
||||
"src/layers/satellites/tiangongStation.js",
|
||||
"src/layers/satellites/tiangongJoints.js",
|
||||
"src/layers/satellites/tiangongArticulation.js",
|
||||
"src/layers/satellites/tiangongModel.js"
|
||||
"src/layers/satellites/tiangongModel.js",
|
||||
"src/data/aircraftViews.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"hls.js",
|
||||
@@ -6606,7 +6629,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": [
|
||||
"cesium",
|
||||
@@ -6720,7 +6744,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -7555,7 +7580,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "egm96-universal", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -7685,7 +7711,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "pbf", "kdbush"]
|
||||
},
|
||||
@@ -7997,7 +8024,8 @@
|
||||
"src/render/cesium/zoomOutGuard.js",
|
||||
"src/render/cesium/sceneOcclusionProbe.js",
|
||||
"src/render/occlusion/depthProbe.js",
|
||||
"src/data/detectionOcclusion.js"
|
||||
"src/data/detectionOcclusion.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["cesium", "kdbush"]
|
||||
},
|
||||
@@ -8194,7 +8222,6 @@
|
||||
"src/data/militaryInstallationData.js",
|
||||
"src/layers/launches/source.js",
|
||||
"src/layers/perimeters/source.js",
|
||||
"src/layers/perimeters/records.js",
|
||||
"src/layers/radio/source.js",
|
||||
"src/layers/radio/policy.js",
|
||||
"src/layers/satellites/source.js",
|
||||
@@ -8447,7 +8474,8 @@
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/render/recession.js",
|
||||
"src/render/modelParts.js"
|
||||
"src/render/modelParts.js",
|
||||
"src/data/viewSheet.js"
|
||||
],
|
||||
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* qa-aircraft-view-sheet.mjs: contact sheets of a baked aircraft view sheet,
|
||||
* for reviewing a bake (`scripts/build-aircraft-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, 30° below the horizon at the bottom, each ring
|
||||
* from dead ahead to dead astern), over a dark sea colour, a pale land colour
|
||||
* and a mid satellite tone, each tinted as the layers tint it. Under them, a
|
||||
* few frames (above, oblique, abeam, below) shrunk to the sizes a contact is
|
||||
* drawn at, to judge whether thin wings still read.
|
||||
*
|
||||
* Run: node scripts/qa-aircraft-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
|
||||
* [--sheet <image>] [--out qa-shots/aircraft-views] [--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';
|
||||
|
||||
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 OUT = path.resolve(opt('--out', 'qa-shots/aircraft-views'));
|
||||
const ZOOM = Number(opt('--zoom', '2'));
|
||||
const SIZES = opt('--sizes', '40,30,20').split(',').map(Number);
|
||||
const ONLY = opt('--only', '').split(',').filter(Boolean);
|
||||
|
||||
/** Grounds a contact is seen over: a dark sea, pale land, a mid satellite tone. */
|
||||
const GROUNDS = [
|
||||
{ name: 'sea', css: '#1f3a4f' },
|
||||
{ name: 'land', css: '#d9d2bd' },
|
||||
{ name: 'satellite', css: '#6f7559' },
|
||||
];
|
||||
/** The layers' tints, multiplied into the neutral sprite. */
|
||||
const TINTS = [
|
||||
{ name: 'fleet', rgb: [1, 1, 1] },
|
||||
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
|
||||
{ name: 'military', rgb: [1, 0.72, 0] },
|
||||
];
|
||||
const GAP = 8;
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
|
||||
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));
|
||||
/** Frames shown shrunk, as ring and index: straight above, oblique from
|
||||
* ahead and to the right, abeam on the horizon, and from below, abeam. */
|
||||
const PICKS = [
|
||||
[0, 0],
|
||||
[ringAt(45), Math.floor((rings[ringAt(45)] - 1) / 3)],
|
||||
[ringAt(90), Math.round((rings[ringAt(90)] - 1) / 2)],
|
||||
[rings.length - 1, Math.round((rings[rings.length - 1] - 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 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, fleet 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, TINTS[0], 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));
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
#!/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] [--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) or `flights` (white, the
|
||||
// classes an ADS-B emitter category gives).
|
||||
const LAYER = opt('--layer', 'military');
|
||||
// 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],
|
||||
];
|
||||
const ROWS = LAYER === 'flights' ? CATEGORIES : CLASSES;
|
||||
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
|
||||
const CENTRE = { lon: -97.74, lat: 30.3 };
|
||||
const STEP_DEG = 0.03;
|
||||
const ALT_FT = 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 },
|
||||
{ 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\/aircraft-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/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) => {
|
||||
const { dataManager, viewer } = window.__godsEyeView;
|
||||
await dataManager.setEnabled(name, true);
|
||||
const layer = dataManager.layers.get(name).module;
|
||||
for (let i = 0; i < 4; i++) await layer.update(viewer);
|
||||
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
|
||||
return layer.getStats().count;
|
||||
}, LAYER);
|
||||
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);
|
||||
});
|
||||
@@ -23,7 +23,6 @@ const API_URL =
|
||||
'attr_IncidentTypeCategory',
|
||||
'attr_FireDiscoveryDateTime',
|
||||
'poly_DateCurrent',
|
||||
'poly_PolygonDateTime',
|
||||
'attr_FireCause',
|
||||
'attr_FireBehaviorGeneral',
|
||||
'attr_TotalIncidentPersonnel',
|
||||
|
||||
@@ -67,8 +67,6 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
|
||||
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
|
||||
* places live aircraft, vessels, transit and trains; without one each layer
|
||||
* uses its own motion.
|
||||
* `perimeterOptions: { inciweb: false }` leaves the Fire Perimeters cards
|
||||
* without InciWeb links, and the layer never asks InciWeb.
|
||||
*/
|
||||
export function createApplicationCatalog({
|
||||
surface,
|
||||
@@ -77,7 +75,6 @@ export function createApplicationCatalog({
|
||||
metadata = APPLICATION_LAYER_METADATA,
|
||||
vesselOptions,
|
||||
newsOptions,
|
||||
perimeterOptions,
|
||||
resolveAsset,
|
||||
nepalBoundaryResolver,
|
||||
streetLevelProviders,
|
||||
@@ -148,7 +145,6 @@ export function createApplicationCatalog({
|
||||
createApplicationEarthquakes({ source: sources.earthquakes }),
|
||||
createApplicationAirQuality({ source: sources['air-quality'] }),
|
||||
createApplicationFirePerimeters({
|
||||
...perimeterOptions,
|
||||
source: sources['fire-perimeters'],
|
||||
}),
|
||||
createApplicationGnssIntegrity({
|
||||
|
||||
@@ -7,8 +7,6 @@ import { catalogControlServices } from './catalog.js';
|
||||
import { LayerLifecycle } from '../data/lifecycle.js';
|
||||
import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
|
||||
import { worldClock } from '../time/worldClock.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
@@ -256,48 +254,3 @@ test('a GNSS integrity source can set the layer evidence window', (t) => {
|
||||
`${String(windowMs)} falls back to the default`,
|
||||
);
|
||||
});
|
||||
|
||||
test('perimeterOptions reach Fire Perimeters: inciweb false never asks InciWeb', async (t) => {
|
||||
const lifetime = new AbortController();
|
||||
const { signal } = lifetime;
|
||||
const sources = fixtureSources([], []);
|
||||
sources['fire-perimeters'] = {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
fetchedAt: null,
|
||||
stale: false,
|
||||
revision: 'r',
|
||||
note: null,
|
||||
fires: [],
|
||||
pieces: [],
|
||||
}),
|
||||
};
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
return Response.json([]);
|
||||
});
|
||||
const viewer = { scene: { pick: () => null } };
|
||||
bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
const layer = createApplicationCatalog({
|
||||
sources,
|
||||
signal,
|
||||
surface: fixtureSurface(signal),
|
||||
perimeterOptions: { inciweb: false, inputFor: () => input.input },
|
||||
}).get('fire-perimeters');
|
||||
t.after(() => {
|
||||
layer.destroy();
|
||||
input.destroy();
|
||||
lifetime.abort();
|
||||
worldClock.goLive();
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
assert.equal(await layer.update(viewer), true);
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(
|
||||
requested.filter((url) => url.includes('inciweb')),
|
||||
[],
|
||||
);
|
||||
});
|
||||
@@ -6,11 +6,8 @@ import {
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
|
||||
/** Wire fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters({
|
||||
inciweb = true,
|
||||
...options
|
||||
} = {}) {
|
||||
/** Wire WFIGS fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters(options) {
|
||||
return createFirePerimetersLayer({
|
||||
overlayHost: {
|
||||
setEntries: overlays.setOverlayEntries,
|
||||
@@ -18,17 +15,10 @@ export function createApplicationFirePerimeters({
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
...(inciweb !== false && {
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
}),
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
picking,
|
||||
...options,
|
||||
// inciweb: false outranks InciWeb sources in options.
|
||||
...(inciweb === false && {
|
||||
inciwebSource: null,
|
||||
inciwebPublications: null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createApplicationFirePerimeters } from './perimeters.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
|
||||
const ring = [
|
||||
[-108.1, 35.2],
|
||||
[-108.0, 35.2],
|
||||
[-108.0, 35.3],
|
||||
[-108.1, 35.2],
|
||||
];
|
||||
const source = {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
fetchedAt: null,
|
||||
stale: false,
|
||||
revision: 'r',
|
||||
note: null,
|
||||
fires: [{ id: 'f', name: 'Fixture', anchor: { lon: -108.05, lat: 35.25 } }],
|
||||
pieces: [{ fireId: 'f', born: null, polygons: [[ring]], outline: [ring] }],
|
||||
}),
|
||||
};
|
||||
|
||||
for (const inciweb of [true, false]) {
|
||||
test(`inciweb: ${inciweb} ${inciweb ? 'asks' : 'never asks'} InciWeb`, async (t) => {
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
return Response.json([]);
|
||||
});
|
||||
const viewer = { scene: { pick: () => null } };
|
||||
bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
t.after(() => input.destroy());
|
||||
const getIndex = t.mock.fn(async () => []);
|
||||
const layer = createApplicationFirePerimeters({
|
||||
source,
|
||||
inciweb,
|
||||
...(inciweb === false && { inciwebSource: { getIndex } }),
|
||||
inputFor: () => input.input,
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
assert.equal(await layer.update(viewer), true);
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(
|
||||
requested.filter((url) => url.includes('inciweb')),
|
||||
inciweb ? ['/api/fire-perimeters/inciweb/index'] : [],
|
||||
);
|
||||
assert.equal(getIndex.mock.callCount(), 0);
|
||||
layer.destroy(viewer);
|
||||
});
|
||||
}
|
||||
+1
-3
@@ -39,7 +39,6 @@ import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
|
||||
import {
|
||||
getRenderGovernorDiagnostics,
|
||||
governorRequestRender,
|
||||
FOLLOW_FRAME_RATE,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
} from '../renderGovernor.js';
|
||||
@@ -274,8 +273,7 @@ export function createApplicationTools({
|
||||
// The follow camera recomputes the tracked target's dead-reckon position
|
||||
// every frame — tracking anything is a per-frame animation. (perf wave 2)
|
||||
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
|
||||
if (followed)
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
if (followed) holdContinuousRender('tracked-entity');
|
||||
else releaseContinuousRender('tracked-entity');
|
||||
});
|
||||
|
||||
|
||||
@@ -243,7 +243,7 @@ const RECOGNIZED = new Set([
|
||||
// credit
|
||||
'#cesium-credits',
|
||||
'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits',
|
||||
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits",
|
||||
"body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits",
|
||||
'body.ui-clean-view #cesium-credits',
|
||||
'body.recording-mode #cesium-credits',
|
||||
// dock
|
||||
@@ -274,12 +274,12 @@ const DOCKED_RAIL = 'body.context-docked #right-context-rail';
|
||||
// the Omnibar and the voice control share the dock; outside it the legacy
|
||||
// layout below governs.
|
||||
const OMNIBAR_SCOPE =
|
||||
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(.has-omnibar.dock-has-voice *)';
|
||||
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(:has(#gev-omnibar):has(#command-dock > #gev-voice-control))';
|
||||
const OMNIBAR = Object.freeze({
|
||||
dock: `${OMNIBAR_SCOPE} #command-dock`,
|
||||
credit: `${OMNIBAR_SCOPE} :is(#cesium-credits, #gev-credits)`,
|
||||
minimalCredit: `${OMNIBAR_SCOPE}:is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`,
|
||||
minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #right-context-rail`,
|
||||
minimalCredit: `${OMNIBAR_SCOPE}:has(#intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`,
|
||||
minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) #right-context-rail`,
|
||||
trays: `${OMNIBAR_SCOPE} #command-dock > :is(#location-bar, #control-panel)`,
|
||||
});
|
||||
// What each Omnibar-scope rule may set on a modelled box; the Omnibar
|
||||
@@ -518,7 +518,7 @@ const CREDIT_SELECTORS = [
|
||||
'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits',
|
||||
];
|
||||
const MINIMAL_HUD_CREDIT =
|
||||
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits";
|
||||
"body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits";
|
||||
const TRAY_ORDINARY = [
|
||||
'#command-dock .dock-popover-content',
|
||||
'#command-dock #location-bar .dock-popover-content',
|
||||
@@ -1279,7 +1279,7 @@ test('expanded Context keeps the credits beside it right to left and with the mi
|
||||
// The minimal HUD puts the credits bottom right, where the column docks.
|
||||
assert.ok(
|
||||
rule(
|
||||
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):is\\( \\.hud-minimal-active \\*, #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
|
||||
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):has\\( #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
|
||||
'right: calc\\(36px \\+ var\\(--context-dock-width\\)\\)',
|
||||
),
|
||||
'with the minimal HUD, the credits end before the expanded column',
|
||||
|
||||
@@ -10,7 +10,6 @@ import { straightSegment } from './fixCurve.js';
|
||||
import {
|
||||
norm180,
|
||||
distance,
|
||||
distanceSquared,
|
||||
clone,
|
||||
copyInto,
|
||||
toDegrees,
|
||||
@@ -34,6 +33,7 @@ import {
|
||||
} from './aircraftIcons.js';
|
||||
import { cockpitContactDotImage } from './cockpitContactDot.js';
|
||||
import { rotorFrame, rotorTurns } from './rotorFrames.js';
|
||||
import { registerAircraftViews, withAircraftView } from './aircraftViews.js';
|
||||
import { aircraftRecedeSpec } from './aircraftRecession.js';
|
||||
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
|
||||
|
||||
@@ -386,32 +386,8 @@ let instances = 0;
|
||||
/** A plan that ran out longer ago than this (ms) is not eased away from. */
|
||||
const RECOVER_STALE_PLAN_MS = 1_000;
|
||||
|
||||
/** How far ahead (ms) a placed contact's segment runs before it is asked
|
||||
* again, in view and near the eye. */
|
||||
/** How far ahead (ms) a placed contact's segment runs before it is asked again. */
|
||||
const PLACED_PLAN_MS = 1000;
|
||||
/** The same out of view, or farther than PLACED_NEAR_M from the eye: off
|
||||
* screen a contact's path is not seen, and that far a straight segment
|
||||
* over this long (half as long again at most, as spread) is well under a
|
||||
* pixel off it. Asking for each contact every second would rewrite the
|
||||
* whole fleet every second. */
|
||||
const PLACED_FAR_PLAN_MS = 4000;
|
||||
/** Nearer the eye than this (m), a placed contact in view is planned every
|
||||
* PLACED_PLAN_MS. */
|
||||
const PLACED_NEAR_M = 300_000;
|
||||
|
||||
/**
|
||||
* Each contact's plans run between 1/2 and 3/2 of their length, by its id,
|
||||
* so the fleet's plans run out spread over the passes, not together in one
|
||||
* (contacts first planned in the same pass would otherwise stay in step).
|
||||
*/
|
||||
export function placedPlanSpread(id) {
|
||||
let hash = 2166136261;
|
||||
for (let i = 0; i < id.length; i++) {
|
||||
hash ^= id.charCodeAt(i);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return 0.5 + ((hash >>> 0) % 1024) / 1024;
|
||||
}
|
||||
|
||||
/** A display delay that never changes (ms). */
|
||||
function fixedDelay(ms) {
|
||||
@@ -461,6 +437,8 @@ function fixedDelay(ms) {
|
||||
* Where a host-supplied placement draws a live contact at a wall time,
|
||||
* written into `out` (`placeAircraftAt`), or null when it does not place
|
||||
* it; none without a placement.
|
||||
* @param {(url: string) => string} [options.resolveAsset] The layer's asset
|
||||
* URL resolver, for the aircraft view sheet's image.
|
||||
*/
|
||||
export function createAircraftIcons({
|
||||
state,
|
||||
@@ -478,10 +456,14 @@ export function createAircraftIcons({
|
||||
afterSettle = () => {},
|
||||
onForget = () => {},
|
||||
placeAt = null,
|
||||
resolveAsset = (url) => url,
|
||||
}) {
|
||||
const { focusPassIsNeeded } = services.focus;
|
||||
// The near-image switch the rows were last written with (CSS px).
|
||||
let switchPx = nearImageSwitchPx(1);
|
||||
/** Whether the renderer draws icons along their course from the aircraft
|
||||
* view sheet (`aircraftViews.js`), set when the draw set is made. */
|
||||
let views = false;
|
||||
/**
|
||||
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
|
||||
* frame each was last drawn at, and the frame it was last judged at
|
||||
@@ -490,8 +472,6 @@ export function createAircraftIcons({
|
||||
* @type {Map<string, {drawn: number, checked: number}>}
|
||||
*/
|
||||
const rotors = new Map();
|
||||
/** When a rotor in view was last given a new frame (wall ms). */
|
||||
let rotorDrawnAtMs = -Infinity;
|
||||
|
||||
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
|
||||
const _displayMs = () =>
|
||||
@@ -519,8 +499,7 @@ export function createAircraftIcons({
|
||||
const motionClock = (scene) =>
|
||||
scene
|
||||
? { kind: 'scene' }
|
||||
: // The layer's pace asks for the frames its moving rows need.
|
||||
{ kind: 'live', delayMs: displayDelay.currentMs, frames: 'owner' };
|
||||
: { kind: 'live', delayMs: displayDelay.currentMs };
|
||||
|
||||
/**
|
||||
* Once a frame: move the display delay on, and put the set's motion on
|
||||
@@ -572,9 +551,9 @@ export function createAircraftIcons({
|
||||
sceneClock = followsClock();
|
||||
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
|
||||
switchPx = _imageSwitchPx(viewer);
|
||||
state._icons = createContactIcons(set, {
|
||||
capabilities: rendererOf(viewer)?.capabilities ?? null,
|
||||
});
|
||||
const capabilities = rendererOf(viewer)?.capabilities ?? null;
|
||||
views = registerAircraftViews(drawOf(viewer), capabilities, resolveAsset);
|
||||
state._icons = createContactIcons(set, { capabilities });
|
||||
return set.id;
|
||||
}
|
||||
|
||||
@@ -583,6 +562,7 @@ export function createAircraftIcons({
|
||||
state._icons?.dispose();
|
||||
state._icons = null;
|
||||
liveSet = null;
|
||||
views = false;
|
||||
rotors.clear();
|
||||
planFrom.clear();
|
||||
easeEnds.clear();
|
||||
@@ -843,28 +823,12 @@ export function createAircraftIcons({
|
||||
planFrom.set(icao24, validFrom);
|
||||
}
|
||||
|
||||
/** The camera, while the fleet pass re-plans the rows that ran out:
|
||||
* `{eye, inView(position)}` (null: every plan is a near one). */
|
||||
let planView = null;
|
||||
|
||||
/** How long a placed contact at `position` is planned for (ms). */
|
||||
function _placedPlanMs(icao24, position) {
|
||||
const near =
|
||||
!planView ||
|
||||
(distanceSquared(planView.eye, position) <
|
||||
PLACED_NEAR_M * PLACED_NEAR_M &&
|
||||
planView.inView(position));
|
||||
return (
|
||||
(near ? PLACED_PLAN_MS : PLACED_FAR_PLAN_MS) * placedPlanSpread(icao24)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan a live contact a host-supplied placement places: from where it
|
||||
* places it at `t` (display ms, the live clock's delayed time) to where it
|
||||
* places it a plan's length on (`_placedPlanMs`), asked again when that
|
||||
* runs out. Display time is wall time less the display delay, so the
|
||||
* placement is asked at the wall times the segment's ends stand for.
|
||||
* places it PLACED_PLAN_MS on, asked again when that runs out. Display
|
||||
* time is wall time less the display delay, so the placement is asked at
|
||||
* the wall times the segment's ends stand for.
|
||||
* @returns {boolean} False when there is no placement, the layer follows
|
||||
* the world clock, or it has no answer for this contact.
|
||||
*/
|
||||
@@ -883,7 +847,7 @@ export function createAircraftIcons({
|
||||
)
|
||||
return true;
|
||||
easeEnds.delete(icao24);
|
||||
const t1 = t + _placedPlanMs(icao24, from);
|
||||
const t1 = t + PLACED_PLAN_MS;
|
||||
const to = vec();
|
||||
const end = placeAt(icao24, t1 + leadMs, info, history, to);
|
||||
const motion = end
|
||||
@@ -947,17 +911,12 @@ export function createAircraftIcons({
|
||||
* moved back (a seek, or the clock run backward): it is drawn where it was
|
||||
* then, as it is when the time moves on.
|
||||
*/
|
||||
function _replanExpired(t, view = null) {
|
||||
planView = view;
|
||||
try {
|
||||
if (followsClock() && t < replannedAt)
|
||||
for (const [icao24, from] of planFrom)
|
||||
if (from > t) _planIcon(icao24, { rewound: true });
|
||||
replannedAt = t;
|
||||
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
|
||||
} finally {
|
||||
planView = null;
|
||||
}
|
||||
function _replanExpired(t) {
|
||||
if (followsClock() && t < replannedAt)
|
||||
for (const [icao24, from] of planFrom)
|
||||
if (from > t) _planIcon(icao24, { rewound: true });
|
||||
replannedAt = t;
|
||||
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -979,7 +938,6 @@ export function createAircraftIcons({
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
const eye = viewer ? findCamera(viewer)?.pose()?.position : null;
|
||||
let active = 0;
|
||||
let fading = 0;
|
||||
for (const id of icons.ids()) {
|
||||
if (!icons.shown(id) && !state._models.has(id)) continue;
|
||||
const item = icons.item(id);
|
||||
@@ -1002,32 +960,36 @@ export function createAircraftIcons({
|
||||
spriteHalfHeightPx: item.size[1] * half,
|
||||
});
|
||||
if (focus.active || focus.transitioning) active++;
|
||||
if (focus.transitioning) fading++;
|
||||
if (focusAlphaNeedsWrite(current, focus.factor))
|
||||
icons.setFocus(id, focus.factor);
|
||||
}
|
||||
state._iconFocusActive = active;
|
||||
// Rows still fading in or out, for the layer's pace.
|
||||
state._iconFocusFading = fading;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a contact's icon is drawn outside Cockpit: its image (and the sharper
|
||||
* one it switches to up close), size, scale and scale by distance. The
|
||||
* tracked contact's own icon is drawn with this too, so selecting a contact
|
||||
* changes its colour and nothing else.
|
||||
* changes its colour and nothing else. Drawn along its course
|
||||
* (`alongCourse`) on a renderer that draws view sheets, a kind with
|
||||
* rendered views draws from the aircraft view sheet, with no near image
|
||||
* (`aircraftViews.js`); otherwise it is the flat glyph.
|
||||
* @param {string} icao24
|
||||
* @param {object} [info] Its record.
|
||||
* @returns {{image: string, imageLod: {near: string, switchPx: number},
|
||||
* @param {number} [frame] A helicopter's rotor frame.
|
||||
* @param {{alongCourse?: boolean}} [options]
|
||||
* @returns {{image: string|{views: string, first: number},
|
||||
* imageLod: {near: string, switchPx: number}|undefined,
|
||||
* size: [number, number], scale: number, scaleByDistance: object}}
|
||||
*/
|
||||
function _fleetLook(
|
||||
icao24,
|
||||
info = state.records.data.get(icao24),
|
||||
frame = _rotorFrameOf(icao24, info, Date.now()),
|
||||
{ alongCourse = false } = {},
|
||||
) {
|
||||
const rendering = parts.rendering;
|
||||
return {
|
||||
const look = {
|
||||
image: aircraftIcon(
|
||||
rendering._iconKind(icao24, info?.klass),
|
||||
FLEET_ICON_PX,
|
||||
@@ -1045,6 +1007,17 @@ export function createAircraftIcons({
|
||||
scale: rendering._fleetBillboardScale(icao24),
|
||||
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
|
||||
};
|
||||
return withAircraftView(look, {
|
||||
views,
|
||||
kind: rendering._iconKind(icao24, info?.klass),
|
||||
frame,
|
||||
rotationMode: alongCourse ? 'course' : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether contacts drawn along their course draw from the view sheet. */
|
||||
function _drawsViews() {
|
||||
return views;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1096,7 +1069,6 @@ export function createAircraftIcons({
|
||||
if (!_aboveHorizon(position, occluder)) continue;
|
||||
if (inView && !inView(position)) continue;
|
||||
rotor.drawn = frame;
|
||||
rotorDrawnAtMs = nowMs;
|
||||
if (tracked) {
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
continue;
|
||||
@@ -1105,6 +1077,7 @@ export function createAircraftIcons({
|
||||
id,
|
||||
state.records.data.get(id),
|
||||
frame,
|
||||
{ alongCourse: icons.item(id)?.rotationMode === 'course' },
|
||||
);
|
||||
icons.update(id, { image, imageLod });
|
||||
}
|
||||
@@ -1118,6 +1091,11 @@ export function createAircraftIcons({
|
||||
const rendering = parts.rendering;
|
||||
const info = state.records.data.get(icao24);
|
||||
const tracked = icao24 === state._trackedIcao;
|
||||
// A helicopter's rotor frame, chosen once for its look and its rotor.
|
||||
const heliFrame = _rotorFrameOf(icao24, info, Date.now());
|
||||
// A ground station's mast stands upright; every other glyph turns
|
||||
// along its course.
|
||||
const station = info?.klass === 'station';
|
||||
const cockpitDot =
|
||||
state._cockpitContactMode &&
|
||||
!tracked &&
|
||||
@@ -1133,21 +1111,18 @@ export function createAircraftIcons({
|
||||
rotationMode: 'screen',
|
||||
}
|
||||
: {
|
||||
..._fleetLook(icao24, info),
|
||||
..._fleetLook(icao24, info, heliFrame, { alongCourse: !station }),
|
||||
color: rgba(rendering._fleetBillboardColor(icao24, info)),
|
||||
rotationMode: 'course',
|
||||
};
|
||||
// A ground station's mast stands upright.
|
||||
if (!cockpitDot && info?.klass === 'station') {
|
||||
if (!cockpitDot && station) {
|
||||
look.rotationMode = 'screen';
|
||||
look.rotation = 0;
|
||||
}
|
||||
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
|
||||
icons.update(icao24, look);
|
||||
// An airborne helicopter drawn as its glyph turns its rotor.
|
||||
const frame = cockpitDot
|
||||
? undefined
|
||||
: _rotorFrameOf(icao24, info, Date.now());
|
||||
const frame = cockpitDot ? undefined : heliFrame;
|
||||
if (frame === undefined || !rotorTurns(_rotorState(info))) {
|
||||
// A tracked helicopter that lands shows the still frame at once.
|
||||
if (rotors.delete(icao24) && tracked)
|
||||
@@ -1160,11 +1135,6 @@ export function createAircraftIcons({
|
||||
return rotors.size > 0;
|
||||
}
|
||||
|
||||
/** When a rotor in view was last given a new frame (wall ms), for the pace. */
|
||||
function _rotorDrawnAtMs() {
|
||||
return rotorDrawnAtMs;
|
||||
}
|
||||
|
||||
/** Add a row for a new contact, hidden while it is the tracked one. */
|
||||
function _addIcon(icao24) {
|
||||
state._icons.put(_baseItem(icao24, icao24 !== state._trackedIcao), {
|
||||
@@ -1235,9 +1205,9 @@ export function createAircraftIcons({
|
||||
_focusIcons,
|
||||
_applyIconPresentation,
|
||||
_fleetLook,
|
||||
_drawsViews,
|
||||
_turnRotors,
|
||||
_rotorsTurning,
|
||||
_rotorDrawnAtMs,
|
||||
_addIcon,
|
||||
_forgetContact,
|
||||
_iconIds,
|
||||
|
||||
+159
-107
@@ -5,7 +5,6 @@ import {
|
||||
createAircraftIcons,
|
||||
createContactIcons,
|
||||
floorCoastArc,
|
||||
placedPlanSpread,
|
||||
} from './aircraftIconLayer.js';
|
||||
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
|
||||
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
|
||||
@@ -38,11 +37,7 @@ test('following the world clock, contacts draw at the world’s time on the scen
|
||||
icons._createIcons(viewer);
|
||||
const set = draw.find('flights-icons:');
|
||||
// Live: a poll interval behind real time, on the delayed live clock.
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
|
||||
assert.equal(icons._displayMs(), Date.now() - 30_000);
|
||||
following = true;
|
||||
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
|
||||
@@ -50,11 +45,7 @@ test('following the world clock, contacts draw at the world’s time on the scen
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
|
||||
following = false;
|
||||
icons._syncMotionClock();
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
|
||||
icons._disposeIcons();
|
||||
});
|
||||
|
||||
@@ -77,11 +68,7 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
|
||||
});
|
||||
icons._createIcons(viewer);
|
||||
const set = draw.find('flights-icons:');
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
|
||||
// Reports 90 s old every 30 s: the delay heads for about two minutes.
|
||||
for (let i = 0; i < 20; i++)
|
||||
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
|
||||
@@ -89,11 +76,7 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
|
||||
t.mock.timers.setTime(WORLD_MS + 10_000);
|
||||
icons._syncMotionClock();
|
||||
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 32_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
|
||||
assert.equal(icons._displayMs(), Date.now() - 32_000);
|
||||
// Following the world clock: no delay, and it is not moved on meanwhile.
|
||||
following = true;
|
||||
@@ -104,11 +87,7 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
|
||||
assert.equal(delay.currentMs, 32_000);
|
||||
following = false;
|
||||
icons._syncMotionClock();
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 34_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
|
||||
icons._disposeIcons();
|
||||
});
|
||||
|
||||
@@ -503,109 +482,182 @@ test('back at live, a placed contact eases from where it is drawn over a recover
|
||||
);
|
||||
});
|
||||
|
||||
/** A layer whose placement has every contact flying east from `at(id)`. */
|
||||
function placedFleet(ids, at) {
|
||||
/**
|
||||
* 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(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(ids.map((id) => [id, [{ epochMs: WORLD_MS }]])),
|
||||
records: { data: new Map(ids.map((id) => [id, {}])) },
|
||||
_positionHistory: new Map(),
|
||||
_cockpitNearContacts: new Set(),
|
||||
records: { data: records, missingPolls: new Map() },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
|
||||
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,
|
||||
placeAt: (id, wallMs, _info, _history, out) => {
|
||||
Object.assign(out, at(id, wallMs));
|
||||
return { courseDeg: 90, speedMps: 200 };
|
||||
},
|
||||
resolveAsset,
|
||||
});
|
||||
for (const id of ids)
|
||||
icons._createIcons(viewer);
|
||||
const here = fromDegrees(0, 30, 300);
|
||||
for (const id of records.keys()) {
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: at(id, WORLD_MS),
|
||||
motion: { kind: 'hold', courseDeg: 90 },
|
||||
course: 90,
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: -Infinity },
|
||||
{ id, pos: here, motion: { kind: 'hold', courseDeg: 0 }, size: [20, 20] },
|
||||
{ expiresAt: Infinity },
|
||||
);
|
||||
return { icons, set: state._icons };
|
||||
icons._applyIconPresentation(id);
|
||||
}
|
||||
return { state, icons, registered: draw.viewSheets, here, unbind };
|
||||
}
|
||||
|
||||
test('a placed fleet planned in one pass runs out spread over the passes after it, not together', (t) => {
|
||||
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 ids = Array.from({ length: 400 }, (_, i) =>
|
||||
(0xa00000 + i * 37).toString(16),
|
||||
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),
|
||||
);
|
||||
const { icons, set } = placedFleet(ids, () => fromDegrees(0, 30, 3_000));
|
||||
icons._replanExpired(Date.now());
|
||||
const ends = ids.map((id) => set.expires(id) - WORLD_MS);
|
||||
for (const ms of ends) assert.ok(ms >= 500 && ms < 1_500, `${ms} ms`);
|
||||
// An 80 ms pass (the fleet's tick) has an eighth of the fleet at most.
|
||||
const perPass = new Map();
|
||||
for (const ms of ends) {
|
||||
const pass = Math.floor(ms / 80);
|
||||
perPass.set(pass, (perPass.get(pass) ?? 0) + 1);
|
||||
}
|
||||
assert.ok(
|
||||
Math.max(...perPass.values()) <= ids.length / 8,
|
||||
`${Math.max(...perPass.values())} in one pass`,
|
||||
// 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),
|
||||
);
|
||||
// Planned again when it runs out, each runs as long as before, from then.
|
||||
const first = new Map(ids.map((id) => [id, set.expires(id)]));
|
||||
t.mock.timers.tick(1_500);
|
||||
icons._replanExpired(Date.now());
|
||||
for (const id of ids) {
|
||||
const item = set.item(id);
|
||||
assert.equal(item.motion.t0, Date.now(), id);
|
||||
assert.equal(
|
||||
set.expires(id) - Date.now(),
|
||||
first.get(id) - WORLD_MS,
|
||||
`${id} runs as long`,
|
||||
);
|
||||
}
|
||||
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('a placed contact far from the eye or out of view is planned for longer than a near one in view', (t) => {
|
||||
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 where = {
|
||||
n: fromDegrees(0, 30, 3_000),
|
||||
f: fromDegrees(10, 30, 3_000),
|
||||
o: fromDegrees(0.01, 30, 3_000),
|
||||
};
|
||||
const ids = Object.keys(where);
|
||||
const { icons, set } = placedFleet(ids, (id) => where[id]);
|
||||
const eye = fromDegrees(0, 30, 60_000);
|
||||
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
// In view: all but 'o', told apart by where the placement puts it.
|
||||
const view = { eye, inView: (p) => metres(p, where.o) > 1 };
|
||||
const length = (id) =>
|
||||
(set.expires(id) - set.item(id).motion.t0) / placedPlanSpread(id);
|
||||
icons._replanExpired(Date.now(), view);
|
||||
assert.ok(Math.abs(length('n') - 1_000) < 1, `near ${length('n')}`);
|
||||
assert.ok(Math.abs(length('f') - 4_000) < 1, `far ${length('f')}`);
|
||||
assert.ok(Math.abs(length('o') - 4_000) < 1, `out of view ${length('o')}`);
|
||||
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);
|
||||
});
|
||||
|
||||
// The camera is the pass's only: a contact planned after it, as a new
|
||||
// report plans it, takes a near plan, even after a pass that threw.
|
||||
icons._planIcon('f');
|
||||
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a pass ${length('f')}`);
|
||||
t.mock.timers.tick(5_000);
|
||||
assert.throws(() =>
|
||||
icons._replanExpired(Date.now(), {
|
||||
eye,
|
||||
inView: () => {
|
||||
throw new Error('camera gone');
|
||||
},
|
||||
}),
|
||||
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),
|
||||
);
|
||||
icons._planIcon('f');
|
||||
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a throw ${length('f')}`);
|
||||
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),
|
||||
);
|
||||
});
|
||||
@@ -14,12 +14,6 @@ import {
|
||||
showModel,
|
||||
} from './modelRecord.js';
|
||||
import { modelDrawnScale } from './modelVisualAnchor.js';
|
||||
import {
|
||||
createRenderPace,
|
||||
createScreenSpeed,
|
||||
paceHzForSpeed,
|
||||
} from '../renderPace.js';
|
||||
import { ROTOR_FPS } from './rotorFrames.js';
|
||||
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
|
||||
import { aircraftLayerPartState } from './modelPartDrivers.js';
|
||||
import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js';
|
||||
@@ -125,70 +119,6 @@ export function createAircraftModels({
|
||||
let instances = 0;
|
||||
/** The fleet items this tick wrote, sent together when it ends. */
|
||||
let pendingItems = [];
|
||||
|
||||
// The pace: how often the fleet is drawn while nothing else draws
|
||||
// (renderPace.js). The icons move on the GPU, so a frame is all a move
|
||||
// takes; an airliner crosses a hundredth of a pixel a second on the whole
|
||||
// globe and hundreds from close by, so the rate follows the fastest icon
|
||||
// in view.
|
||||
const pace = createRenderPace({ owner: setPrefix, render: services.render });
|
||||
const screenSpeed = createScreenSpeed();
|
||||
/** How often the icons' on-screen speed is read, in ms. */
|
||||
const PACE_READ_MS = 250;
|
||||
/** Each icon's move is read over this much of its drawn path, in ms. */
|
||||
const PACE_SPAN_MS = 1000;
|
||||
/** While icons fade for a focus change, they are drawn this often. */
|
||||
const PACE_FADE_HZ = 20;
|
||||
/** A rotor drawn this recently is in view. */
|
||||
const PACE_ROTOR_SEEN_MS = 600;
|
||||
let paceReadMs = -Infinity;
|
||||
let pacePxPerSec = 0;
|
||||
|
||||
/**
|
||||
* The fastest icon in view's speed on screen, in pixels a second: each
|
||||
* shown icon's drawn position now and PACE_SPAN_MS on, which takes in a
|
||||
* new fix being blended in as well as its flight.
|
||||
*/
|
||||
function _readIconSpeed(pose) {
|
||||
const icons = state._icons;
|
||||
if (!icons || !screenSpeed.begin(pose, _viewport().height)) return 0;
|
||||
const t = parts.icons._displayMs();
|
||||
for (const id of icons.ids()) {
|
||||
if (!icons.shown(id)) continue;
|
||||
screenSpeed.add(
|
||||
icons.position(id, t),
|
||||
icons.position(id, t + PACE_SPAN_MS),
|
||||
);
|
||||
}
|
||||
return screenSpeed.pxPerSec(PACE_SPAN_MS / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a second the fleet needs as the camera stands (the pace clamps
|
||||
* it to its range). Infinity: as often as the pace allows.
|
||||
*/
|
||||
function _paceHz(nowMs = Date.now()) {
|
||||
const pose = _pose();
|
||||
if (!pose?.position) return Infinity;
|
||||
// Models, and the Cockpit's contacts, are moved on every frame.
|
||||
if (
|
||||
state._cockpitContactMode ||
|
||||
state._models.size ||
|
||||
_modelRegimeActive(pose)
|
||||
)
|
||||
return Infinity;
|
||||
if (nowMs - paceReadMs >= PACE_READ_MS) {
|
||||
paceReadMs = nowMs;
|
||||
pacePxPerSec = _readIconSpeed(pose);
|
||||
}
|
||||
let hz = paceHzForSpeed(pacePxPerSec);
|
||||
if (state._iconFocusFading > 0 && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
|
||||
// A helicopter in view turns its rotor ROTOR_FPS times a second.
|
||||
const rotorAtMs = parts.icons._rotorDrawnAtMs?.() ?? -Infinity;
|
||||
if (nowMs - rotorAtMs < PACE_ROTOR_SEEN_MS && hz < ROTOR_FPS)
|
||||
hz = ROTOR_FPS;
|
||||
return hz;
|
||||
}
|
||||
/** The ground sample's exclusions, kept while the sets they name live. */
|
||||
let exclusions = null;
|
||||
|
||||
@@ -1022,7 +952,6 @@ export function createAircraftModels({
|
||||
}
|
||||
}
|
||||
state._icons?.flush();
|
||||
pace.set(_paceHz());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1041,14 +970,7 @@ export function createAircraftModels({
|
||||
|
||||
if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts();
|
||||
parts.icons._syncImageSwitch();
|
||||
// Far and out-of-view contacts are planned for longer (the camera says
|
||||
// which are which).
|
||||
parts.icons._replanExpired(
|
||||
t,
|
||||
pose?.position
|
||||
? { eye: pose.position, inView: (position) => inView(pose, position) }
|
||||
: null,
|
||||
);
|
||||
parts.icons._replanExpired(t);
|
||||
const renderTime = parts.motion._displayTimeAt(
|
||||
t,
|
||||
state._scratchFleetRenderTime,
|
||||
@@ -1214,11 +1136,5 @@ export function createAircraftModels({
|
||||
_handBackDeselected,
|
||||
_updateTrackedModel,
|
||||
_fleetTick,
|
||||
_paceHz,
|
||||
_startPace: () => {
|
||||
paceReadMs = -Infinity;
|
||||
pace.start();
|
||||
},
|
||||
_stopPace: pace.stop,
|
||||
};
|
||||
}
|
||||
@@ -114,14 +114,11 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
|
||||
};
|
||||
let now = 1_000_000;
|
||||
let iconRecedeSyncs = 0;
|
||||
const replanViews = [];
|
||||
const parts = {
|
||||
icons: {
|
||||
_displayMs: () => now,
|
||||
_syncImageSwitch() {},
|
||||
_replanExpired(_t, view) {
|
||||
replanViews.push(view);
|
||||
},
|
||||
_replanExpired() {},
|
||||
_focusIcons() {},
|
||||
_occluder: () => null,
|
||||
_aboveHorizon: () => true,
|
||||
@@ -163,9 +160,6 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
|
||||
failNextUpsert: () => (failNextUpsert = true),
|
||||
/** How often the icons were told to recede by the tuning as it is now. */
|
||||
iconRecedeSyncs: () => iconRecedeSyncs,
|
||||
/** The camera each fleet tick re-planned the icons with. */
|
||||
replanViews,
|
||||
eye,
|
||||
/** Mark a contact as not there yet at the time drawn, or there again. */
|
||||
setUnseen(id, value) {
|
||||
if (value) unseenIds.add(id);
|
||||
@@ -482,15 +476,3 @@ test('the selected contact keeps a loaded, hidden fleet model that takes it back
|
||||
assert.equal(f.fleet().items.get('a1').show, true);
|
||||
assert.equal(f.shown.get('a1'), false);
|
||||
});
|
||||
|
||||
test('the fleet tick re-plans the icons with the camera: its eye, and what it sees', () => {
|
||||
const f = fleetFixture(new Map([['a1', far(1)]]));
|
||||
f.tick();
|
||||
const [view] = f.replanViews;
|
||||
assert.equal(view.eye, f.eye);
|
||||
// The camera looks along -z: ahead of the eye is in view, behind it not.
|
||||
const ahead = { x: f.eye.x, y: f.eye.y, z: f.eye.z - 10_000 };
|
||||
const behind = { x: f.eye.x, y: f.eye.y, z: f.eye.z + 10_000 };
|
||||
assert.equal(view.inView(ahead), true);
|
||||
assert.equal(view.inView(behind), false);
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* @module data/aircraftViews
|
||||
* @description Which block of the aircraft view sheet (`viewSheet.js`) a
|
||||
* contact's icon draws from. Each aircraft class is rendered there from a
|
||||
* sphere of camera angles; a renderer with the `viewSheets` capability lays
|
||||
* the icon flat on the earth along its course and draws the view that
|
||||
* matches where the eye is, so an oblique contact looks solid instead of
|
||||
* like a paper cut-out. Only an icon drawn along its course
|
||||
* (`rotationMode: 'course'`) can do this: a screen-rotated or upright icon
|
||||
* keeps its flat glyph. Kinds with no rendered views (the TR-3B triangle,
|
||||
* airport vehicles, ground stations) keep their flat glyph as well.
|
||||
*/
|
||||
import { AIRCRAFT_VIEWS } from './viewSheet.js';
|
||||
import {
|
||||
aircraftIcon,
|
||||
FLEET_ICON_PX,
|
||||
ROTOR_FRAMES,
|
||||
ROTOR_STILL_FRAME,
|
||||
} from './aircraftIcons.js';
|
||||
|
||||
/** The renderer capability that draws view sheets. */
|
||||
export const VIEW_SHEETS_CAPABILITY = 'viewSheets';
|
||||
|
||||
/** Kinds drawn from the sheet with one block each (helicopters have three). */
|
||||
const STILL_KINDS = new Set([
|
||||
'airliner',
|
||||
'widebody',
|
||||
'quadjet',
|
||||
'turboprop',
|
||||
'light',
|
||||
'glider',
|
||||
'fastjet',
|
||||
'bizjet',
|
||||
'uav',
|
||||
]);
|
||||
|
||||
/** One frozen image ref per block, so equal refs are the same object. */
|
||||
const refs = new Map();
|
||||
|
||||
/**
|
||||
* The ref of the block at `first`, with the flat glyph of `kind` (and its
|
||||
* rotor `frame`) as its fallback: what the renderer draws until the sheet
|
||||
* has loaded, and for good if it cannot load.
|
||||
*/
|
||||
function refAt(first, kind, frame) {
|
||||
let ref = refs.get(first);
|
||||
if (!ref) {
|
||||
ref = Object.freeze({
|
||||
views: AIRCRAFT_VIEWS.id,
|
||||
first,
|
||||
fallback: aircraftIcon(kind, FLEET_ICON_PX, frame),
|
||||
});
|
||||
refs.set(first, ref);
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
/**
|
||||
* The view image of an icon kind: `{views, first, fallback}`, the sheet's
|
||||
* id, the first cell of the kind's block and its flat glyph (drawn while
|
||||
* the sheet loads, or if it fails), or null for a kind with no views.
|
||||
* @param {string} kind An icon kind (`rendering._iconKind`).
|
||||
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
|
||||
* (the still frame otherwise, as `aircraftIcon` takes it).
|
||||
* @returns {{views: string, first: number, fallback: string}|null}
|
||||
*/
|
||||
export function aircraftViewRef(kind, frame) {
|
||||
const subjects = AIRCRAFT_VIEWS.subjects;
|
||||
if (kind === 'helicopter') {
|
||||
const f =
|
||||
Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
|
||||
? frame
|
||||
: ROTOR_STILL_FRAME;
|
||||
const first = subjects[`helicopter${f}`];
|
||||
return Number.isInteger(first) ? refAt(first, kind, f) : null;
|
||||
}
|
||||
if (!STILL_KINDS.has(kind)) return null;
|
||||
const first = subjects[kind];
|
||||
return Number.isInteger(first) ? refAt(first, kind) : null;
|
||||
}
|
||||
|
||||
/** Whether an icon image is a view-sheet ref. */
|
||||
export function isAircraftViewRef(image) {
|
||||
return Boolean(image) && typeof image === 'object' && 'views' in image;
|
||||
}
|
||||
|
||||
/** Draw ports the sheet is registered on. */
|
||||
const registered = new WeakSet();
|
||||
|
||||
/**
|
||||
* Register the aircraft view sheet on a draw port, once per port, when its
|
||||
* renderer draws view sheets, its image URL resolved as the layer resolves
|
||||
* its other assets (the fleet models'). Safe to call any number of times.
|
||||
* @param {{views?: Function}|null} drawPort
|
||||
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
|
||||
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
|
||||
* resolver.
|
||||
* @returns {boolean} Whether icons on this port can draw views.
|
||||
*/
|
||||
export function registerAircraftViews(
|
||||
drawPort,
|
||||
capabilities,
|
||||
resolveAsset = (url) => url,
|
||||
) {
|
||||
if (!drawPort || typeof drawPort.views !== 'function') return false;
|
||||
if (!capabilities?.has?.(VIEW_SHEETS_CAPABILITY)) return false;
|
||||
if (!registered.has(drawPort)) {
|
||||
const sheet = AIRCRAFT_VIEWS.sheet;
|
||||
drawPort.views(AIRCRAFT_VIEWS.id, {
|
||||
...sheet,
|
||||
image: resolveAsset(sheet.image),
|
||||
});
|
||||
registered.add(drawPort);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* An icon's look drawn from the view sheet where it can be: with views on,
|
||||
* the item drawn along its course and the kind rendered, the image is the
|
||||
* view ref and there is no near image (`imageLod: undefined`, so an update
|
||||
* clears it); otherwise the look as given, the very same object.
|
||||
* @template {{image: unknown, imageLod?: unknown}} T
|
||||
* @param {T} look
|
||||
* @param {object} options
|
||||
* @param {boolean} options.views Whether the renderer draws views
|
||||
* (`registerAircraftViews`).
|
||||
* @param {string} options.kind The icon kind.
|
||||
* @param {number} [options.frame] A helicopter's rotor frame.
|
||||
* @param {string} [options.rotationMode] How the item is rotated.
|
||||
* @returns {T}
|
||||
*/
|
||||
export function withAircraftView(look, { views, kind, frame, rotationMode }) {
|
||||
if (!views || rotationMode !== 'course') return look;
|
||||
const ref = aircraftViewRef(kind, frame);
|
||||
if (!ref) return look;
|
||||
return { ...look, image: ref, imageLod: undefined };
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
aircraftViewRef,
|
||||
isAircraftViewRef,
|
||||
registerAircraftViews,
|
||||
VIEW_SHEETS_CAPABILITY,
|
||||
withAircraftView,
|
||||
} from './aircraftViews.js';
|
||||
import { AIRCRAFT_VIEWS } from './viewSheet.js';
|
||||
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './rotorFrames.js';
|
||||
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
|
||||
|
||||
const STILL_KINDS = [
|
||||
'airliner',
|
||||
'widebody',
|
||||
'quadjet',
|
||||
'turboprop',
|
||||
'light',
|
||||
'glider',
|
||||
'fastjet',
|
||||
'bizjet',
|
||||
'uav',
|
||||
];
|
||||
|
||||
test('every aircraft class draws its own block of the view sheet', () => {
|
||||
for (const kind of STILL_KINDS)
|
||||
assert.deepEqual(
|
||||
aircraftViewRef(kind),
|
||||
{
|
||||
views: AIRCRAFT_VIEWS.id,
|
||||
first: AIRCRAFT_VIEWS.subjects[kind],
|
||||
fallback: aircraftIcon(kind, FLEET_ICON_PX),
|
||||
},
|
||||
kind,
|
||||
);
|
||||
const firsts = STILL_KINDS.map((kind) => aircraftViewRef(kind).first);
|
||||
assert.equal(
|
||||
new Set(firsts).size,
|
||||
STILL_KINDS.length,
|
||||
'no two share a block',
|
||||
);
|
||||
assert.equal(
|
||||
aircraftViewRef('airliner'),
|
||||
aircraftViewRef('airliner'),
|
||||
'one ref per block, so an unchanged image writes nothing',
|
||||
);
|
||||
assert.ok(Object.isFrozen(aircraftViewRef('airliner')));
|
||||
});
|
||||
|
||||
test('a helicopter draws the block of its rotor frame, the still frame by default', () => {
|
||||
assert.equal(ROTOR_FRAMES, 3);
|
||||
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
|
||||
const ref = aircraftViewRef('helicopter', frame);
|
||||
assert.equal(
|
||||
ref.first,
|
||||
AIRCRAFT_VIEWS.subjects[`helicopter${frame}`],
|
||||
`frame ${frame}`,
|
||||
);
|
||||
assert.equal(
|
||||
ref.fallback,
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, frame),
|
||||
`its fallback is the glyph of rotor frame ${frame}`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
aircraftViewRef('helicopter').fallback,
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
const still = AIRCRAFT_VIEWS.subjects[`helicopter${ROTOR_STILL_FRAME}`];
|
||||
for (const frame of [undefined, -1, 3, 1.5, NaN])
|
||||
assert.equal(aircraftViewRef('helicopter', frame).first, still, `${frame}`);
|
||||
});
|
||||
|
||||
test('the TR-3B, airport vehicles, ground stations and unknown kinds have no views', () => {
|
||||
for (const kind of [
|
||||
'tr3b',
|
||||
'tr3bHot',
|
||||
'vehicle',
|
||||
'station',
|
||||
'jet',
|
||||
'',
|
||||
undefined,
|
||||
])
|
||||
assert.equal(aircraftViewRef(kind), null, String(kind));
|
||||
assert.equal(
|
||||
aircraftViewRef('airliner', 1).first,
|
||||
0,
|
||||
'a frame means nothing to a fixed wing',
|
||||
);
|
||||
});
|
||||
|
||||
test('a view ref is told apart from flat images', () => {
|
||||
assert.equal(isAircraftViewRef(aircraftViewRef('glider')), true);
|
||||
for (const image of [
|
||||
'data:image/svg+xml;base64,AAA',
|
||||
null,
|
||||
undefined,
|
||||
{ atlas: 'a', slot: 's' },
|
||||
])
|
||||
assert.equal(isAircraftViewRef(image), false, String(image));
|
||||
});
|
||||
|
||||
test('the sheet is registered once per draw port, only with the capability', () => {
|
||||
const calls = [];
|
||||
const port = { views: (id, sheet) => calls.push([id, sheet]) };
|
||||
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
|
||||
assert.equal(VIEW_SHEETS_CAPABILITY, 'viewSheets');
|
||||
assert.equal(registerAircraftViews(port, new Set()), false);
|
||||
assert.equal(registerAircraftViews(port, null), false);
|
||||
assert.equal(calls.length, 0, 'nothing registered without the capability');
|
||||
assert.equal(registerAircraftViews(port, caps), true);
|
||||
assert.equal(registerAircraftViews(port, caps), true);
|
||||
assert.deepEqual(calls, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
|
||||
const other = { views: (id) => calls.push([id]) };
|
||||
assert.equal(registerAircraftViews(other, caps), true);
|
||||
assert.equal(calls.length, 2, 'a second port registers its own');
|
||||
assert.equal(
|
||||
registerAircraftViews({}, caps),
|
||||
false,
|
||||
'a port without views()',
|
||||
);
|
||||
assert.equal(registerAircraftViews(null, caps), false);
|
||||
});
|
||||
|
||||
test('a look takes the view only when views are on and it is drawn along its course', () => {
|
||||
const look = {
|
||||
image: 'flat',
|
||||
imageLod: { near: 'near', switchPx: 30 },
|
||||
size: [20, 20],
|
||||
scale: 1.5,
|
||||
};
|
||||
const on = { views: true, kind: 'airliner', rotationMode: 'course' };
|
||||
const viewed = withAircraftView(look, on);
|
||||
assert.deepEqual(viewed, {
|
||||
image: aircraftViewRef('airliner'),
|
||||
imageLod: undefined,
|
||||
size: [20, 20],
|
||||
scale: 1.5,
|
||||
});
|
||||
assert.ok('imageLod' in viewed, 'imageLod is cleared, so an update drops it');
|
||||
assert.equal(look.image, 'flat', 'the look given is left as it was');
|
||||
assert.equal(withAircraftView(look, { ...on, views: false }), look);
|
||||
assert.equal(withAircraftView(look, { ...on, rotationMode: 'screen' }), look);
|
||||
assert.equal(
|
||||
withAircraftView(look, { ...on, rotationMode: undefined }),
|
||||
look,
|
||||
);
|
||||
assert.equal(withAircraftView(look, { ...on, kind: 'tr3b' }), look);
|
||||
assert.equal(withAircraftView(look, { ...on, kind: 'station' }), look);
|
||||
assert.equal(
|
||||
withAircraftView(look, { ...on, kind: 'helicopter', frame: 2 }).image,
|
||||
aircraftViewRef('helicopter', 2),
|
||||
);
|
||||
});
|
||||
|
||||
test('the sheet is registered with its image resolved as the layer resolves its assets', () => {
|
||||
const calls = [];
|
||||
const port = { views: (id, sheet) => calls.push([id, sheet]) };
|
||||
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
|
||||
registerAircraftViews(port, caps, (url) => `https://cdn.example/app${url}`);
|
||||
assert.equal(calls.length, 1);
|
||||
const [id, sheet] = calls[0];
|
||||
assert.equal(id, AIRCRAFT_VIEWS.id);
|
||||
assert.equal(
|
||||
sheet.image,
|
||||
'https://cdn.example/app/sprites/aircraft-views.webp',
|
||||
);
|
||||
assert.deepEqual(
|
||||
{ ...sheet, image: AIRCRAFT_VIEWS.sheet.image },
|
||||
{ ...AIRCRAFT_VIEWS.sheet },
|
||||
'the layout as it is',
|
||||
);
|
||||
assert.equal(AIRCRAFT_VIEWS.sheet.image, '/sprites/aircraft-views.webp');
|
||||
});
|
||||
@@ -64,8 +64,7 @@ export const ANALYST_LAYERS = Object.freeze(
|
||||
|
||||
/** Fields every record carries regardless of layer. */
|
||||
const COMMON_FIELDS = Object.freeze(['id', 'lat', 'lon']);
|
||||
/** Derived per-record field for layers with a time field (hours before the
|
||||
* moment the layer's records show: now, or its past snapshot's time). */
|
||||
/** Derived per-record field for layers with a time field (hours before now). */
|
||||
const AGE_FIELD = 'ageHours';
|
||||
/** Spatial scope kinds `query()` accepts. */
|
||||
const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
@@ -583,8 +582,6 @@ function offerTop(top, candidate, limit, dir) {
|
||||
* engine and the Contacts-window path so both format and rank alike.
|
||||
* @param {Array<{key: string, rows: object[]}>} groups Candidate rows.
|
||||
* @param {object} options
|
||||
* @param {Map<string, number|null>} [options.recordsAt] Per-layer snapshot times in epoch ms.
|
||||
* Ages count from the layer’s snapshot time when given, otherwise from now.
|
||||
* @returns {Promise<object|null>} Selection, or null when cancelled.
|
||||
*/
|
||||
export async function selectAnalystRows(
|
||||
@@ -598,7 +595,6 @@ export async function selectAnalystRows(
|
||||
ref = null,
|
||||
inScope = null,
|
||||
now = Date.now(),
|
||||
recordsAt = null,
|
||||
isCurrent = () => true,
|
||||
distanceOf = null,
|
||||
} = {},
|
||||
@@ -607,10 +603,8 @@ export async function selectAnalystRows(
|
||||
const ageOf = (key, row) => {
|
||||
const field = timeFieldOf(key);
|
||||
const t = field ? row[field] : null;
|
||||
const from = recordsAt?.get(key);
|
||||
const ref = Number.isFinite(from) ? from : now;
|
||||
return Number.isFinite(t)
|
||||
? Math.round(((ref - t) / 3_600_000) * 10) / 10
|
||||
? Math.round(((now - t) / 3_600_000) * 10) / 10
|
||||
: null;
|
||||
};
|
||||
const distance = (row) => {
|
||||
@@ -777,7 +771,6 @@ export function createAnalystEngine(providers) {
|
||||
spec = normalized.spec;
|
||||
|
||||
// 1) Source records, grouped by layer and never copied.
|
||||
const recordsAt = followUp ? lastResult.recordsAt : new Map();
|
||||
let groups;
|
||||
let layersQueried;
|
||||
let queriedSnapshots;
|
||||
@@ -793,7 +786,6 @@ export function createAnalystEngine(providers) {
|
||||
queriedSnapshots = [];
|
||||
for (const key of layers) {
|
||||
const rows = providers.getRecords(key) || [];
|
||||
recordsAt.set(key, providers.getRecordsAt?.(key) ?? null);
|
||||
const snapshot = providers.getLayerSnapshot?.(key);
|
||||
if (snapshot) queriedSnapshots.push(snapshot);
|
||||
const coverage = providers.getRecordCoverage?.(key, rows) || {};
|
||||
@@ -1056,7 +1048,6 @@ export function createAnalystEngine(providers) {
|
||||
: null,
|
||||
inScope,
|
||||
now: providers.now?.() ?? Date.now(),
|
||||
recordsAt,
|
||||
isCurrent,
|
||||
});
|
||||
if (!selection || !isCurrent()) return cancelled();
|
||||
@@ -1156,7 +1147,6 @@ export function createAnalystEngine(providers) {
|
||||
if (!isCurrent()) return cancelled();
|
||||
lastResult = {
|
||||
matched: memoryOverride?.matched || selection.matched,
|
||||
recordsAt,
|
||||
distanceOf: memoryOverride?.distanceOf || rememberedDistanceOf,
|
||||
layerKeys: [...(memoryOverride?.layerKeys || layers)],
|
||||
coverage: memoryOverride?.coverage || result.coverage,
|
||||
|
||||
@@ -896,24 +896,6 @@ test('time fields filter by ISO and derive ageHours; the feed window is exposed'
|
||||
assert.equal(age.coverage.layersQueried[0].window, 'last 24 h');
|
||||
});
|
||||
|
||||
test('perimeter age follows the snapshot time of the remembered rows', async () => {
|
||||
const discoveredTime = Date.UTC(2024, 6, 1);
|
||||
let at = Date.UTC(2024, 6, 2);
|
||||
const engine = createAnalystEngine({
|
||||
now: () => Date.UTC(2026, 6, 2),
|
||||
getRecords: () => [{ id: 'Pine', discoveredTime }],
|
||||
getRecordsAt: () => at,
|
||||
});
|
||||
const first = await engine.query({
|
||||
layers: ['fire-perimeters'],
|
||||
scope: { kind: 'anywhere' },
|
||||
});
|
||||
assert.equal(first.items[0].ageHours, 24);
|
||||
at = null;
|
||||
const followUp = await engine.query({ followUp: true });
|
||||
assert.equal(followUp.items[0].ageHours, 24);
|
||||
});
|
||||
|
||||
test('follow-up provenance stays attached to old rows after a feed recovers', async () => {
|
||||
let state = 'stale';
|
||||
const engine = createAnalystEngine({
|
||||
|
||||
@@ -34,7 +34,6 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { PACE_MIN_HZ } from '../renderPace.js';
|
||||
|
||||
import {
|
||||
DETECTION_ENABLE_FADE_MS,
|
||||
@@ -449,34 +448,31 @@ test('the render-governor gate covers the parked case, with teeth on the painter
|
||||
// until some unrelated frame happens along.
|
||||
//
|
||||
// It cannot, and the reason is structural rather than lucky: an AIR bracket can
|
||||
// only exist while an aircraft layer is enabled, and both aircraft layers pace
|
||||
// the render loop for their fleet (src/renderPace.js): never fewer than
|
||||
// PACE_MIN_HZ frames a second however still the camera, more as the fleet
|
||||
// moves faster on screen. So for exactly as long as there is anything to
|
||||
// bracket, the scene keeps drawing and the overlay repaints with it, at most a
|
||||
// third of a second behind. (Before the pace the layers held the loop on every
|
||||
// frame; measured live 2026-08-23 on a parked camera, an outside-aircraft
|
||||
// population change moved the painted bracket count with no camera input.)
|
||||
// only exist while an aircraft layer is enabled, and both aircraft layers take a
|
||||
// continuous-render hold for their own per-frame fleet animation. So for exactly
|
||||
// as long as there is anything to bracket, the scene is rendering every frame
|
||||
// and the overlay repaints with it. (Measured live 2026-08-23 on a parked
|
||||
// camera: an outside-aircraft population change moved the painted bracket count
|
||||
// with no camera input, holds = ["flights"], requestRenderMode = false.)
|
||||
//
|
||||
// That is a COUPLING, so it deserves a pin. If a later perf pass stops the
|
||||
// aircraft layers pacing, or lets the pace's floor reach zero, bracket
|
||||
// That is a COUPLING, so it deserves a pin. If a later perf pass strips these
|
||||
// holds the way it stripped detection's — a reasonable-looking change — bracket
|
||||
// promptness goes with them, silently. This test is where that shows up.
|
||||
test('aircraft brackets stay prompt because the aircraft layers pace the render loop', async () => {
|
||||
assert.ok(PACE_MIN_HZ >= 3, 'a still scene still draws a few times a second');
|
||||
test('aircraft brackets stay prompt because the aircraft layers hold the render loop', async () => {
|
||||
for (const file of ['./flights.js', './militaryFlights.js']) {
|
||||
const source = readLayerSource(new URL(file, import.meta.url));
|
||||
const enable = /\n([ \t]*)enable\([\s\S]*?\n\1\},/.exec(source)?.[0];
|
||||
assert.ok(enable, `${file}: enable() is still identifiable`);
|
||||
assert.match(
|
||||
enable,
|
||||
/parts\.rendering\._startPace\(\)/,
|
||||
`${file}: enabling the layer must start its pace — detection no longer ` +
|
||||
'holds the loop, so this is what keeps its AIR brackets repainting on a parked scene',
|
||||
/holdContinuousRender\('(flights|military)'\)/,
|
||||
`${file}: enabling the layer must hold continuous render — detection no longer ` +
|
||||
'holds one, so this is what keeps its AIR brackets repainting on a parked scene',
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/parts\.rendering\._stopPace\(\)/,
|
||||
`${file}: and the pace must be stopped, or the governor can never idle`,
|
||||
/releaseContinuousRender\('(flights|military)'\)/,
|
||||
`${file}: and the hold must be released, or the governor can never idle`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -57,34 +57,6 @@ function install(options = {}, hook = 'configureServer') {
|
||||
};
|
||||
}
|
||||
|
||||
test('the WFIGS query asks for the mapping and edit times, and rows keep both', async () => {
|
||||
let url;
|
||||
const request = install({
|
||||
now: () => 1234,
|
||||
fetchImpl: async (input) => {
|
||||
url = new URL(input);
|
||||
return Response.json({
|
||||
features: [
|
||||
{
|
||||
...feature('timed'),
|
||||
properties: {
|
||||
attr_UniqueFireIdentifier: 'timed',
|
||||
poly_PolygonDateTime: 100,
|
||||
poly_DateCurrent: 200,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
const res = await request();
|
||||
const fields = url.searchParams.get('outFields').split(',');
|
||||
assert.ok(fields.includes('poly_PolygonDateTime'));
|
||||
assert.ok(fields.includes('poly_DateCurrent'));
|
||||
assert.equal(res.body.rows[0].polygonTime, 100);
|
||||
assert.equal(res.body.rows[0].updatedTime, 200);
|
||||
});
|
||||
|
||||
for (const hook of ['configureServer', 'configurePreviewServer']) {
|
||||
test(`${hook}: paging stops at five pages and normalizes the combined snapshot`, async () => {
|
||||
const calls = [];
|
||||
|
||||
+7
-11
@@ -42,8 +42,8 @@ export const MAX_ICON_SLOTS = 176;
|
||||
export const MIN_ICON_SLOTS = 64;
|
||||
/**
|
||||
* Vertex uniform vectors the icon shader keeps for everything else: its own
|
||||
* and the renderer's (about 34), with room for drivers that keep constants
|
||||
* in uniforms.
|
||||
* and the renderer's (about 45, the view sheet's layout among them), with
|
||||
* room for drivers that keep constants in uniforms.
|
||||
*/
|
||||
const OTHER_VERTEX_UNIFORMS = 80;
|
||||
|
||||
@@ -65,10 +65,7 @@ const START_SIZE_PX = 1024;
|
||||
const MAX_SIZE_PX = 4096;
|
||||
|
||||
function createAtlas() {
|
||||
// By URL, then by size: a URL is hashed once as it is, where a key built
|
||||
// from it would be a new string to hash on every look-up (an SVG data URL
|
||||
// runs to kilobytes, and a fleet's write looks up two a row).
|
||||
const slotsOfUrl = new Map();
|
||||
const slotOfKey = new Map();
|
||||
const entries = [];
|
||||
const listeners = new Set();
|
||||
const atlas = {
|
||||
@@ -93,8 +90,8 @@ function createAtlas() {
|
||||
* @returns {number}
|
||||
*/
|
||||
slot(url, sizePx, source) {
|
||||
let bySize = slotsOfUrl.get(url);
|
||||
const known = bySize?.get(sizePx);
|
||||
const key = `${sizePx}|${url}`;
|
||||
const known = slotOfKey.get(key);
|
||||
if (known !== undefined) return known;
|
||||
if (entries.length >= MAX_ICON_SLOTS)
|
||||
throw new RangeError(
|
||||
@@ -103,8 +100,7 @@ function createAtlas() {
|
||||
const slot = entries.length;
|
||||
const entry = { url, sizePx, image: null, x: 0, y: 0 };
|
||||
entries.push(entry);
|
||||
if (!bySize) slotsOfUrl.set(url, (bySize = new Map()));
|
||||
bySize.set(sizePx, slot);
|
||||
slotOfKey.set(key, slot);
|
||||
if (source) placeLoaded(entry, source);
|
||||
else load(entry);
|
||||
return slot;
|
||||
@@ -112,7 +108,7 @@ function createAtlas() {
|
||||
|
||||
/** Whether `url` at `sizePx` already has a slot. */
|
||||
has(url, sizePx) {
|
||||
return slotsOfUrl.get(url)?.has(sizePx) === true;
|
||||
return slotOfKey.has(`${sizePx}|${url}`);
|
||||
},
|
||||
|
||||
/** Whether a slot's image is packed and drawable. */
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { iconAtlas } from './iconAtlas.js';
|
||||
|
||||
test('an atlas slot is one per image and size, and has() agrees with slot()', () => {
|
||||
const url = `data:image/svg+xml;charset=utf-8,${'%3Csvg%3E'.repeat(400)}#slots`;
|
||||
const other = `${url}-other`;
|
||||
assert.equal(iconAtlas.has(url, 20), false);
|
||||
const small = iconAtlas.slot(url, 20);
|
||||
assert.equal(iconAtlas.has(url, 20), true);
|
||||
assert.equal(iconAtlas.slot(url, 20), small, 'the same image and size');
|
||||
// A copy of the URL, not the same string, finds it too.
|
||||
assert.equal(iconAtlas.slot(url.slice(0), 20), small);
|
||||
assert.equal(iconAtlas.has(url, 40), false, 'another size is another slot');
|
||||
const large = iconAtlas.slot(url, 40);
|
||||
assert.notEqual(large, small);
|
||||
assert.equal(iconAtlas.has(url, 40), true);
|
||||
assert.equal(
|
||||
iconAtlas.has(other, 20),
|
||||
false,
|
||||
'another image is another slot',
|
||||
);
|
||||
assert.notEqual(iconAtlas.slot(other, 20), small);
|
||||
});
|
||||
@@ -100,6 +100,12 @@ export const ICON_RECEDES = 4;
|
||||
* −31 m before its floor warms) otherwise reads as beyond the limb.
|
||||
*/
|
||||
export const ICON_CULL_LIFT = 8;
|
||||
/**
|
||||
* The row's image is a subject of the set's view sheet
|
||||
* ({@link module:viewSheet}): its far image is the subject's first cell, and
|
||||
* the renderer draws the frame that shows it from the eye.
|
||||
*/
|
||||
export const ICON_VIEWS = 16;
|
||||
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
|
||||
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
|
||||
/**
|
||||
|
||||
@@ -15,8 +15,14 @@
|
||||
* pick names the set and the contact's id, as the fleet icons' do.
|
||||
* `visible` hides the icon while it stays shown (Cockpit flies the
|
||||
* aircraft from its own seat).
|
||||
*
|
||||
* Given a view-sheet image (`aircraftViews.js`) and a course reader, it is
|
||||
* drawn along that course instead (`rotationMode: 'course'`), as the fleet
|
||||
* icons are, so the renderer draws the view of the aircraft that matches
|
||||
* the eye and tracking a contact does not flatten it.
|
||||
*/
|
||||
import { findDraw, findFrame } from '../render/rendererOf.js';
|
||||
import { isAircraftViewRef } from './aircraftViews.js';
|
||||
|
||||
/** Uniquifier for the sets' ids. */
|
||||
let instances = 0;
|
||||
@@ -105,18 +111,21 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
|
||||
function draw() {
|
||||
if (!shown || !set) return;
|
||||
const pos = shown.position();
|
||||
const alongCourse =
|
||||
typeof shown.course === 'function' && isAircraftViewRef(shown.image);
|
||||
const item = {
|
||||
id: shown.id,
|
||||
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
|
||||
show: Boolean(pos) && visible,
|
||||
image: shown.image,
|
||||
...(shown.imageLod ? { imageLod: shown.imageLod } : {}),
|
||||
...(shown.imageLod && !alongCourse ? { imageLod: shown.imageLod } : {}),
|
||||
size: [shown.sprite.width, shown.sprite.height],
|
||||
scale: shown.sprite.scale,
|
||||
scaleByDistance: shown.sprite.scaleByDistance,
|
||||
color: shown.color(),
|
||||
rotationMode: 'screen',
|
||||
rotation: pos ? shown.rotation() : 0,
|
||||
...(alongCourse
|
||||
? { rotationMode: 'course', course: pos ? shown.course() : 0 }
|
||||
: { rotationMode: 'screen', rotation: pos ? shown.rotation() : 0 }),
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
};
|
||||
if (
|
||||
@@ -132,7 +141,9 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
|
||||
written.size[0] === item.size[0] &&
|
||||
written.size[1] === item.size[1] &&
|
||||
written.scale === item.scale &&
|
||||
written.rotationMode === item.rotationMode &&
|
||||
written.rotation === item.rotation &&
|
||||
written.course === item.course &&
|
||||
sameColor(written.color, item.color)
|
||||
)
|
||||
return;
|
||||
@@ -146,13 +157,17 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
|
||||
* next one on.
|
||||
* @param {object} target
|
||||
* @param {string} target.id The contact's id.
|
||||
* @param {string} target.image
|
||||
* @param {string|{views: string, first: number}} target.image A flat
|
||||
* glyph, or a view-sheet image (drawn along `course`).
|
||||
* @param {{near: string, switchPx: number}} [target.imageLod] The
|
||||
* sharper image it switches to once drawn larger than `switchPx`.
|
||||
* sharper image a flat glyph switches to once drawn larger than
|
||||
* `switchPx`.
|
||||
* @param {{width: number, height: number, scale: number,
|
||||
* scaleByDistance: object}} target.sprite Read each frame.
|
||||
* @param {() => object|null} target.position ECEF this frame; none hides it.
|
||||
* @param {() => number} target.rotation Screen radians, counter-clockwise.
|
||||
* @param {() => number} [target.course] Degrees clockwise from north;
|
||||
* required with a view-sheet image, which only draws along a course.
|
||||
* @param {() => object} target.color The tint this frame.
|
||||
*/
|
||||
show(target) {
|
||||
|
||||
@@ -199,3 +199,52 @@ test('the tracked icon keeps its contact\'s colour; only the alpha changes', ()
|
||||
assert.ok(Object.isFrozen(stale));
|
||||
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
|
||||
});
|
||||
|
||||
test('given a view-sheet image and a course, the tracked icon is drawn along its course with no near image', async () => {
|
||||
const { aircraftViewRef } = await import('./aircraftViews.js');
|
||||
const { viewer, draw, tick } = harness();
|
||||
const icon = createTrackedAircraftIcon({
|
||||
viewer: () => viewer,
|
||||
setPrefix: 'flights',
|
||||
});
|
||||
let course = 45;
|
||||
let rotations = 0;
|
||||
icon.show({
|
||||
id: 'abc123',
|
||||
image: aircraftViewRef('airliner'),
|
||||
imageLod: { near: 'near', switchPx: 30 },
|
||||
sprite: SPRITE,
|
||||
position: () => ({ x: 1, y: 2, z: 3 }),
|
||||
rotation: () => {
|
||||
rotations++;
|
||||
return 0.5;
|
||||
},
|
||||
course: () => course,
|
||||
color: () => [0, 1, 1, 1],
|
||||
});
|
||||
const set = draw.find('flights-tracked-icon:');
|
||||
tick();
|
||||
const item = set.items.get('abc123');
|
||||
assert.equal(item.image, aircraftViewRef('airliner'));
|
||||
assert.equal('imageLod' in item, false);
|
||||
assert.equal(item.rotationMode, 'course');
|
||||
assert.equal(item.course, 45);
|
||||
assert.equal('rotation' in item, false);
|
||||
assert.equal(rotations, 0, 'no screen rotation is projected');
|
||||
assert.deepEqual(item.size, [28, 28]);
|
||||
const writes = set.writes;
|
||||
tick();
|
||||
assert.equal(set.writes, writes, 'an unchanged frame writes nothing');
|
||||
course = 50;
|
||||
tick();
|
||||
assert.equal(set.items.get('abc123').course, 50);
|
||||
// A flat image (a TR-3B conversion, a ground station) turns on screen again.
|
||||
icon.setImage('data:image/svg+xml;base64,AAA', { near: 'near', switchPx: 30 });
|
||||
tick();
|
||||
const flat = set.items.get('abc123');
|
||||
assert.equal(flat.rotationMode, 'screen');
|
||||
assert.equal(flat.rotation, 0.5);
|
||||
assert.deepEqual(flat.imageLod, { near: 'near', switchPx: 30 });
|
||||
assert.equal('course' in flat, false);
|
||||
icon.dispose();
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* @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/build-aircraft-view-sheet.py` bakes the aircraft sheet to
|
||||
* this layout; a renderer with the `viewSheets` capability draws it.
|
||||
*
|
||||
* **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,
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,379 @@
|
||||
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,
|
||||
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/build-aircraft-view-sheet.py',
|
||||
import.meta.url,
|
||||
);
|
||||
const MANIFEST = new URL(
|
||||
'../../public/sprites/aircraft-views.json',
|
||||
import.meta.url,
|
||||
);
|
||||
|
||||
test('the bake script lays the sheet out as AIRCRAFT_VIEWS says', () => {
|
||||
const script = readFileSync(BAKE, 'utf8');
|
||||
const constant = (name) => {
|
||||
const match = new RegExp(`^${name} = (.+)$`, 'm').exec(script);
|
||||
assert.ok(match, `${name} in the bake script`);
|
||||
return JSON.parse(match[1]);
|
||||
};
|
||||
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
|
||||
assert.equal(constant('RING_STEP_DEG'), sheet.ringStepDeg);
|
||||
assert.deepEqual(constant('RINGS'), [...sheet.rings]);
|
||||
assert.equal(constant('COLUMNS'), sheet.columns);
|
||||
const list = /^SUBJECTS = \[([\s\S]*?)^\]/m.exec(script);
|
||||
assert.ok(list, 'SUBJECTS in the bake script');
|
||||
const names = [...list[1].matchAll(/^\s*\("(\w+)",/gm)].map((m) => m[1]);
|
||||
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);
|
||||
});
|
||||
|
||||
test(
|
||||
'the baked manifest matches AIRCRAFT_VIEWS',
|
||||
{ skip: !existsSync(MANIFEST) && 'no public/sprites/aircraft-views.json' },
|
||||
() => {
|
||||
const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
|
||||
const { sheet, subjects } = AIRCRAFT_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, 'aircraft-views.webp');
|
||||
assert.deepEqual(Object.keys(manifest.subjects), Object.keys(subjects));
|
||||
for (const [name, first] of Object.entries(subjects))
|
||||
assert.equal(manifest.subjects[name].first, first, name);
|
||||
},
|
||||
);
|
||||
|
||||
const SHEET = new URL(
|
||||
'../../public/sprites/aircraft-views.webp',
|
||||
import.meta.url,
|
||||
);
|
||||
|
||||
test(
|
||||
'the shipped sheet is the size the layout says, grey, and clear at every cell’s edge',
|
||||
{ skip: !existsSync(SHEET) && 'no public/sprites/aircraft-views.webp' },
|
||||
async () => {
|
||||
const { default: sharp } = await import('sharp');
|
||||
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
|
||||
const { data, info } = await sharp(fileURLToPath(SHEET))
|
||||
.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).
|
||||
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;
|
||||
for (let y = 0; y < c; y++)
|
||||
for (let x = 0; x < c; x++) {
|
||||
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) continue;
|
||||
if (data[at(left + x, top + y) + 3] !== 0)
|
||||
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
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). */
|
||||
@@ -920,7 +920,7 @@ test('the Stories announcement waits behind the welcome card', () => {
|
||||
// the card is dismissed.
|
||||
assert.match(
|
||||
css,
|
||||
/body:is\(\.launcher-shown \*, #first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
|
||||
/body:has\(#first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
|
||||
);
|
||||
// The selector only works while Stories still renders the popup as #hPop
|
||||
// inside #gev-stories.
|
||||
@@ -1110,11 +1110,10 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
|
||||
// Pistes extend the generated layer enums and alias hint; voice geometry
|
||||
// adds the analyst area scopes and the osm-places layer.
|
||||
// control_cockpit states the own-layer entry rule (Contacts not required).
|
||||
// Fire Perimeters queries add lastGrowthTime.
|
||||
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
|
||||
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
|
||||
assert.equal(
|
||||
crypto.createHash('sha256').update(block).digest('hex'),
|
||||
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
|
||||
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
|
||||
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
|
||||
);
|
||||
const instructions = fs.readFileSync(
|
||||
|
||||
+22
-140
@@ -227,17 +227,6 @@ const NEARBY_POINTS = Object.values(CITY_POIS).flatMap((city) =>
|
||||
* and the altitude-scaled GSD/NIIRS figures. Readouts update on independent
|
||||
* fixed cadences.
|
||||
*/
|
||||
/**
|
||||
* The view's attributes on #intel-hud itself: shown or not, layout variant
|
||||
* and style colors. Stylesheets and layout elsewhere on the page read them.
|
||||
*/
|
||||
const HUD_FRAME_KEYS = Object.freeze(['active', 'variant', 'colors']);
|
||||
|
||||
/** @param {object} view @returns {object} Its {@link HUD_FRAME_KEYS}. */
|
||||
function pickFrame(view) {
|
||||
return Object.fromEntries(HUD_FRAME_KEYS.map((key) => [key, view[key]]));
|
||||
}
|
||||
|
||||
export class IntelHUD {
|
||||
/**
|
||||
* @param {object} viewer - The scene the HUD sits over.
|
||||
@@ -265,19 +254,6 @@ export class IntelHUD {
|
||||
this.placeSearch = placeSearch;
|
||||
this.viewer = viewer;
|
||||
this._visible = false;
|
||||
// Whether the HUD's view is on screen (setDisplayed). While it is not,
|
||||
// no timer runs and no readout is worked out or published; what was
|
||||
// skipped is caught up when it is back.
|
||||
this._displayed = true;
|
||||
this._unseen = { settle: false, show: false, summary: false };
|
||||
/** Summary updates under way; one still running when the view goes is
|
||||
* dropped and asked again when it is back. */
|
||||
this._summaryRuns = 0;
|
||||
/** The text the typewriter is typing out, while it types. */
|
||||
this._summaryTypingText = null;
|
||||
/** When the view stopped being displayed (Date.now()), or null. */
|
||||
this._undisplayedAt = null;
|
||||
this._destroyed = false;
|
||||
this._autoMode = true; // auto show/hide based on style
|
||||
this._currentStyle = 'normal';
|
||||
/** The presented HUD; see {@link IntelHUD#_initView}. */
|
||||
@@ -344,8 +320,20 @@ export class IntelHUD {
|
||||
};
|
||||
this._onCameraMoveEnd = () => {
|
||||
this._markSummaryDirty();
|
||||
if (this._displayed) this._settle();
|
||||
else this._unseen.settle = true;
|
||||
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
|
||||
// leave the prior city on-screen after a long CCTV focus flight.
|
||||
// Refresh deterministic camera context synchronously on settle; the AI
|
||||
// summary can still upgrade it on its normal cadence.
|
||||
if (this._visible) {
|
||||
this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
// First settled view: request the AI summary now rather than waiting for
|
||||
// the periodic tick (saves up to ~15s of "Awaiting telemetry...").
|
||||
if (!this._firstSummaryKicked && this._visible && this._latestMetrics) {
|
||||
this._firstSummaryKicked = true;
|
||||
void this._updateSummary(true, true);
|
||||
}
|
||||
};
|
||||
|
||||
// Session-consistent pseudorandom identifiers (generated once at construction)
|
||||
@@ -370,27 +358,6 @@ export class IntelHUD {
|
||||
this._startTimers();
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera has settled: show the readouts and the plain summary for the
|
||||
* view it settled on.
|
||||
*/
|
||||
_settle() {
|
||||
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
|
||||
// leave the prior city on-screen after a long CCTV focus flight.
|
||||
// Refresh deterministic camera context synchronously on settle; the AI
|
||||
// summary can still upgrade it on its normal cadence.
|
||||
if (this._visible) {
|
||||
this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
// First settled view: request the AI summary now rather than waiting for
|
||||
// the periodic tick (saves up to ~15s of "Awaiting telemetry...").
|
||||
if (!this._firstSummaryKicked && this._visible && this._latestMetrics) {
|
||||
this._firstSummaryKicked = true;
|
||||
void this._updateSummary(true, true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Show the HUD's words in the new locale; drop AI text in the old one. */
|
||||
_relocalize() {
|
||||
this._markSummaryDirty();
|
||||
@@ -407,8 +374,7 @@ export class IntelHUD {
|
||||
? {}
|
||||
: { vessel: { active: false, text: t('AIS: --') } }),
|
||||
});
|
||||
if (this._visible && this._displayed && this._latestMetrics)
|
||||
this._updateCameraData();
|
||||
if (this._visible && this._latestMetrics) this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
|
||||
@@ -451,17 +417,10 @@ export class IntelHUD {
|
||||
*/
|
||||
_present(patch) {
|
||||
Object.assign(this._view, patch);
|
||||
// Not displayed: only the view's own attributes are published, which the
|
||||
// page's stylesheets and layout read from #intel-hud while it is hidden
|
||||
// too; the readouts wait until it is displayed again.
|
||||
const view = this._displayed
|
||||
? this._view
|
||||
: { ...this._shown, ...pickFrame(this._view) };
|
||||
const signature = JSON.stringify(view);
|
||||
const signature = JSON.stringify(this._view);
|
||||
if (signature === this._viewSignature) return;
|
||||
this._viewSignature = signature;
|
||||
this._shown = Object.freeze({ ...view });
|
||||
this._publish(this._shown);
|
||||
this._publish(Object.freeze({ ...this._view }));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -470,7 +429,6 @@ export class IntelHUD {
|
||||
* cadences and are cleaned up in {@link destroy}.
|
||||
*/
|
||||
_startTimers() {
|
||||
this._stopTimers();
|
||||
// Timestamp — every second
|
||||
this._timestampInterval = setInterval(() => {
|
||||
this._present({ timestamp: this._formatUTC() });
|
||||
@@ -497,18 +455,6 @@ export class IntelHUD {
|
||||
}, HUD_SUMMARY_INTERVAL_MS);
|
||||
}
|
||||
|
||||
/** Stop the periodic timers {@link _startTimers} started. */
|
||||
_stopTimers() {
|
||||
clearInterval(this._timestampInterval);
|
||||
clearInterval(this._recBlinkInterval);
|
||||
clearInterval(this._updateInterval);
|
||||
clearInterval(this._summaryInterval);
|
||||
this._timestampInterval = null;
|
||||
this._recBlinkInterval = null;
|
||||
this._updateInterval = null;
|
||||
this._summaryInterval = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the HUD's world time as a UTC Zulu string.
|
||||
* @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SSZ` format.
|
||||
@@ -898,7 +844,6 @@ export class IntelHUD {
|
||||
_stopSummaryTyping() {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
this._summaryTypingText = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -908,7 +853,6 @@ export class IntelHUD {
|
||||
*/
|
||||
_typeSummary(text) {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingText = text;
|
||||
let index = 0;
|
||||
this._present({ summary: '' });
|
||||
this._summaryTypingInterval = setInterval(() => {
|
||||
@@ -917,7 +861,6 @@ export class IntelHUD {
|
||||
this._present({ summary: text });
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
this._summaryTypingText = null;
|
||||
return;
|
||||
}
|
||||
this._present({ summary: text.slice(0, index) });
|
||||
@@ -930,16 +873,6 @@ export class IntelHUD {
|
||||
* by character; otherwise sets it instantly.
|
||||
*/
|
||||
async _updateSummary(animate = false, force = false) {
|
||||
this._summaryRuns += 1;
|
||||
try {
|
||||
await this._runSummaryUpdate(animate, force);
|
||||
} finally {
|
||||
this._summaryRuns -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link _updateSummary}'s work. */
|
||||
async _runSummaryUpdate(animate, force) {
|
||||
const fallbackText = this._composeSummary();
|
||||
if (!this._latestMetrics) {
|
||||
this._setSummaryText(fallbackText, animate);
|
||||
@@ -1069,8 +1002,7 @@ export class IntelHUD {
|
||||
}
|
||||
|
||||
_setSummaryText(text, animate) {
|
||||
// Nothing types out off screen: the text is there when the view is back.
|
||||
if (animate && this._displayed) {
|
||||
if (animate) {
|
||||
this._typeSummary(text);
|
||||
return;
|
||||
}
|
||||
@@ -1191,63 +1123,11 @@ export class IntelHUD {
|
||||
show() {
|
||||
this._visible = true;
|
||||
this._present({ active: true });
|
||||
if (this._displayed) this._refreshShown();
|
||||
else this._unseen.show = true;
|
||||
}
|
||||
|
||||
/** Readouts and a fresh summary for a HUD just shown. */
|
||||
_refreshShown() {
|
||||
this._updateCameraData(); // immediate update
|
||||
this._markSummaryDirty();
|
||||
void this._updateSummary(false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the HUD's view is on screen. A stylesheet can give the view
|
||||
* `display: none`, or the view can be unmounted; until it is displayed
|
||||
* again no timer runs, a summary being worked out is dropped and only the
|
||||
* view's own attributes ({@link HUD_FRAME_KEYS}) are published. Then the
|
||||
* timers start again and current readouts show at once.
|
||||
* @param {boolean} displayed
|
||||
*/
|
||||
setDisplayed(displayed) {
|
||||
displayed = Boolean(displayed);
|
||||
if (this._destroyed || displayed === this._displayed) return;
|
||||
this._displayed = displayed;
|
||||
if (!displayed) {
|
||||
this._undisplayedAt = Date.now();
|
||||
this._stopTimers();
|
||||
// A reply still typing is finished: the view shows all of it when it
|
||||
// is back, not the rest of it typing out.
|
||||
const typing = this._summaryTypingText;
|
||||
this._stopSummaryTyping();
|
||||
if (typing !== null) this._present({ summary: typing });
|
||||
// A summary being worked out is dropped, and asked again when the
|
||||
// view is back.
|
||||
if (this._summaryRuns > 0) {
|
||||
this._unseen.summary = true;
|
||||
this._markSummaryDirty();
|
||||
this._summaryRequest?.abort();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const { settle, show } = this._unseen;
|
||||
// The summary refresh that would have come round while it was away.
|
||||
const summary =
|
||||
this._unseen.summary ||
|
||||
Date.now() - (this._undisplayedAt ?? Date.now()) >=
|
||||
HUD_SUMMARY_INTERVAL_MS;
|
||||
this._unseen = { settle: false, show: false, summary: false };
|
||||
this._undisplayedAt = null;
|
||||
this._startTimers();
|
||||
// Publishes the whole view: what changed while it was not displayed.
|
||||
this._present({ timestamp: this._formatUTC() });
|
||||
if (settle) this._settle();
|
||||
if (show && this._visible) this._refreshShown();
|
||||
else if (!settle && this._visible) this._updateCameraData();
|
||||
if (summary && !show && this._visible) void this._updateSummary(true);
|
||||
}
|
||||
|
||||
/** Hide the HUD overlay. */
|
||||
hide() {
|
||||
this._visible = false;
|
||||
@@ -1334,8 +1214,10 @@ export class IntelHUD {
|
||||
|
||||
/** Tear down all running intervals. Call when discarding the HUD instance. */
|
||||
destroy() {
|
||||
this._destroyed = true;
|
||||
this._stopTimers();
|
||||
clearInterval(this._updateInterval);
|
||||
clearInterval(this._recBlinkInterval);
|
||||
clearInterval(this._timestampInterval);
|
||||
clearInterval(this._summaryInterval);
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
for (const off of this._offCamera.splice(0)) off();
|
||||
this._dataManagerUnsubscribe?.();
|
||||
|
||||
@@ -1845,6 +1845,11 @@
|
||||
"Unnamed incident": "حادث بلا اسم",
|
||||
"Open {title} on InciWeb": "فتح {title} على InciWeb",
|
||||
"Perimeter source unavailable": "مصدر محيطات الحرائق غير متاح",
|
||||
"Not contained or unknown": "بلا احتواء أو غير معروف",
|
||||
"Under 50% contained": "الاحتواء: أقل من 50%",
|
||||
"50–99% contained": "الاحتواء: 50–99%",
|
||||
"Fully contained": "احتواء كامل",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "يبيّن اللون نسبة الاحتواء المُبلَّغ عنها. المحيطات مبسّطة إلى نحو 100 م.",
|
||||
"Malformed perimeter snapshot": "لقطة المحيطات مشوّهة",
|
||||
"radio tag|All": "الكل",
|
||||
"Directory refresh degraded; showing the previous station catalog.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
|
||||
@@ -4851,12 +4856,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "آخر توسّع قبل {age}",
|
||||
"Last 6 hours": "آخر 6 ساعات",
|
||||
"6–24 hours": "6–24 ساعة",
|
||||
"1–3 days": "1–3 أيام",
|
||||
"Older or unknown": "أقدم أو غير معروف",
|
||||
"Colour shows the age of each area.": "يبيّن اللون عمر كل منطقة.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "يُحسب العمر من وقت رسم WFIGS للحدود، وإلا فمن آخر تعديل للسجل. الحدود مبسّطة إلى نحو 100 م."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · التحذير {number} · صدر {time}"
|
||||
}
|
||||
@@ -1727,6 +1727,11 @@
|
||||
"Unnamed incident": "Unbenannter Einsatz",
|
||||
"Open {title} on InciWeb": "{title} auf InciWeb öffnen",
|
||||
"Perimeter source unavailable": "Quelle der Brandgrenzen nicht verfügbar",
|
||||
"Not contained or unknown": "Nicht eingedämmt oder unbekannt",
|
||||
"Under 50% contained": "Unter 50 % eingedämmt",
|
||||
"50–99% contained": "50–99 % eingedämmt",
|
||||
"Fully contained": "Vollständig eingedämmt",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Die Farbe zeigt die gemeldete Eindämmung. Brandgrenzen sind auf etwa 100 m vereinfacht.",
|
||||
"Malformed perimeter snapshot": "Fehlerhafter Brandgrenzen-Snapshot",
|
||||
"radio tag|All": "Alle",
|
||||
"Directory refresh degraded; showing the previous station catalog.": "Verzeichnisaktualisierung eingeschränkt; der vorherige Senderkatalog wird gezeigt.",
|
||||
@@ -4427,12 +4432,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "zuletzt gewachsen vor {age}",
|
||||
"Last 6 hours": "Letzte 6 Stunden",
|
||||
"6–24 hours": "6–24 Stunden",
|
||||
"1–3 days": "1–3 Tage",
|
||||
"Older or unknown": "Älter oder unbekannt",
|
||||
"Colour shows the age of each area.": "Die Farbe zeigt das Alter jeder Fläche.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Alter ab der Kartierung durch WFIGS, sonst ab der letzten Änderung des Datensatzes. Brandgrenzen auf ca. 100 m vereinfacht."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Warnung {number} · ausgegeben {time}"
|
||||
}
|
||||
@@ -1411,6 +1411,11 @@
|
||||
"Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
|
||||
"Routing unavailable": "Rutas no disponibles",
|
||||
"Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
|
||||
"Not contained or unknown": "Sin contener o desconocido",
|
||||
"Under 50% contained": "Contenido por debajo del 50%",
|
||||
"50–99% contained": "Contenido al 50–99%",
|
||||
"Fully contained": "Totalmente contenido",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
|
||||
"MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
|
||||
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
|
||||
"DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
|
||||
@@ -4533,12 +4538,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "último crecimiento hace {age}",
|
||||
"Last 6 hours": "Últimas 6 horas",
|
||||
"6–24 hours": "6–24 horas",
|
||||
"1–3 days": "1–3 días",
|
||||
"Older or unknown": "Más antiguo o desconocido",
|
||||
"Colour shows the age of each area.": "El color indica la antigüedad de cada zona.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Antigüedad desde el mapeo de WFIGS o, si falta, desde la última edición del registro. Perímetros simplificados a ~100 m."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
|
||||
}
|
||||
@@ -1070,6 +1070,11 @@
|
||||
"Unnamed incident": "Incident sans nom",
|
||||
"Open {title} on InciWeb": "Ouvrir {title} sur InciWeb",
|
||||
"Perimeter source unavailable": "Source des périmètres indisponible",
|
||||
"Not contained or unknown": "Non circonscrit ou inconnu",
|
||||
"Under 50% contained": "Circonscrit à moins de 50 %",
|
||||
"50–99% contained": "Circonscrit à 50–99 %",
|
||||
"Fully contained": "Entièrement circonscrit",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "La couleur indique la part du périmètre déclarée circonscrite. Les périmètres sont simplifiés à environ 100 m.",
|
||||
"Malformed perimeter snapshot": "Instantané des périmètres mal formé",
|
||||
"radio tag|All": "Toutes",
|
||||
"News": "Actualités",
|
||||
@@ -4533,12 +4538,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "dernière progression il y a {age}",
|
||||
"Last 6 hours": "6 dernières heures",
|
||||
"6–24 hours": "6–24 heures",
|
||||
"1–3 days": "1–3 jours",
|
||||
"Older or unknown": "Plus ancien ou inconnu",
|
||||
"Colour shows the age of each area.": "La couleur indique l’âge de chaque zone.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Âge compté depuis la cartographie WFIGS, sinon depuis la dernière modification de la fiche. Périmètres simplifiés à ~100 m."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avertissement {number} · émis {time}"
|
||||
}
|
||||
@@ -919,6 +919,11 @@
|
||||
"Unnamed incident": "אירוע ללא שם",
|
||||
"Open {title} on InciWeb": "פתיחת {title} ב-InciWeb",
|
||||
"Perimeter source unavailable": "מקור ההיקף אינו זמין",
|
||||
"Not contained or unknown": "ללא הכלה או לא ידוע",
|
||||
"Under 50% contained": "הכלה מתחת ל-50%",
|
||||
"50–99% contained": "הכלה 50–99%",
|
||||
"Fully contained": "הכלה מלאה",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "הצבע מציג את ההכלה שדווחה. ההיקפים מפושטים לכ-100 מ׳.",
|
||||
"Malformed perimeter snapshot": "תמונת מצב היקף פגומה",
|
||||
"radio tag|All": "הכול",
|
||||
"News": "חדשות",
|
||||
@@ -4533,12 +4538,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "התפשטות אחרונה לפני {age}",
|
||||
"Last 6 hours": "6 השעות האחרונות",
|
||||
"6–24 hours": "6–24 שעות",
|
||||
"1–3 days": "1–3 ימים",
|
||||
"Older or unknown": "ישן יותר או לא ידוע",
|
||||
"Colour shows the age of each area.": "הצבע מציין את הגיל של כל שטח.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "הגיל נספר ממועד המיפוי של WFIGS, או מהעריכה האחרונה של הרשומה. קווי המתאר מפושטים לכ־100 מ׳."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · אזהרה {number} · פורסמה {time}"
|
||||
}
|
||||
@@ -1070,6 +1070,11 @@
|
||||
"Unnamed incident": "Incendio senza nome",
|
||||
"Open {title} on InciWeb": "Apri {title} su InciWeb",
|
||||
"Perimeter source unavailable": "Fonte dei perimetri non disponibile",
|
||||
"Not contained or unknown": "Non contenuto o dato non disponibile",
|
||||
"Under 50% contained": "Contenuto a meno del 50%",
|
||||
"50–99% contained": "Contenuto al 50–99%",
|
||||
"Fully contained": "Completamente contenuto",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Il colore indica il contenimento riportato. I perimetri sono semplificati a circa 100 m.",
|
||||
"Malformed perimeter snapshot": "Snapshot dei perimetri non valido",
|
||||
"radio tag|All": "Tutti",
|
||||
"News": "Notizie",
|
||||
@@ -4533,12 +4538,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "ultima espansione {age} fa",
|
||||
"Last 6 hours": "Ultime 6 ore",
|
||||
"6–24 hours": "6–24 ore",
|
||||
"1–3 days": "1–3 giorni",
|
||||
"Older or unknown": "Più vecchio o sconosciuto",
|
||||
"Colour shows the age of each area.": "Il colore indica l’età di ciascuna area.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Età dalla mappatura WFIGS, altrimenti dall’ultima modifica del record. Perimetri semplificati a ~100 m."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avviso {number} · emesso {time}"
|
||||
}
|
||||
@@ -1024,6 +1024,11 @@
|
||||
"Unnamed incident": "名称未設定の火災",
|
||||
"Open {title} on InciWeb": "InciWebで{title}を開く",
|
||||
"Perimeter source unavailable": "延焼範囲のソースを利用できません",
|
||||
"Not contained or unknown": "封じ込め率0%または不明",
|
||||
"Under 50% contained": "封じ込め率50%未満",
|
||||
"50–99% contained": "封じ込め率50–99%",
|
||||
"Fully contained": "封じ込め率100%",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "色は報告された封じ込め率を示します。延焼範囲の輪郭は約100 mの精度で簡略化されています。",
|
||||
"Malformed perimeter snapshot": "延焼範囲スナップショットの形式が不正です",
|
||||
"radio tag|All": "すべて",
|
||||
"News": "ニュース",
|
||||
@@ -4321,12 +4326,5 @@
|
||||
"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} 発表",
|
||||
"last growth {age} ago": "{age}前に最終拡大",
|
||||
"Last 6 hours": "過去6時間",
|
||||
"6–24 hours": "6–24時間",
|
||||
"1–3 days": "1–3日",
|
||||
"Older or unknown": "それ以前または不明",
|
||||
"Colour shows the age of each area.": "色は各区域の経過時間を示します。",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "経過時間は WFIGS の測図時刻から、なければ記録の最終編集時刻から数えます。境界線は約 100 m に簡略化されています。"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第{number}号警報 · {time} 発表"
|
||||
}
|
||||
@@ -1068,6 +1068,11 @@
|
||||
"Unnamed incident": "Sem nome",
|
||||
"Open {title} on InciWeb": "Abrir {title} no InciWeb",
|
||||
"Perimeter source unavailable": "Fonte de perímetros indisponível",
|
||||
"Not contained or unknown": "Não contido ou desconhecido",
|
||||
"Under 50% contained": "Menos de 50% contido",
|
||||
"50–99% contained": "50–99% contido",
|
||||
"Fully contained": "Totalmente contido",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "A cor indica a contenção informada. Os perímetros são simplificados para cerca de 100 m.",
|
||||
"Malformed perimeter snapshot": "Snapshot de perímetros malformado",
|
||||
"radio tag|All": "Todas",
|
||||
"News": "Notícias",
|
||||
@@ -4533,12 +4538,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "último crescimento há {age}",
|
||||
"Last 6 hours": "Últimas 6 horas",
|
||||
"6–24 hours": "6–24 horas",
|
||||
"1–3 days": "1–3 dias",
|
||||
"Older or unknown": "Mais antigo ou desconhecido",
|
||||
"Colour shows the age of each area.": "A cor indica a idade de cada área.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Idade a partir do mapeamento do WFIGS ou, na falta dele, da última edição do registro. Perímetros simplificados a ~100 m."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
|
||||
}
|
||||
@@ -1439,6 +1439,11 @@
|
||||
"Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
|
||||
"Routing unavailable": "Построение маршрута недоступно",
|
||||
"Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
|
||||
"Not contained or unknown": "Не локализован или неизвестно",
|
||||
"Under 50% contained": "Локализован менее чем на 50%",
|
||||
"50–99% contained": "Локализован на 50–99%",
|
||||
"Fully contained": "Полностью локализован",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
|
||||
"MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
|
||||
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
|
||||
"DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
|
||||
@@ -4639,12 +4644,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "последний рост {age} назад",
|
||||
"Last 6 hours": "Последние 6 часов",
|
||||
"6–24 hours": "6–24 часа",
|
||||
"1–3 days": "1–3 дня",
|
||||
"Older or unknown": "Старше или неизвестно",
|
||||
"Colour shows the age of each area.": "Цвет показывает возраст каждого участка.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Возраст — от картирования WFIGS, иначе от последней правки записи. Контуры упрощены до ~100 м."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Предупреждение № {number} · выпущено {time}"
|
||||
}
|
||||
@@ -1643,6 +1643,11 @@
|
||||
"Unnamed incident": "Namnlös händelse",
|
||||
"Open {title} on InciWeb": "Öppna {title} på InciWeb",
|
||||
"Perimeter source unavailable": "Källa för brandgränser otillgänglig",
|
||||
"Not contained or unknown": "Inte under kontroll eller okänt",
|
||||
"Under 50% contained": "Mindre än 50 % under kontroll",
|
||||
"50–99% contained": "50–99 % under kontroll",
|
||||
"Fully contained": "Helt under kontroll",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Färgen visar rapporterad kontrollgrad. Brandgränserna är förenklade till cirka 100 m.",
|
||||
"Malformed perimeter snapshot": "Felformaterad ögonblicksbild av brandgränser",
|
||||
"radio tag|All": "Alla",
|
||||
"Directory refresh degraded; showing the previous station catalog.": "Uppdateringen av katalogen är begränsad; visar den tidigare stationskatalogen.",
|
||||
@@ -4427,12 +4432,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "senaste tillväxt för {age} sedan",
|
||||
"Last 6 hours": "Senaste 6 timmarna",
|
||||
"6–24 hours": "6–24 timmar",
|
||||
"1–3 days": "1–3 dagar",
|
||||
"Older or unknown": "Äldre eller okänt",
|
||||
"Colour shows the age of each area.": "Färgen visar åldern på varje område.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Åldern räknas från WFIGS kartläggning, annars från postens senaste ändring. Brandgränser förenklade till ~100 m."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Varning {number} · utfärdad {time}"
|
||||
}
|
||||
@@ -1092,6 +1092,11 @@
|
||||
"Unnamed incident": "Без назви",
|
||||
"Open {title} on InciWeb": "Відкрити {title} в InciWeb",
|
||||
"Perimeter source unavailable": "Джерело контурів пожеж недоступне",
|
||||
"Not contained or unknown": "Не локалізовано або невідомо",
|
||||
"Under 50% contained": "Локалізовано менш ніж на 50%",
|
||||
"50–99% contained": "Локалізовано на 50–99%",
|
||||
"Fully contained": "Повністю локалізовано",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Колір показує заявлений ступінь локалізації. Контури спрощено приблизно до 100 м.",
|
||||
"Malformed perimeter snapshot": "Некоректний знімок контурів пожеж",
|
||||
"radio tag|All": "Усі",
|
||||
"News": "Новини",
|
||||
@@ -4639,12 +4644,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "останнє зростання {age} тому",
|
||||
"Last 6 hours": "Останні 6 годин",
|
||||
"6–24 hours": "6–24 години",
|
||||
"1–3 days": "1–3 дні",
|
||||
"Older or unknown": "Старше або невідомо",
|
||||
"Colour shows the age of each area.": "Колір показує вік кожної ділянки.",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Вік — від картування WFIGS, інакше від останнього редагування запису. Контури спрощено до ~100 м."
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Попередження № {number} · випущено {time}"
|
||||
}
|
||||
@@ -1004,6 +1004,11 @@
|
||||
"Unnamed incident": "未命名火情",
|
||||
"Open {title} on InciWeb": "在 InciWeb 上打开 {title}",
|
||||
"Perimeter source unavailable": "周界数据源不可用",
|
||||
"Not contained or unknown": "未控制或未知",
|
||||
"Under 50% contained": "控制低于 50%",
|
||||
"50–99% contained": "控制 50–99%",
|
||||
"Fully contained": "已全部控制",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "颜色表示报告的控制比例。周界简化至约 100 m。",
|
||||
"Malformed perimeter snapshot": "周界快照格式错误",
|
||||
"radio tag|All": "全部",
|
||||
"News": "新闻",
|
||||
@@ -4321,12 +4326,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "最近一次扩展于 {age}前",
|
||||
"Last 6 hours": "过去 6 小时",
|
||||
"6–24 hours": "6–24 小时",
|
||||
"1–3 days": "1–3 天",
|
||||
"Older or unknown": "更早或未知",
|
||||
"Colour shows the age of each area.": "颜色表示各区域在所示时刻的年龄。",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "时长从 WFIGS 测绘时间算起,否则从记录的最后编辑时间算起。边界已简化至约 100 米。"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 号警报 · 发布于 {time}"
|
||||
}
|
||||
@@ -1004,6 +1004,11 @@
|
||||
"Unnamed incident": "未命名火情",
|
||||
"Open {title} on InciWeb": "在 InciWeb 上打開 {title}",
|
||||
"Perimeter source unavailable": "周界數據源不可用",
|
||||
"Not contained or unknown": "未控制或未知",
|
||||
"Under 50% contained": "控制低於 50%",
|
||||
"50–99% contained": "控制 50–99%",
|
||||
"Fully contained": "已全部控制",
|
||||
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "顏色表示報告的控制比例。周界簡化至約 100 m。",
|
||||
"Malformed perimeter snapshot": "周界快照格式錯誤",
|
||||
"radio tag|All": "全部",
|
||||
"News": "新聞",
|
||||
@@ -4321,12 +4326,5 @@
|
||||
"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}",
|
||||
"last growth {age} ago": "最近一次擴展於 {age}前",
|
||||
"Last 6 hours": "過去 6 小時",
|
||||
"6–24 hours": "6–24 小時",
|
||||
"1–3 days": "1–3 天",
|
||||
"Older or unknown": "更早或未知",
|
||||
"Colour shows the age of each area.": "顏色表示各區域在所示時刻的年齡。",
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "時長從 WFIGS 測繪時間算起,否則從記錄的最後編輯時間算起。邊界已簡化至約 100 米。"
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 號警報 · 發布於 {time}"
|
||||
}
|
||||
@@ -21,11 +21,12 @@ const PIN_TURN_DEG = 0.1;
|
||||
* the grounded floor: a floor-pinned row holds a CPU position, so it is not
|
||||
* planned, and settling a grounded contact puts it straight onto the floor.
|
||||
*/
|
||||
export function createIcons({ flightState, services, parts }) {
|
||||
export function createIcons({ flightState, services, parts, resolveAsset }) {
|
||||
const icons = createAircraftIcons({
|
||||
state: flightState,
|
||||
services,
|
||||
parts,
|
||||
resolveAsset,
|
||||
layerId: 'flights',
|
||||
displayDelay: flightState._displayDelay,
|
||||
followsClock: () => followsClock(flightState),
|
||||
|
||||
@@ -3,10 +3,7 @@ import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createIcons } from './icons.js';
|
||||
import {
|
||||
createContactIcons,
|
||||
placedPlanSpread,
|
||||
} from '../../data/aircraftIconLayer.js';
|
||||
import { createContactIcons } from '../../data/aircraftIconLayer.js';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import {
|
||||
aircraftMotionRegime,
|
||||
@@ -272,10 +269,8 @@ test('a live contact a placement places is drawn along where it places it', (t)
|
||||
const now = icons._displayMs();
|
||||
const leadMs = Date.now() - now;
|
||||
icons._planIcon('p');
|
||||
// A plan's length, as this contact's are spread (a second on average).
|
||||
const planMs = 1000 * placedPlanSpread('p');
|
||||
// Asked for the wall times the segment's ends stand for.
|
||||
assert.deepEqual(asked, [now + leadMs, now + planMs + leadMs]);
|
||||
assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
|
||||
assert.equal(regimes.length, 0, 'its own motion is not planned');
|
||||
const item = set.item('p');
|
||||
assert.equal(item.motion.kind, 'lerp');
|
||||
@@ -289,16 +284,16 @@ test('a live contact a placement places is drawn along where it places it', (t)
|
||||
Cesium.Cartesian3.distance(
|
||||
item.motion.to,
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
(now + planMs + leadMs - t0) / 10_000,
|
||||
(now + 1000 + leadMs - t0) / 10_000,
|
||||
30,
|
||||
2000,
|
||||
),
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.equal(item.motion.t0, now);
|
||||
assert.equal(item.motion.t1, now + planMs);
|
||||
assert.ok(Math.abs(item.motion.courseSlopeDeg - planMs / 1000) < 1e-9);
|
||||
assert.equal(set.expires('p'), now + planMs);
|
||||
assert.equal(item.motion.t1, now + 1000);
|
||||
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
|
||||
assert.equal(set.expires('p'), now + 1000);
|
||||
|
||||
// No answer: the layer's own motion plans it.
|
||||
places = false;
|
||||
|
||||
@@ -11,6 +11,7 @@ export function createLifecycle({
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { onMilitaryLayerActiveChange } = services.militaryRegistry;
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
@@ -111,8 +112,7 @@ export function createLifecycle({
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
// Drawn as often as the fleet moves on screen (renderPace.js).
|
||||
parts.rendering._startPace();
|
||||
holdContinuousRender('flights'); // per-frame animator (perf wave 2)
|
||||
parts.rendering._setModelsShown(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
document.body.classList.contains('cockpit-mode'),
|
||||
@@ -168,7 +168,7 @@ export function createLifecycle({
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
parts.rendering._stopPace();
|
||||
releaseContinuousRender('flights');
|
||||
parts.rendering._releaseModels();
|
||||
parts.rendering._setModelsShown(false);
|
||||
parts.tracking._clearTracking();
|
||||
@@ -208,7 +208,7 @@ export function createLifecycle({
|
||||
flightState._enrichActive = 0;
|
||||
flightState._enrichLastDispatchMs = 0;
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
releaseContinuousRender('flights'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -948,7 +948,12 @@ export function createTracking({
|
||||
/** The tracked billboard's images, from the current class/conversion: the
|
||||
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
|
||||
function _trackedBillboardLook() {
|
||||
return parts.icons._fleetLook(flightState._trackedIcao);
|
||||
// Drawn along its course, as the fleet icon is: from the view sheet
|
||||
// where the renderer draws one.
|
||||
const id = flightState._trackedIcao;
|
||||
return parts.icons._fleetLook(id, undefined, undefined, {
|
||||
alongCourse: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1130,6 +1135,9 @@ export function createTracking({
|
||||
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
|
||||
// or model still loading); transparent once the tracked model is actually up.
|
||||
color: _trackedIconColor,
|
||||
// The course a view-sheet image is drawn along (the same display
|
||||
// course the screen rotation below is projected from).
|
||||
course: () => parts.motion._trackedDisplayCourse(),
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
import { aircraftIcon } from '../../data/aircraftIcons.js';
|
||||
import {
|
||||
aircraftViewRef,
|
||||
registerAircraftViews,
|
||||
} from '../../data/aircraftViews.js';
|
||||
import { rotorFrame } from '../../data/rotorFrames.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
import {
|
||||
@@ -13,6 +17,7 @@ import {
|
||||
findCamera,
|
||||
findFrame,
|
||||
findQuery,
|
||||
rendererOf,
|
||||
} from '../../render/rendererOf.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
|
||||
@@ -148,6 +153,9 @@ export function createLocalAdsbLayer({
|
||||
* @type {{markers: object, rings: object}|null}
|
||||
*/
|
||||
let sets = null;
|
||||
/** Whether the renderer draws markers from the aircraft view sheet
|
||||
* (`aircraftViews.js`), set at `init`. */
|
||||
let views = false;
|
||||
let enabled = false;
|
||||
let unsubscribe = null;
|
||||
let unsubscribeFeeds = null;
|
||||
@@ -355,31 +363,36 @@ export function createLocalAdsbLayer({
|
||||
/**
|
||||
* A marker's icon, where and how it now draws: a helicopter's rotor frame
|
||||
* at `at` (still on the ground), an airport vehicle in its own tint, a
|
||||
* ground station's mast upright.
|
||||
* ground station's mast upright. On a renderer that draws view sheets, a
|
||||
* kind with rendered views is drawn from the sheet along its course;
|
||||
* every other marker is its flat glyph turned on screen.
|
||||
*/
|
||||
function markerItem(marker, basis, at) {
|
||||
const kind = marker.iconKind ?? 'airliner';
|
||||
const frame =
|
||||
kind === 'helicopter'
|
||||
? rotorFrame(marker.id, at, {
|
||||
onGround: marker.onGround,
|
||||
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
|
||||
? marker.record.groundSpeedKt * KNOT_MPS
|
||||
: null,
|
||||
})
|
||||
: undefined;
|
||||
const view = views ? aircraftViewRef(kind, frame) : null;
|
||||
return {
|
||||
id: marker.id,
|
||||
pos: marker.position,
|
||||
image: aircraftIcon(
|
||||
kind,
|
||||
undefined,
|
||||
kind === 'helicopter'
|
||||
? rotorFrame(marker.id, at, {
|
||||
onGround: marker.onGround,
|
||||
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
|
||||
? marker.record.groundSpeedKt * KNOT_MPS
|
||||
: null,
|
||||
})
|
||||
: undefined,
|
||||
),
|
||||
image: view ?? aircraftIcon(kind, undefined, frame),
|
||||
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
|
||||
scale: marker.iconScale ?? 1,
|
||||
color: kind === 'vehicle' ? vehicleColor : color,
|
||||
scaleByDistance: MARKER_SPRITE.scaleByDistance,
|
||||
rotationMode: 'screen',
|
||||
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
|
||||
...(view
|
||||
? { rotationMode: 'course', course: marker.courseDeg ?? 0 }
|
||||
: {
|
||||
rotationMode: 'screen',
|
||||
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
|
||||
}),
|
||||
// The 3D model, once loaded and placed, is the visual instead.
|
||||
show: !marker.modelOwnsVisual,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
@@ -773,6 +786,11 @@ export function createLocalAdsbLayer({
|
||||
init(nextViewer) {
|
||||
viewer = nextViewer;
|
||||
const draw = drawOf(viewer);
|
||||
views = registerAircraftViews(
|
||||
draw,
|
||||
rendererOf(viewer)?.capabilities ?? null,
|
||||
resolveAsset,
|
||||
);
|
||||
const prefix = `${LAYER_ID}:${++instances}`;
|
||||
sets = {
|
||||
markers: draw.icons({
|
||||
@@ -872,6 +890,7 @@ export function createLocalAdsbLayer({
|
||||
models = null;
|
||||
if (sets) for (const set of Object.values(sets)) set.dispose();
|
||||
sets = null;
|
||||
views = false;
|
||||
viewer = null;
|
||||
void receiver.destroy?.();
|
||||
},
|
||||
|
||||
@@ -223,6 +223,7 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
|
||||
feeds,
|
||||
services: { ...services, ...options.services },
|
||||
now: () => clock.now,
|
||||
...(options.resolveAsset ? { resolveAsset: options.resolveAsset } : {}),
|
||||
});
|
||||
layer.init(viewer);
|
||||
await layer.enable();
|
||||
@@ -319,6 +320,63 @@ test('local aircraft use their class silhouette at one size in magenta', async (
|
||||
assert.equal(detectable.type, 'AIR');
|
||||
});
|
||||
|
||||
test('on a renderer that draws view sheets, local aircraft draw their view along their track; vehicles and masts stay flat', async (t) => {
|
||||
const { aircraftViewRef } = await import('../../data/aircraftViews.js');
|
||||
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
|
||||
const viewer = { scene: {} };
|
||||
const camera = fakeCameraPort({
|
||||
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
|
||||
});
|
||||
const { draw } = bindFakeDraw(viewer, {
|
||||
camera: camera.port,
|
||||
query: { drillPick: () => [] },
|
||||
capabilities: new Set(['viewSheets']),
|
||||
});
|
||||
fakeInput(viewer);
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
const { layer } = await enabledLayer(receiver, clock, null, {
|
||||
viewer: { draw, viewer },
|
||||
resolveAsset: (url) => `/gev${url}`,
|
||||
});
|
||||
t.after(() => layer.destroy());
|
||||
// Registered once, at the layer's own asset URL.
|
||||
assert.deepEqual(draw.viewSheets, [
|
||||
[
|
||||
AIRCRAFT_VIEWS.id,
|
||||
{ ...AIRCRAFT_VIEWS.sheet, image: '/gev/sprites/aircraft-views.webp' },
|
||||
],
|
||||
]);
|
||||
receiver.set({
|
||||
aircraft: [
|
||||
record({ trackDeg: 0 }),
|
||||
record({ icao: 'a0b702', category: 'A7' }),
|
||||
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
|
||||
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
|
||||
],
|
||||
});
|
||||
await layer.update();
|
||||
const icon = iconOf(draw, 'local-adsb:abc123');
|
||||
assert.equal(icon.image, aircraftViewRef('airliner'));
|
||||
assert.equal(icon.rotationMode, 'course');
|
||||
assert.equal(icon.course, 0);
|
||||
assert.equal('rotation' in icon, false);
|
||||
assert.deepEqual(icon.size, [20, 20]);
|
||||
assert.deepEqual(icon.color, MAGENTA);
|
||||
assert.equal(
|
||||
iconOf(draw, 'local-adsb:a0b702').image,
|
||||
aircraftViewRef('helicopter', rotorFrame('local-adsb:a0b702', clock.now)),
|
||||
'the rotor turns through the sheet',
|
||||
);
|
||||
const vehicle = iconOf(draw, 'local-adsb:a0c001');
|
||||
assert.equal(vehicle.image, aircraftIcon('vehicle'));
|
||||
assert.equal(vehicle.rotationMode, 'screen');
|
||||
const mast = iconOf(draw, 'local-adsb:a0c003');
|
||||
assert.equal(mast.image, aircraftIcon('station'));
|
||||
assert.equal(mast.rotationMode, 'screen');
|
||||
assert.equal(mast.rotation, 0);
|
||||
});
|
||||
|
||||
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
|
||||
@@ -8,11 +8,12 @@ import {
|
||||
} from './policy.js';
|
||||
|
||||
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
|
||||
export function createIcons({ flightState, services, parts }) {
|
||||
export function createIcons({ flightState, services, parts, resolveAsset }) {
|
||||
return createAircraftIcons({
|
||||
state: flightState,
|
||||
services,
|
||||
parts,
|
||||
resolveAsset,
|
||||
layerId: 'military',
|
||||
displayDelay: flightState._displayDelay,
|
||||
followsClock: () => followsClock(flightState),
|
||||
|
||||
@@ -10,6 +10,7 @@ export function createLifecycle({
|
||||
resolveAsset,
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const { setMilitaryLayerActive } = services.militaryRegistry;
|
||||
@@ -92,8 +93,7 @@ export function createLifecycle({
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
// Drawn as often as the fleet moves on screen (renderPace.js).
|
||||
parts.rendering._startPace();
|
||||
holdContinuousRender('military'); // per-frame animator (perf wave 2)
|
||||
parts.rendering._setModelsShown(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
document.body.classList.contains('cockpit-mode'),
|
||||
@@ -151,7 +151,7 @@ export function createLifecycle({
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
parts.rendering._stopPace();
|
||||
releaseContinuousRender('military');
|
||||
parts.rendering._releaseModels();
|
||||
parts.rendering._setModelsShown(false);
|
||||
parts.tracking._clearTracking();
|
||||
@@ -191,7 +191,7 @@ export function createLifecycle({
|
||||
flightState.timeline?.stop();
|
||||
flightState.lifetime.abort();
|
||||
parts.controller._abortActiveUpdates();
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -396,7 +396,12 @@ export function createTracking({
|
||||
/** The tracked billboard's images, from the current class/conversion: the
|
||||
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
|
||||
function _trackedBillboardLook() {
|
||||
return parts.icons._fleetLook(flightState._trackedIcao);
|
||||
// Drawn along its course, as the fleet icon is: from the view sheet
|
||||
// where the renderer draws one.
|
||||
const id = flightState._trackedIcao;
|
||||
return parts.icons._fleetLook(id, undefined, undefined, {
|
||||
alongCourse: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1087,6 +1092,9 @@ export function createTracking({
|
||||
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
|
||||
// or model still loading); transparent once the tracked model is actually up (ready + shown).
|
||||
color: _trackedIconColor,
|
||||
// The course a view-sheet image is drawn along (the same display
|
||||
// course the screen rotation below is projected from).
|
||||
course: () => parts.motion._trackedDisplayCourse(),
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
|
||||
@@ -8,14 +8,13 @@ import { buildIncidentCard } from './cards.js';
|
||||
|
||||
const now = Date.UTC(2026, 9, 14);
|
||||
const row = {
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Lake',
|
||||
acres: 1200,
|
||||
containedPct: 40,
|
||||
state: 'CA',
|
||||
discoveredTime: now - 2 * 3600e3,
|
||||
updatedTime: now - 3600e3,
|
||||
lastGrowthTime: now - 3 * 3600e3,
|
||||
cause: 'Human',
|
||||
behavior: 'Moderate',
|
||||
complexity: 'Type 3 Incident',
|
||||
@@ -34,7 +33,6 @@ test('en: the fire card keeps its English wording', () => {
|
||||
'part of North Complex',
|
||||
'Human cause · Moderate · Type 3 Incident',
|
||||
'1,500 personnel · Plumas County · $4.2M to date',
|
||||
'last growth 3h ago',
|
||||
'discovered 2h ago · updated 1h ago',
|
||||
'InciWeb ↗ · click card to open',
|
||||
]);
|
||||
@@ -46,8 +44,8 @@ for (const locale of ['es', 'ru']) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
assert.notEqual(
|
||||
t('Older or unknown'),
|
||||
'Older or unknown',
|
||||
t('Fully contained'),
|
||||
'Fully contained',
|
||||
'legend is translated',
|
||||
);
|
||||
const card = buildIncidentCard(row, now, {
|
||||
@@ -62,7 +60,6 @@ for (const locale of ['es', 'ru']) {
|
||||
'contained',
|
||||
'discovered',
|
||||
'updated',
|
||||
'last growth',
|
||||
'part of',
|
||||
'cause',
|
||||
'personnel',
|
||||
|
||||
@@ -3,7 +3,7 @@ import { formatNumber, t, tn } from '../../i18n/index.js';
|
||||
|
||||
export const PERIMETER_OVERLAY_SOURCE_ID = 'fire-perimeters';
|
||||
|
||||
/** CSS accent for a perimeter card by containment progress. */
|
||||
/** CSS accent for a perimeter card by containment progress (mirrors the fill). */
|
||||
export function containmentAccent(containedPct) {
|
||||
if (!Number.isFinite(containedPct) || containedPct <= 0) return '#ff3b30';
|
||||
if (containedPct < 50) return '#ff7a00';
|
||||
@@ -11,6 +11,55 @@ export function containmentAccent(containedPct) {
|
||||
return '#8bc34a';
|
||||
}
|
||||
|
||||
/** Shoelace area along short longitude edges (degree², relative sizes only). */
|
||||
function ringArea(ring) {
|
||||
let sum = 0;
|
||||
let [x1, y1] = ring[0];
|
||||
for (let i = 1; i < ring.length; i++) {
|
||||
let delta = ring[i][0] - ring[i - 1][0];
|
||||
if (delta > 180) delta -= 360;
|
||||
else if (delta < -180) delta += 360;
|
||||
const x2 = x1 + delta;
|
||||
const y2 = ring[i][1];
|
||||
sum += x1 * y2 - x2 * y1;
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
}
|
||||
return Math.abs(sum / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor point for the incident card: the vertex mean of the largest polygon's
|
||||
* outer ring, with circular longitude. Callers own the Cartesian conversion.
|
||||
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
|
||||
* @returns {{lon: number, lat: number}}
|
||||
*/
|
||||
export function perimeterAnchorDegrees(polygons) {
|
||||
let best = null;
|
||||
let bestArea = -1;
|
||||
for (const rings of polygons) {
|
||||
const outer = rings[0];
|
||||
const area = ringArea(outer);
|
||||
if (area > bestArea) {
|
||||
bestArea = area;
|
||||
best = outer;
|
||||
}
|
||||
}
|
||||
// Vertex mean over the closed ring (first == last point dropped): perimeters
|
||||
// are compact enough that this stays inside or near the polygon.
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let lat = 0;
|
||||
const count = best.length - 1;
|
||||
const toRad = Math.PI / 180;
|
||||
for (let i = 0; i < count; i++) {
|
||||
sinLon += Math.sin(best[i][0] * toRad);
|
||||
cosLon += Math.cos(best[i][0] * toRad);
|
||||
lat += best[i][1];
|
||||
}
|
||||
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact USD in the UI language: en "$85K / $4.2M / $1.3B", ru "4,2 млн $",
|
||||
* es "4,2 M$". Null under $1,000.
|
||||
@@ -100,9 +149,8 @@ function formatAge(deltaMs) {
|
||||
/**
|
||||
* Build the overlay-host entry for one selected incident. The caller supplies
|
||||
* `position` (Cartesian) separately — this model stays JSON-safe for tests.
|
||||
* @param {Object} row - A snapshot fire (see records.js).
|
||||
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
|
||||
* `at`, or now.
|
||||
* @param {Object} row - Normalized perimeter row (see records.js).
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
|
||||
* @returns {Object} World-overlay entry without `position`.
|
||||
*/
|
||||
@@ -146,17 +194,13 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
if (cost) response.push(t('{cost} to date', { cost }));
|
||||
}
|
||||
|
||||
const ago = (time) => (time == null ? null : formatAge(nowMs - time));
|
||||
const growth = ago(row.lastGrowthTime);
|
||||
const lastGrowth = growth
|
||||
? t('last growth {age} ago', { age: growth })
|
||||
: null;
|
||||
|
||||
const ages = [];
|
||||
const discovered = ago(row.discoveredTime);
|
||||
if (discovered) ages.push(t('discovered {age} ago', { age: discovered }));
|
||||
const updated = ago(row.updatedTime);
|
||||
if (updated) ages.push(t('updated {age} ago', { age: updated }));
|
||||
const discovered = formatAge(nowMs - row.discoveredTime);
|
||||
if (row.discoveredTime != null && discovered)
|
||||
ages.push(t('discovered {age} ago', { age: discovered }));
|
||||
const updated = formatAge(nowMs - row.updatedTime);
|
||||
if (row.updatedTime != null && updated)
|
||||
ages.push(t('updated {age} ago', { age: updated }));
|
||||
|
||||
const details = [facts.join(' · ')];
|
||||
if (row.complexName)
|
||||
@@ -165,7 +209,6 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
);
|
||||
if (situation.length) details.push(situation.join(' · '));
|
||||
if (response.length) details.push(response.join(' · '));
|
||||
if (lastGrowth) details.push(lastGrowth);
|
||||
if (ages.length) details.push(ages.join(' · '));
|
||||
if (link) details.push(t('InciWeb ↗ · click card to open'));
|
||||
|
||||
@@ -173,7 +216,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
name: row.name || t('Unnamed incident'),
|
||||
});
|
||||
return {
|
||||
id: `fire-perimeter-card:${row.id}`,
|
||||
id: `fire-perimeter-card:${row.stableId}`,
|
||||
// `selected` picks the paint lane and collision protection; an explicit
|
||||
// paintLane would override it in the host's lane resolver.
|
||||
selected: true,
|
||||
|
||||
@@ -1,12 +1,99 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildIncidentCard } from './cards.js';
|
||||
import { perimeterAnchorDegrees, buildIncidentCard } from './cards.js';
|
||||
|
||||
const square = [
|
||||
[-108.2, 35.0],
|
||||
[-108.0, 35.0],
|
||||
[-108.0, 35.2],
|
||||
[-108.2, 35.2],
|
||||
[-108.2, 35.0],
|
||||
];
|
||||
const tiny = [
|
||||
[-107.01, 34.0],
|
||||
[-107.0, 34.0],
|
||||
[-107.0, 34.01],
|
||||
[-107.01, 34.0],
|
||||
];
|
||||
|
||||
test('the card anchors at the vertex mean of the largest polygon', () => {
|
||||
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
|
||||
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
|
||||
});
|
||||
|
||||
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
|
||||
const vertices = [
|
||||
[179, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
];
|
||||
for (let start = 0; start < vertices.length; start++) {
|
||||
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
|
||||
for (const points of [rotated, [...rotated].reverse()]) {
|
||||
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
|
||||
for (const boundary of [-180, 180]) {
|
||||
const ring = [
|
||||
[179, 10],
|
||||
[boundary, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
[179, 10],
|
||||
];
|
||||
const anchor = perimeterAnchorDegrees([[ring]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('multipart cards compare polygon areas along short dateline edges', () => {
|
||||
const ordinary = [
|
||||
[10, 20],
|
||||
[11, 20],
|
||||
[11, 21],
|
||||
[10, 21],
|
||||
[10, 20],
|
||||
];
|
||||
for (const width of [0.2, 2]) {
|
||||
const crossing = [
|
||||
[180 - width / 2, 10],
|
||||
[-180 + width / 2, 10],
|
||||
[-180 + width / 2, 10 + width],
|
||||
[180 - width / 2, 10 + width],
|
||||
[180 - width / 2, 10],
|
||||
];
|
||||
for (const ring of [crossing, [...crossing].reverse()]) {
|
||||
for (const polygons of [
|
||||
[[ring], [ordinary]],
|
||||
[[ordinary], [ring]],
|
||||
]) {
|
||||
const anchor = perimeterAnchorDegrees(polygons);
|
||||
if (width < 1) {
|
||||
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
|
||||
} else {
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('a full incident row renders name, size, containment, and ages', () => {
|
||||
const now = 1758000000000;
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: '2026-NMGNF-000123',
|
||||
stableId: '2026-NMGNF-000123',
|
||||
name: 'Frijoles',
|
||||
acres: 15956.4,
|
||||
containedPct: 74,
|
||||
@@ -14,7 +101,6 @@ test('a full incident row renders name, size, containment, and ages', () => {
|
||||
category: 'WF',
|
||||
discoveredTime: now - 36 * 3600000,
|
||||
updatedTime: now - 2 * 3600000,
|
||||
lastGrowthTime: now - 5 * 3600000,
|
||||
cause: 'Natural',
|
||||
behavior: 'Active',
|
||||
personnel: 380,
|
||||
@@ -30,7 +116,6 @@ test('a full incident row renders name, size, containment, and ages', () => {
|
||||
'15,956 ac · 74% contained · US-NM',
|
||||
'Natural cause · Active · Type 3 Incident',
|
||||
'380 personnel · Sandoval County · $4.2M to date',
|
||||
'last growth 5h ago',
|
||||
'discovered 1d ago · updated 2h ago',
|
||||
]);
|
||||
assert.equal(card.selected, true);
|
||||
@@ -40,7 +125,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
|
||||
test('missing attributes degrade to available facts instead of placeholders', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: null,
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -64,7 +149,7 @@ test('missing attributes degrade to available facts instead of placeholders', ()
|
||||
test('a known InciWeb page adds a link line to the card', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Timber',
|
||||
acres: 25426,
|
||||
containedPct: 44,
|
||||
@@ -92,7 +177,7 @@ test('a known InciWeb page adds a link line to the card', () => {
|
||||
test('the selected card claims the selected paint lane, not the ambient lane', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Any',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -119,7 +204,7 @@ test('the selected card claims the selected paint lane, not the ambient lane', (
|
||||
|
||||
test('costs near a unit boundary promote to the larger unit', () => {
|
||||
const base = {
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Any',
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -147,7 +232,7 @@ test('costs near a unit boundary promote to the larger unit', () => {
|
||||
test('a complex member names its complex on the card', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 342923,
|
||||
containedPct: 99,
|
||||
@@ -171,7 +256,7 @@ test('a complex member names its complex on the card', () => {
|
||||
test('a card without a link is not interactive', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -194,7 +279,7 @@ test('a card without a link is not interactive', () => {
|
||||
test('partial incident details render only the facts that exist', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Whiskey',
|
||||
acres: 542,
|
||||
containedPct: 48,
|
||||
@@ -220,7 +305,7 @@ test('partial incident details render only the facts that exist', () => {
|
||||
|
||||
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
|
||||
const row = {
|
||||
id: 'x',
|
||||
stableId: 'x',
|
||||
name: 'Grey',
|
||||
acres: 0.25,
|
||||
containedPct: null,
|
||||
@@ -248,22 +333,3 @@ test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () =>
|
||||
'1 ac · containment unknown · US-WA',
|
||||
);
|
||||
});
|
||||
|
||||
test('ages count from the moment shown, not from the clock', () => {
|
||||
const at = Date.UTC(2025, 7, 1, 12);
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
id: 'past',
|
||||
name: 'Past',
|
||||
containedPct: 10,
|
||||
discoveredTime: at - 3 * 86400000,
|
||||
updatedTime: at - 30 * 60000,
|
||||
lastGrowthTime: at - 7 * 3600000,
|
||||
},
|
||||
at,
|
||||
);
|
||||
assert.deepEqual(card.details.slice(-2), [
|
||||
'last growth 7h ago',
|
||||
'discovered 3d ago · updated 30m ago',
|
||||
]);
|
||||
});
|
||||
@@ -17,8 +17,19 @@ function normalizeName(name) {
|
||||
.replace(/ fire$/, '');
|
||||
}
|
||||
|
||||
function nodeCandidates(publications, { name, state }) {
|
||||
if (!Array.isArray(publications) || !name) return [];
|
||||
/**
|
||||
* Resolve one WFIGS incident against the publication catalog.
|
||||
* Only rows whose normalized title equals the incident's normalized name
|
||||
* count. Ambiguity resolves by the tau dispatch unit's state prefix, then
|
||||
* by newest incident id (same-state duplicates are usually reburns of the
|
||||
* same name). The `/node/{id}` link 301s to the canonical page, so no slug
|
||||
* construction is needed.
|
||||
* @param {?Array} publications - Publication catalog rows.
|
||||
* @param {{name: ?string, state: ?string}} incident - WFIGS row facts.
|
||||
* @returns {?string} InciWeb node URL.
|
||||
*/
|
||||
export function resolveInciwebNodeLink(publications, { name, state }) {
|
||||
if (!Array.isArray(publications) || !name) return null;
|
||||
const wanted = normalizeName(name);
|
||||
let candidates = publications.filter(
|
||||
(row) =>
|
||||
@@ -40,26 +51,20 @@ function nodeCandidates(publications, { name, state }) {
|
||||
row.tau.slice(0, 2).toLowerCase() === statePrefix,
|
||||
);
|
||||
} else if (candidates.length > 1) {
|
||||
return [];
|
||||
return null;
|
||||
}
|
||||
// Same-state duplicates are usually reburns of the same name. Newest wins live.
|
||||
return candidates
|
||||
.sort((a, b) => Number(b.incident_id) - Number(a.incident_id))
|
||||
.map((row) => `https://inciweb.wildfire.gov/node/${row.incident_id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one WFIGS incident against the publication catalog.
|
||||
* Only rows whose normalized title equals the incident's normalized name
|
||||
* count. Matches are filtered by the tau dispatch unit's state prefix.
|
||||
* The `/node/{id}` link 301s to the canonical page, so no slug construction
|
||||
* is needed.
|
||||
* @param {?Array} publications - Publication catalog rows.
|
||||
* @param {{name: ?string, state: ?string}} incident - WFIGS row facts.
|
||||
* @returns {?string} InciWeb node URL.
|
||||
*/
|
||||
export function resolveInciwebNodeLink(publications, incident) {
|
||||
return nodeCandidates(publications, incident)[0] ?? null;
|
||||
if (candidates.length > 1) {
|
||||
// Same-state duplicates are usually reburns of the same name — newest
|
||||
// wins here, and the publication-currency check guards the final link.
|
||||
candidates = [
|
||||
candidates.reduce((a, b) =>
|
||||
Number(a.incident_id) >= Number(b.incident_id) ? a : b,
|
||||
),
|
||||
];
|
||||
}
|
||||
return candidates.length === 1
|
||||
? `https://inciweb.wildfire.gov/node/${candidates[0].incident_id}`
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The publication id inside a node link produced above, or null. */
|
||||
@@ -74,8 +79,7 @@ export function inciwebNodeId(link) {
|
||||
// whose page predates discovery by more than this is an archived
|
||||
// same-name incident from a earlier season.
|
||||
const CREATED_BEFORE_DISCOVERY_MS = 60 * 24 * 3600000;
|
||||
// Without a discovery date, require editorial activity on the page in the
|
||||
// 180 days up to the moment shown.
|
||||
// Without a discovery date, require recent editorial activity on the page.
|
||||
const CHANGED_WITHIN_MS = 180 * 24 * 3600000;
|
||||
|
||||
/**
|
||||
@@ -93,8 +97,7 @@ export function isCurrentPublication(
|
||||
return createdMs >= discoveredTime - CREATED_BEFORE_DISCOVERY_MS;
|
||||
}
|
||||
if (Number.isFinite(changedMs)) {
|
||||
const age = nowMs - changedMs;
|
||||
return age >= 0 && age <= CHANGED_WITHIN_MS;
|
||||
return nowMs - changedMs <= CHANGED_WITHIN_MS;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -129,14 +132,6 @@ export function createInciwebPublicationSource({
|
||||
};
|
||||
}
|
||||
|
||||
/** Every same-name page that could be this incident's, newest first: the own name's, else its complex's. */
|
||||
export function findInciwebLinks(publications, { name, state, complexName }) {
|
||||
const links = nodeCandidates(publications, { name, state });
|
||||
return links.length
|
||||
? links
|
||||
: nodeCandidates(publications, { name: complexName, state });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one WFIGS incident to its InciWeb page, or null.
|
||||
* The incident's own name is tried first; a member of a complex whose own
|
||||
@@ -148,8 +143,11 @@ export function findInciwebLinks(publications, { name, state, complexName }) {
|
||||
* - WFIGS row facts.
|
||||
* @returns {?string} InciWeb URL.
|
||||
*/
|
||||
export function findInciwebLink(publications, incident) {
|
||||
return findInciwebLinks(publications, incident)[0] ?? null;
|
||||
export function findInciwebLink(publications, { name, state, complexName }) {
|
||||
return (
|
||||
resolveInciwebNodeLink(publications, { name, state }) ??
|
||||
resolveInciwebNodeLink(publications, { name: complexName, state })
|
||||
);
|
||||
}
|
||||
|
||||
/** Fetch the full InciWeb incident catalog. */
|
||||
|
||||
@@ -2,7 +2,6 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
resolveInciwebNodeLink,
|
||||
createInciwebIndexSource,
|
||||
createInciwebPublicationSource,
|
||||
@@ -143,34 +142,6 @@ test('ambiguous titles disambiguate by state, then newest id', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('same-name pages list newest first, falling back to the complex', () => {
|
||||
const rows = [
|
||||
{
|
||||
incident_id: '100',
|
||||
tau: 'ORXXX Coyote Fire',
|
||||
incident_title: 'Coyote Fire',
|
||||
},
|
||||
{
|
||||
incident_id: '328922',
|
||||
tau: 'OR95S Coyote Fire',
|
||||
incident_title: 'Coyote Fire',
|
||||
},
|
||||
{ incident_id: '5', tau: 'ORXXX', incident_title: 'Big Complex' },
|
||||
];
|
||||
const incident = {
|
||||
name: 'Coyote',
|
||||
state: 'US-OR',
|
||||
complexName: 'Big Complex',
|
||||
};
|
||||
assert.deepEqual(findInciwebLinks(rows, incident), [
|
||||
'https://inciweb.wildfire.gov/node/328922',
|
||||
'https://inciweb.wildfire.gov/node/100',
|
||||
]);
|
||||
assert.deepEqual(findInciwebLinks(rows, { ...incident, name: 'Nope' }), [
|
||||
'https://inciweb.wildfire.gov/node/5',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a complex member falls back to its complex page', () => {
|
||||
assert.equal(
|
||||
findInciwebLink(catalog, {
|
||||
@@ -243,14 +214,6 @@ test('publication currency accepts pages created around or after discovery', ()
|
||||
),
|
||||
false,
|
||||
);
|
||||
// An edit after the moment shown says nothing about the page then.
|
||||
assert.equal(
|
||||
isCurrentPublication(
|
||||
{ createdMs: now - 900 * day, changedMs: now + 10 * day },
|
||||
{ discoveredTime: null, nowMs: now },
|
||||
),
|
||||
false,
|
||||
);
|
||||
// Unusable timestamps fail closed.
|
||||
assert.equal(
|
||||
isCurrentPublication(
|
||||
|
||||
+143
-277
@@ -1,64 +1,34 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import {
|
||||
findInciwebLinks,
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
perimeterAnchorDegrees,
|
||||
buildIncidentCard,
|
||||
containmentAccent,
|
||||
} from './cards.js';
|
||||
import {
|
||||
findInciwebLink,
|
||||
inciwebNodeId,
|
||||
isCurrentPublication,
|
||||
} from './inciweb.js';
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
|
||||
export {
|
||||
normalizeFirePerimeterSnapshot,
|
||||
perimeterAnchorDegrees,
|
||||
} from './records.js';
|
||||
export { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
export { createWfigsPerimeterSource } from './source.js';
|
||||
export * from './cards.js';
|
||||
export * from './inciweb.js';
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
|
||||
/**
|
||||
* Piece colours by age, newest first. A piece of unknown birth, or born after
|
||||
* the moment shown, is drawn as the oldest; the legend counts fires by
|
||||
* `lastGrowthTime` the same way.
|
||||
* Fill/line colour for a perimeter by containment progress (same ramp as the
|
||||
* card accent), as a renderer colour `[r, g, b, a]`.
|
||||
*/
|
||||
export const PERIMETER_AGE_BANDS = Object.freeze(
|
||||
[
|
||||
{ upToMs: 6 * HOUR_MS, color: '#ffc72e', label: msg('Last 6 hours') },
|
||||
{ upToMs: 24 * HOUR_MS, color: '#ff730d', label: msg('6–24 hours') },
|
||||
{ upToMs: 72 * HOUR_MS, color: '#d9290d', label: msg('1–3 days') },
|
||||
{
|
||||
upToMs: Infinity,
|
||||
color: '#730f0a',
|
||||
label: msg('Older or unknown'),
|
||||
},
|
||||
].map((band) => Object.freeze(band)),
|
||||
);
|
||||
|
||||
function perimeterAgeBand(time, atMs) {
|
||||
const last = PERIMETER_AGE_BANDS.length - 1;
|
||||
if (!Number.isFinite(time) || time > atMs) return last;
|
||||
return PERIMETER_AGE_BANDS.findIndex(({ upToMs }) => atMs - time < upToMs);
|
||||
export function containmentColor(containedPct) {
|
||||
return hexColor(containmentAccent(containedPct));
|
||||
}
|
||||
|
||||
const FILL_ALPHA = 0.35;
|
||||
const LINE_ALPHA = 0.9;
|
||||
const LINE_WIDTH_PX = 2;
|
||||
|
||||
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
|
||||
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
|
||||
const validLine = (line, min) =>
|
||||
Array.isArray(line) &&
|
||||
line.length >= min &&
|
||||
line.every(
|
||||
(point) =>
|
||||
Array.isArray(point) &&
|
||||
Number.isFinite(point[0]) &&
|
||||
Number.isFinite(point[1]),
|
||||
);
|
||||
const validAnchor = (anchor) =>
|
||||
Number.isFinite(anchor?.lon) && Number.isFinite(anchor?.lat);
|
||||
|
||||
/**
|
||||
* The draw sets the perimeters are drawn in start with this; each layer has
|
||||
@@ -82,29 +52,10 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
|
||||
/**
|
||||
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
|
||||
*
|
||||
* `source.getSnapshot({signal})` resolves to the snapshot the layer draws
|
||||
* (records.js `firePerimeterSnapshot` builds it from WFIGS):
|
||||
* - `at`: the moment shown, epoch ms, or null for now. Ages, colours and the
|
||||
* legend count from it.
|
||||
* - `fetchedAt` (epoch ms or null) and `stale`: a stale snapshot is dated by
|
||||
* its `fetchedAt`.
|
||||
* - `revision`: a string that changes whenever any piece does. Without a
|
||||
* string revision the layer redraws on every read.
|
||||
* - `note`: text the layer row shows with the legend, or null.
|
||||
* - `fires`: `id` (string), `anchor` (`{lon, lat}` degrees, where the card
|
||||
* stands), `lastGrowthTime` (epoch ms or null; the legend counts by it) and
|
||||
* the card facts (`name`, `acres`, `containedPct`, `state`,
|
||||
* `discoveredTime`, `updatedTime`, …). A fire without an id or anchor is
|
||||
* dropped. A fire may have no pieces: it keeps its card and legend count.
|
||||
* - `pieces`: `fireId` (a listed fire's id; any other piece is dropped),
|
||||
* `born` (epoch ms or null; the piece's colour), `polygons` (each
|
||||
* `[outer, ...holes]`, rings of `[lon, lat]`) and `outline` (lines of
|
||||
* `[lon, lat]` drawn as the fire line, apart from the fill, so a piece cut
|
||||
* from a larger area has no line along the cut).
|
||||
*
|
||||
* When to read again (a timeline, the camera) is the host's call, through
|
||||
* the manager's `refreshLayer`. Given a Cesium viewer with no renderer bound,
|
||||
* the caller loads the package's `./render/cesium/unbound` export first.
|
||||
* Each perimeter is a ground-clamped fill in one renderer draw set and its
|
||||
* fire line a draped line in another (`drawOf(viewer)`), made at `init`.
|
||||
* Given a Cesium viewer with no renderer bound, the
|
||||
* caller loads the package's `./render/cesium/unbound` export first.
|
||||
*/
|
||||
export function createFirePerimetersLayer({
|
||||
source,
|
||||
@@ -120,17 +71,12 @@ export function createFirePerimetersLayer({
|
||||
let _viewer = null;
|
||||
let _request = null;
|
||||
let _linkRequest = null;
|
||||
// What the sets show: the snapshot revision and each piece's age band.
|
||||
let _drawnKey = null;
|
||||
let _snapshotSignature = null;
|
||||
let _fills = null;
|
||||
let _lines = null;
|
||||
let _setIds = new Set();
|
||||
let _count = 0;
|
||||
let _lastUpdate = null;
|
||||
// The moment the snapshot shows (null: now), and the source's legend note.
|
||||
let _at = null;
|
||||
let _note = null;
|
||||
// The moment the drawn colours were computed at; the legend counts at it
|
||||
// too, so it matches the map between reads.
|
||||
let _bandsAt = null;
|
||||
// The proxy's last snapshot, served while WFIGS is unreachable.
|
||||
let _stale = false;
|
||||
let _lastError = null;
|
||||
@@ -142,26 +88,16 @@ export function createFirePerimetersLayer({
|
||||
let _inciwebIndex = [];
|
||||
let _indexFetchedAt = 0;
|
||||
let _indexFetchInFlight = false;
|
||||
let _fireById = new Map();
|
||||
/** `<set id>\n<item id>` → the fire that item belongs to. */
|
||||
const _fireByItem = new Map();
|
||||
const shownAt = () => _at ?? Date.now();
|
||||
const _linkPublications = new Map();
|
||||
// Retry failed pages on reselection or when a read finds the card linkless.
|
||||
const _linkFailures = new Set();
|
||||
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
|
||||
const _rowById = new Map();
|
||||
// Link → currency verdict from the publication check; unknown links are
|
||||
// absent. Failed checks are not cached so a transient outage retries.
|
||||
const _linkVerdicts = new Map();
|
||||
function abortLinkVerification() {
|
||||
_linkRequest?.controller.abort();
|
||||
_linkRequest = null;
|
||||
}
|
||||
|
||||
function resetSelection() {
|
||||
abortLinkVerification();
|
||||
_linkFailures.clear();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
}
|
||||
|
||||
const canSelect = () => overlayHost && inputFor && picking;
|
||||
|
||||
/**
|
||||
@@ -205,57 +141,29 @@ export function createFirePerimetersLayer({
|
||||
.getPublication(id, { signal })
|
||||
.then((publication) => {
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkPublications.set(link, publication ?? {});
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
_linkVerdicts.set(
|
||||
link,
|
||||
isCurrentPublication(publication, {
|
||||
discoveredTime: row.discoveredTime,
|
||||
}),
|
||||
);
|
||||
if (_selectedId === row.stableId) publishSelectedCard();
|
||||
})
|
||||
.catch(() => {
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkFailures.add(link);
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
// Fail closed without caching: no link now, retry on reselection.
|
||||
})
|
||||
.finally(() => {
|
||||
if (_linkRequest === request) _linkRequest = null;
|
||||
});
|
||||
}
|
||||
|
||||
function isCurrentLink(publication, row) {
|
||||
if (
|
||||
_at !== null &&
|
||||
!(Number.isFinite(publication.createdMs) && publication.createdMs <= _at)
|
||||
)
|
||||
return false;
|
||||
return isCurrentPublication(publication, {
|
||||
discoveredTime: row.discoveredTime,
|
||||
nowMs: shownAt(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The current page among verified candidates: the one whose incident began
|
||||
* nearest the fire's discovery, else (no discovery date) the newest.
|
||||
*/
|
||||
function chooseLink(links, row) {
|
||||
let best = null;
|
||||
let bestGap = Infinity;
|
||||
for (const link of links) {
|
||||
const publication = _linkPublications.get(link);
|
||||
if (!publication || !isCurrentLink(publication, row)) continue;
|
||||
const gap = Number.isFinite(row.discoveredTime)
|
||||
? Math.abs(publication.createdMs - row.discoveredTime)
|
||||
: 0;
|
||||
if (best === null || gap < bestGap) {
|
||||
best = link;
|
||||
bestGap = gap;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function publishSelectedCard() {
|
||||
if (!canSelect()) return;
|
||||
const row = _selectedId ? _fireById.get(_selectedId) : null;
|
||||
const row = _selectedId ? _rowById.get(_selectedId) : null;
|
||||
if (!row) {
|
||||
resetSelection();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
overlayHost.setEntries(
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
@@ -263,36 +171,12 @@ export function createFirePerimetersLayer({
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Live, the newest same-name page stands for the incident. A past `at`
|
||||
// checks each own-name page, since the newest may postdate it, and the
|
||||
// complex's pages only when none of those is current.
|
||||
const groups =
|
||||
_at === null
|
||||
? [findInciwebLinks(_inciwebIndex, row).slice(0, 1)]
|
||||
: [
|
||||
findInciwebLinks(_inciwebIndex, {
|
||||
name: row.name,
|
||||
state: row.state,
|
||||
}),
|
||||
findInciwebLinks(_inciwebIndex, {
|
||||
name: row.complexName,
|
||||
state: row.state,
|
||||
}),
|
||||
];
|
||||
_selectedLink = null;
|
||||
for (const links of groups) {
|
||||
const unverified = links.find(
|
||||
(link) => !_linkPublications.has(link) && !_linkFailures.has(link),
|
||||
);
|
||||
if (unverified) {
|
||||
verifyLink(unverified, row);
|
||||
break;
|
||||
}
|
||||
_selectedLink = chooseLink(links, row);
|
||||
if (_selectedLink) break;
|
||||
}
|
||||
const candidate = findInciwebLink(_inciwebIndex, row);
|
||||
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
|
||||
_selectedLink =
|
||||
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
|
||||
const card = {
|
||||
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
|
||||
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
|
||||
position: fromDegrees(row.anchor.lon, row.anchor.lat),
|
||||
};
|
||||
if (!openExternal) card.interactive = false;
|
||||
@@ -317,9 +201,11 @@ export function createFirePerimetersLayer({
|
||||
* of this layer's own sets, for an incident drawn now; else null.
|
||||
*/
|
||||
function pickedIncidentId(hit) {
|
||||
if (!hit || hit.surface) return null;
|
||||
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
|
||||
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
|
||||
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
|
||||
if (typeof hit.id !== 'string' || !hit.id.startsWith(PICK_PREFIX))
|
||||
return null;
|
||||
const incidentId = hit.id.slice(PICK_PREFIX.length).split(':')[0];
|
||||
return _rowById.has(incidentId) ? incidentId : null;
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
@@ -350,7 +236,6 @@ export function createFirePerimetersLayer({
|
||||
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
|
||||
if (incidentId) {
|
||||
abortLinkVerification();
|
||||
_linkFailures.clear();
|
||||
_selectedId = incidentId;
|
||||
publishSelectedCard();
|
||||
return;
|
||||
@@ -362,67 +247,23 @@ export function createFirePerimetersLayer({
|
||||
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
|
||||
}
|
||||
if (_selectedId) {
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
publishSelectedCard();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function drawPieces(pieces, bands) {
|
||||
const nextFills = [];
|
||||
const nextLines = [];
|
||||
const counts = new Map();
|
||||
_fireByItem.clear();
|
||||
// `fire-perimeter:<fire>:<n>` for fills, `…:<fire>:line:<n>` for lines.
|
||||
const itemId = (fireId, kind) => {
|
||||
const key = `${kind}${fireId}`;
|
||||
const n = counts.get(key) ?? 0;
|
||||
counts.set(key, n + 1);
|
||||
const id = `${PICK_PREFIX}${fireId}:${kind}${n}`;
|
||||
_fireByItem.set(`${kind ? _lines.id : _fills.id}\n${id}`, fireId);
|
||||
return id;
|
||||
};
|
||||
for (const [index, piece] of pieces.entries()) {
|
||||
const { color } = PERIMETER_AGE_BANDS[bands[index]];
|
||||
// Each exterior keeps its own holes.
|
||||
for (const rings of Array.isArray(piece.polygons) ? piece.polygons : []) {
|
||||
if (!Array.isArray(rings) || !rings.every((ring) => validLine(ring, 3)))
|
||||
continue;
|
||||
nextFills.push({
|
||||
id: itemId(piece.fireId, ''),
|
||||
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
|
||||
fill: hexColor(color, FILL_ALPHA),
|
||||
height: 'clampGround',
|
||||
});
|
||||
}
|
||||
// The fire line: the piece's outline draped on the ground, apart from
|
||||
// its fill, so a piece cut from a larger area has no line along the
|
||||
// cut (lines take ECEF, draw.d.ts `LineItem`).
|
||||
for (const line of Array.isArray(piece.outline) ? piece.outline : []) {
|
||||
if (!validLine(line, 2)) continue;
|
||||
nextLines.push({
|
||||
id: itemId(piece.fireId, 'line:'),
|
||||
positions: line.map(([lon, lat]) => fromDegrees(lon, lat)),
|
||||
widthPx: LINE_WIDTH_PX,
|
||||
mode: 'draped',
|
||||
style: { kind: 'solid', color: hexColor(color, LINE_ALPHA) },
|
||||
});
|
||||
}
|
||||
}
|
||||
_fills.set(nextFills);
|
||||
_lines.set(nextLines);
|
||||
console.log(
|
||||
`[Data:FirePerimeters] Drew ${pieces.length} pieces of ${_fireById.size} fires`,
|
||||
);
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
_clickSubscription?.();
|
||||
_clickSubscription = null;
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
resetSelection();
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
if (overlayHost) {
|
||||
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
|
||||
@@ -451,7 +292,9 @@ export function createFirePerimetersLayer({
|
||||
clampTo: 'both',
|
||||
show: false,
|
||||
});
|
||||
_setIds = new Set([_fills.id, _lines.id]);
|
||||
_viewer = viewer;
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -475,58 +318,87 @@ export function createFirePerimetersLayer({
|
||||
clearSelection();
|
||||
},
|
||||
|
||||
async update(_viewerArg, { signal } = {}) {
|
||||
async update() {
|
||||
if (!_enabled || !_fills) return false;
|
||||
_request?.abort();
|
||||
const request = new AbortController();
|
||||
_request = request;
|
||||
const abort = () => request.abort(signal.reason);
|
||||
if (signal?.aborted) abort();
|
||||
else signal?.addEventListener('abort', abort, { once: true });
|
||||
refreshInciwebIndex(request.signal);
|
||||
try {
|
||||
refreshInciwebIndex(request.signal);
|
||||
const snapshot = await source.getSnapshot({ signal: request.signal });
|
||||
// The source contract is getSnapshot; a source that can also say how
|
||||
// fresh its rows are (the WFIGS proxy) offers getSnapshotDetail.
|
||||
const snapshot =
|
||||
typeof source.getSnapshotDetail === 'function'
|
||||
? await source.getSnapshotDetail({ signal: request.signal })
|
||||
: { rows: await source.getSnapshot({ signal: request.signal }) };
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
|
||||
throw new Error(msg('Malformed perimeter snapshot'));
|
||||
const { rows } = snapshot;
|
||||
_stale = snapshot.stale === true;
|
||||
// A stale snapshot is as old as its fetch, not this poll.
|
||||
const updatedAt =
|
||||
_stale && Number.isFinite(snapshot.fetchedAt)
|
||||
? snapshot.fetchedAt
|
||||
: Date.now();
|
||||
_at = Number.isFinite(snapshot.at) ? snapshot.at : null;
|
||||
_note = typeof snapshot.note === 'string' ? snapshot.note : null;
|
||||
// A fire needs an id and the anchor its card stands on; a piece
|
||||
// needs its fire.
|
||||
const fires = new Map();
|
||||
for (const fire of snapshot.fires)
|
||||
if (typeof fire?.id === 'string' && validAnchor(fire.anchor))
|
||||
fires.set(fire.id, fire);
|
||||
const pieces = snapshot.pieces.filter((piece) =>
|
||||
fires.has(piece?.fireId),
|
||||
|
||||
// Incident facts may change independently of the polygon's source clock.
|
||||
const signature = JSON.stringify(
|
||||
rows
|
||||
.map(({ polygons, ...facts }) => facts)
|
||||
.sort((a, b) => a.stableId.localeCompare(b.stableId)),
|
||||
);
|
||||
const atMs = shownAt();
|
||||
const bands = pieces.map((piece) => perimeterAgeBand(piece.born, atMs));
|
||||
const drawKey =
|
||||
typeof snapshot.revision === 'string'
|
||||
? `${snapshot.revision}\n${bands.join('')}`
|
||||
: null;
|
||||
_fireById = fires;
|
||||
_bandsAt = atMs;
|
||||
if (drawKey === null || drawKey !== _drawnKey) {
|
||||
drawPieces(pieces, bands);
|
||||
_drawnKey = drawKey;
|
||||
if (signature === _snapshotSignature) {
|
||||
if (_selectedId) publishSelectedCard();
|
||||
_lastUpdate = updatedAt;
|
||||
_lastError = null;
|
||||
return true;
|
||||
}
|
||||
// Refresh (or drop) the selected incident's card against the new
|
||||
// snapshot: its ages move with `at` even when nothing is redrawn.
|
||||
if (_selectedId) {
|
||||
if (_selectedLink === null && !_linkRequest) _linkFailures.clear();
|
||||
publishSelectedCard();
|
||||
abortLinkVerification();
|
||||
const nextFills = [];
|
||||
const nextLines = [];
|
||||
_rowById.clear();
|
||||
for (const row of rows) {
|
||||
const color = containmentColor(row.containedPct);
|
||||
for (const [index, rings] of row.polygons.entries()) {
|
||||
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
|
||||
// Each exterior keeps its own holes.
|
||||
nextFills.push({
|
||||
id,
|
||||
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
|
||||
fill: withAlpha(color, 0.25),
|
||||
height: 'clampGround',
|
||||
});
|
||||
// The fire line: the exterior ring draped on the ground (lines
|
||||
// take ECEF, draw.d.ts `LineItem`).
|
||||
nextLines.push({
|
||||
id,
|
||||
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
|
||||
widthPx: 2,
|
||||
mode: 'draped',
|
||||
style: { kind: 'solid', color: withAlpha(color, 0.9) },
|
||||
});
|
||||
}
|
||||
// Keep a geometry-free projection: the coordinate arrays would
|
||||
// otherwise be retained for the layer's lifetime while only the
|
||||
// anchor is ever read again.
|
||||
const { polygons, ...facts } = row;
|
||||
_rowById.set(row.stableId, {
|
||||
...facts,
|
||||
anchor: perimeterAnchorDegrees(polygons),
|
||||
});
|
||||
}
|
||||
|
||||
_fills.set(nextFills);
|
||||
_lines.set(nextLines);
|
||||
_snapshotSignature = signature;
|
||||
// Refresh (or drop) the selected incident's card against the new feed.
|
||||
if (_selectedId) publishSelectedCard();
|
||||
_count = rows.length;
|
||||
_lastUpdate = updatedAt;
|
||||
_lastError = null;
|
||||
console.log(
|
||||
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
@@ -537,7 +409,6 @@ export function createFirePerimetersLayer({
|
||||
_stale = false;
|
||||
return false;
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
if (_request === request) _request = null;
|
||||
}
|
||||
},
|
||||
@@ -547,20 +418,18 @@ export function createFirePerimetersLayer({
|
||||
_request = null;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
_fireById = new Map();
|
||||
_fireByItem.clear();
|
||||
_drawnKey = null;
|
||||
_at = null;
|
||||
_bandsAt = null;
|
||||
_note = null;
|
||||
_rowById.clear();
|
||||
_snapshotSignature = null;
|
||||
_inciwebIndex = [];
|
||||
_indexFetchedAt = 0;
|
||||
_linkPublications.clear();
|
||||
_linkVerdicts.clear();
|
||||
_viewer = null;
|
||||
_enabled = false;
|
||||
_fills?.dispose();
|
||||
_lines?.dispose();
|
||||
_fills = _lines = null;
|
||||
_setIds = new Set();
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -573,15 +442,11 @@ export function createFirePerimetersLayer({
|
||||
? Math.max(1, Math.floor(maxCount))
|
||||
: 2000;
|
||||
const result = [];
|
||||
for (const fire of _fireById.values()) {
|
||||
for (const row of _rowById.values()) {
|
||||
if (result.length >= limit) break;
|
||||
const { anchor, id, ...facts } = fire;
|
||||
// A time after the moment shown is unknown in this snapshot.
|
||||
if (_at !== null)
|
||||
for (const key of ['discoveredTime', 'updatedTime', 'lastGrowthTime'])
|
||||
if (facts[key] > _at) facts[key] = null;
|
||||
const { anchor, stableId, ...facts } = row;
|
||||
result.push({
|
||||
id,
|
||||
id: stableId,
|
||||
...facts,
|
||||
lat: anchor.lat,
|
||||
lon: anchor.lon,
|
||||
@@ -590,33 +455,34 @@ export function createFirePerimetersLayer({
|
||||
return result;
|
||||
},
|
||||
|
||||
/** The moment the analyst records show: the snapshot's `at`, or null for now. */
|
||||
getAnalystRecordsAt() {
|
||||
return _at;
|
||||
},
|
||||
|
||||
getRowControls() {
|
||||
const atMs = _bandsAt;
|
||||
const counts = PERIMETER_AGE_BANDS.map(() => 0);
|
||||
for (const fire of _fireById.values())
|
||||
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
|
||||
const bands = [
|
||||
{ label: t('Not contained or unknown'), color: containmentAccent(0) },
|
||||
{ label: t('Under 50% contained'), color: containmentAccent(1) },
|
||||
{ label: t('50–99% contained'), color: containmentAccent(50) },
|
||||
{ label: t('Fully contained'), color: containmentAccent(100) },
|
||||
];
|
||||
return {
|
||||
chips: [],
|
||||
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
|
||||
label: t(band.label),
|
||||
color: band.color,
|
||||
count: counts[index],
|
||||
legend: bands.map((band, index) => ({
|
||||
...band,
|
||||
count: [..._rowById.values()].filter(
|
||||
(row) => containmentAccent(row.containedPct) === band.color,
|
||||
).length,
|
||||
...(index === 0
|
||||
? { blurb: t('Colour shows the age of each area.') }
|
||||
? {
|
||||
blurb: t(
|
||||
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
})),
|
||||
...(_note ? { info: t(_note) } : {}),
|
||||
};
|
||||
},
|
||||
|
||||
getStats() {
|
||||
return {
|
||||
count: _fireById.size,
|
||||
count: _count,
|
||||
lastUpdate: _lastUpdate,
|
||||
error: _lastError,
|
||||
stale: _stale,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,14 +1,3 @@
|
||||
/**
|
||||
* WFIGS perimeters: the proxy's rows (normalizeFirePerimeterSnapshot) and
|
||||
* the snapshot the layer draws (firePerimeterSnapshot).
|
||||
*
|
||||
* The server and the package's `./layers/perimeters/source` export import
|
||||
* this module, so it marks text with msg() only. The layer translates `note`
|
||||
* when it shows it.
|
||||
*/
|
||||
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
|
||||
/**
|
||||
* Normalize a WFIGS feed, skipping individually invalid features.
|
||||
* Only a payload that is not a feature collection at all rejects the whole
|
||||
@@ -91,7 +80,6 @@ export function normalizeFirePerimeterSnapshot(geojson) {
|
||||
: null,
|
||||
discoveredTime: finiteOrNull(properties.attr_FireDiscoveryDateTime),
|
||||
updatedTime: finiteOrNull(properties.poly_DateCurrent),
|
||||
polygonTime: finiteOrNull(properties.poly_PolygonDateTime),
|
||||
cause: textOrNull(properties.attr_FireCause),
|
||||
behavior: textOrNull(properties.attr_FireBehaviorGeneral),
|
||||
personnel: finiteOrNull(properties.attr_TotalIncidentPersonnel),
|
||||
@@ -104,114 +92,3 @@ export function normalizeFirePerimeterSnapshot(geojson) {
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Shoelace area along short longitude edges (degree², relative sizes only). */
|
||||
function ringArea(ring) {
|
||||
let sum = 0;
|
||||
let [x1, y1] = ring[0];
|
||||
for (let i = 1; i < ring.length; i++) {
|
||||
let delta = ring[i][0] - ring[i - 1][0];
|
||||
if (delta > 180) delta -= 360;
|
||||
else if (delta < -180) delta += 360;
|
||||
const x2 = x1 + delta;
|
||||
const y2 = ring[i][1];
|
||||
sum += x1 * y2 - x2 * y1;
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
}
|
||||
return Math.abs(sum / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor point for the incident card: the vertex mean of the largest polygon's
|
||||
* outer ring, with circular longitude. Callers own the Cartesian conversion.
|
||||
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
|
||||
* @returns {{lon: number, lat: number}}
|
||||
*/
|
||||
export function perimeterAnchorDegrees(polygons) {
|
||||
let best = null;
|
||||
let bestArea = -1;
|
||||
for (const rings of polygons) {
|
||||
const outer = rings[0];
|
||||
const area = ringArea(outer);
|
||||
if (area > bestArea) {
|
||||
bestArea = area;
|
||||
best = outer;
|
||||
}
|
||||
}
|
||||
// Vertex mean over the closed ring (first == last point dropped): perimeters
|
||||
// are compact enough that this stays inside or near the polygon.
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let lat = 0;
|
||||
const count = best.length - 1;
|
||||
const toRad = Math.PI / 180;
|
||||
for (let i = 0; i < count; i++) {
|
||||
sinLon += Math.sin(best[i][0] * toRad);
|
||||
cosLon += Math.cos(best[i][0] * toRad);
|
||||
lat += best[i][1];
|
||||
}
|
||||
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
|
||||
}
|
||||
|
||||
/** WFIGS times up to this far ahead of our clock (clock skew) are taken as now; later ones are unknown. */
|
||||
const CLOCK_SKEW_MS = 10 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The WFIGS snapshot for the Fire Perimeters layer (contract:
|
||||
* `createFirePerimetersLayer`), from the proxy's rows.
|
||||
*
|
||||
* WFIGS keeps one perimeter per fire, so each of its polygons is one piece,
|
||||
* born when the perimeter was mapped (`poly_PolygonDateTime`, else the
|
||||
* record's last edit `poly_DateCurrent`).
|
||||
* @param {object[]} rows - normalizeFirePerimeterSnapshot rows.
|
||||
* @param {{fetchedAt?: number|null, stale?: boolean, now?: number}} [options]
|
||||
* @returns {{at: null, fetchedAt: number|null, stale: boolean,
|
||||
* revision: string, note: string, fires: object[], pieces: object[]}}
|
||||
*/
|
||||
export function firePerimeterSnapshot(
|
||||
rows,
|
||||
{ fetchedAt = null, stale = false, now = Date.now() } = {},
|
||||
) {
|
||||
const fires = [];
|
||||
const pieces = [];
|
||||
const versions = [];
|
||||
for (const row of rows) {
|
||||
const { stableId, polygons, polygonTime, ...facts } = row;
|
||||
const mapped = polygonTime ?? facts.updatedTime;
|
||||
const grown =
|
||||
Number.isFinite(mapped) && mapped <= now + CLOCK_SKEW_MS
|
||||
? Math.min(mapped, now)
|
||||
: null;
|
||||
fires.push({
|
||||
...facts,
|
||||
id: stableId,
|
||||
lastGrowthTime: grown,
|
||||
anchor: perimeterAnchorDegrees(polygons),
|
||||
});
|
||||
for (const rings of polygons)
|
||||
pieces.push({
|
||||
fireId: stableId,
|
||||
born: grown,
|
||||
polygons: [rings],
|
||||
outline: rings,
|
||||
});
|
||||
// Without poly_DateCurrent, the mapping time and outline stand in for it.
|
||||
versions.push(
|
||||
Number.isFinite(facts.updatedTime)
|
||||
? `${stableId}@${facts.updatedTime}`
|
||||
: `${stableId}@${polygonTime ?? ''}:${JSON.stringify(polygons)}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
at: null,
|
||||
fetchedAt: Number.isFinite(fetchedAt) ? fetchedAt : null,
|
||||
stale: stale === true,
|
||||
revision: versions.sort().join('|'),
|
||||
note: msg(
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
|
||||
),
|
||||
fires,
|
||||
pieces,
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
perimeterAnchorDegrees,
|
||||
normalizeFirePerimeterSnapshot,
|
||||
firePerimeterSnapshot,
|
||||
} from './records.js';
|
||||
import { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
|
||||
const ring = [
|
||||
[-108.1, 35.2],
|
||||
@@ -26,7 +22,6 @@ function feature(overrides = {}) {
|
||||
attr_IncidentTypeCategory: 'WF',
|
||||
attr_FireDiscoveryDateTime: 1757900000000,
|
||||
poly_DateCurrent: 1757950000000,
|
||||
poly_PolygonDateTime: 1757940000000,
|
||||
attr_FireCause: 'Natural',
|
||||
attr_FireBehaviorGeneral: 'Active',
|
||||
attr_TotalIncidentPersonnel: 380,
|
||||
@@ -64,7 +59,6 @@ test('a valid snapshot yields one row per incident with polygons preserved', ()
|
||||
category: 'WF',
|
||||
discoveredTime: 1757900000000,
|
||||
updatedTime: 1757950000000,
|
||||
polygonTime: 1757940000000,
|
||||
cause: 'Natural',
|
||||
behavior: 'Active',
|
||||
personnel: 380,
|
||||
@@ -96,7 +90,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
attr_IncidentTypeCategory: null,
|
||||
attr_FireDiscoveryDateTime: null,
|
||||
poly_DateCurrent: null,
|
||||
poly_PolygonDateTime: null,
|
||||
attr_FireCause: null,
|
||||
attr_FireBehaviorGeneral: null,
|
||||
attr_TotalIncidentPersonnel: null,
|
||||
@@ -117,7 +110,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
category: rows[0].category,
|
||||
discoveredTime: rows[0].discoveredTime,
|
||||
updatedTime: rows[0].updatedTime,
|
||||
polygonTime: rows[0].polygonTime,
|
||||
cause: rows[0].cause,
|
||||
behavior: rows[0].behavior,
|
||||
personnel: rows[0].personnel,
|
||||
@@ -134,7 +126,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
category: null,
|
||||
discoveredTime: null,
|
||||
updatedTime: null,
|
||||
polygonTime: null,
|
||||
cause: null,
|
||||
behavior: null,
|
||||
personnel: null,
|
||||
@@ -208,223 +199,3 @@ test('a perimeter with no rings is skipped rather than rendered empty', () => {
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].stableId, 'other');
|
||||
});
|
||||
|
||||
const NOW = 1758000000000;
|
||||
const rowsOf = (...features) => normalizeFirePerimeterSnapshot({ features });
|
||||
// feature() replaces all properties with the overrides' own: keep the rest.
|
||||
const fixture = (id, properties) =>
|
||||
feature({ id, properties: { ...feature().properties, ...properties } });
|
||||
|
||||
test('each WFIGS polygon becomes one piece of its fire, born when it was mapped', () => {
|
||||
const hole = [
|
||||
[-108.08, 35.22],
|
||||
[-108.02, 35.22],
|
||||
[-108.02, 35.25],
|
||||
[-108.08, 35.22],
|
||||
];
|
||||
const snapshot = firePerimeterSnapshot(
|
||||
rowsOf(
|
||||
feature({
|
||||
geometry: { type: 'MultiPolygon', coordinates: [[ring, hole], [ring]] },
|
||||
}),
|
||||
),
|
||||
{ fetchedAt: NOW - 1000, now: NOW },
|
||||
);
|
||||
assert.equal(snapshot.at, null);
|
||||
assert.equal(snapshot.stale, false);
|
||||
assert.equal(snapshot.fetchedAt, NOW - 1000);
|
||||
assert.equal(
|
||||
snapshot.note,
|
||||
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
|
||||
);
|
||||
assert.equal(snapshot.fires.length, 1);
|
||||
const [fire] = snapshot.fires;
|
||||
assert.equal(fire.id, '2026-NMGNF-000123');
|
||||
assert.equal(fire.lastGrowthTime, 1757940000000);
|
||||
assert.equal(fire.containedPct, 40);
|
||||
assert.equal('stableId' in fire || 'polygons' in fire, false);
|
||||
assert.ok(Math.abs(fire.anchor.lat - 35.2333) < 0.01);
|
||||
assert.deepEqual(
|
||||
snapshot.pieces.map(({ fireId, born, polygons, outline }) => [
|
||||
fireId,
|
||||
born,
|
||||
polygons,
|
||||
outline,
|
||||
]),
|
||||
[
|
||||
['2026-NMGNF-000123', 1757940000000, [[ring, hole]], [ring, hole]],
|
||||
['2026-NMGNF-000123', 1757940000000, [[ring]], [ring]],
|
||||
],
|
||||
'the outline is every ring, holes included',
|
||||
);
|
||||
});
|
||||
|
||||
test('a perimeter without its mapping time falls back to the last edit; a future time is unknown', () => {
|
||||
const [fallback, future, futureEdit, none] = firePerimeterSnapshot(
|
||||
rowsOf(
|
||||
fixture(1, { poly_PolygonDateTime: null }),
|
||||
fixture(2, {
|
||||
attr_UniqueFireIdentifier: 'future',
|
||||
poly_PolygonDateTime: NOW + 3600000,
|
||||
}),
|
||||
fixture(3, {
|
||||
attr_UniqueFireIdentifier: 'future-edit',
|
||||
poly_PolygonDateTime: null,
|
||||
poly_DateCurrent: NOW + 3600000,
|
||||
}),
|
||||
fixture(4, {
|
||||
attr_UniqueFireIdentifier: 'none',
|
||||
poly_PolygonDateTime: null,
|
||||
poly_DateCurrent: null,
|
||||
}),
|
||||
),
|
||||
{ now: NOW },
|
||||
).fires;
|
||||
assert.equal(fallback.lastGrowthTime, 1757950000000);
|
||||
assert.equal(future.lastGrowthTime, null);
|
||||
assert.equal(futureEdit.lastGrowthTime, null);
|
||||
assert.equal(none.lastGrowthTime, null);
|
||||
// A clock a few minutes ahead of ours is taken as now.
|
||||
const skewed = firePerimeterSnapshot(
|
||||
rowsOf(fixture(1, { poly_PolygonDateTime: NOW + 60000 })),
|
||||
{ now: NOW },
|
||||
);
|
||||
assert.equal(skewed.fires[0].lastGrowthTime, NOW);
|
||||
assert.equal(skewed.pieces[0].born, NOW);
|
||||
});
|
||||
|
||||
test('the revision follows fire ids and update times, not feed order', () => {
|
||||
const a = feature();
|
||||
const b = fixture(2, { attr_UniqueFireIdentifier: 'b' });
|
||||
const revision = (...features) =>
|
||||
firePerimeterSnapshot(rowsOf(...features), { now: NOW }).revision;
|
||||
assert.equal(revision(a, b), revision(b, a));
|
||||
assert.notEqual(
|
||||
revision(a, b),
|
||||
revision(
|
||||
a,
|
||||
fixture(2, { attr_UniqueFireIdentifier: 'b', poly_DateCurrent: 1 }),
|
||||
),
|
||||
);
|
||||
assert.notEqual(revision(a, b), revision(a));
|
||||
|
||||
const undated = fixture(1, { poly_DateCurrent: null });
|
||||
const shifted = ring.map(([lon, lat]) => [lon + 1, lat]);
|
||||
assert.notEqual(
|
||||
revision(undated),
|
||||
revision({
|
||||
...undated,
|
||||
geometry: { type: 'Polygon', coordinates: [shifted] },
|
||||
}),
|
||||
);
|
||||
assert.notEqual(
|
||||
revision(undated),
|
||||
revision(
|
||||
fixture(1, {
|
||||
poly_DateCurrent: null,
|
||||
poly_PolygonDateTime: NOW,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('the snapshot carries staleness', () => {
|
||||
const snapshot = firePerimeterSnapshot(rowsOf(feature()), {
|
||||
stale: true,
|
||||
fetchedAt: 'yesterday',
|
||||
now: NOW,
|
||||
});
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.fetchedAt, null);
|
||||
assert.deepEqual(
|
||||
snapshot.fires.map(({ id }) => id),
|
||||
['2026-NMGNF-000123'],
|
||||
);
|
||||
});
|
||||
|
||||
const square = [
|
||||
[-108.2, 35.0],
|
||||
[-108.0, 35.0],
|
||||
[-108.0, 35.2],
|
||||
[-108.2, 35.2],
|
||||
[-108.2, 35.0],
|
||||
];
|
||||
const tiny = [
|
||||
[-107.01, 34.0],
|
||||
[-107.0, 34.0],
|
||||
[-107.0, 34.01],
|
||||
[-107.01, 34.0],
|
||||
];
|
||||
|
||||
test('the card anchors at the vertex mean of the largest polygon', () => {
|
||||
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
|
||||
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
|
||||
});
|
||||
|
||||
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
|
||||
const vertices = [
|
||||
[179, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
];
|
||||
for (let start = 0; start < vertices.length; start++) {
|
||||
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
|
||||
for (const points of [rotated, [...rotated].reverse()]) {
|
||||
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
|
||||
for (const boundary of [-180, 180]) {
|
||||
const ring = [
|
||||
[179, 10],
|
||||
[boundary, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
[179, 10],
|
||||
];
|
||||
const anchor = perimeterAnchorDegrees([[ring]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('multipart cards compare polygon areas along short dateline edges', () => {
|
||||
const ordinary = [
|
||||
[10, 20],
|
||||
[11, 20],
|
||||
[11, 21],
|
||||
[10, 21],
|
||||
[10, 20],
|
||||
];
|
||||
for (const width of [0.2, 2]) {
|
||||
const crossing = [
|
||||
[180 - width / 2, 10],
|
||||
[-180 + width / 2, 10],
|
||||
[-180 + width / 2, 10 + width],
|
||||
[180 - width / 2, 10 + width],
|
||||
[180 - width / 2, 10],
|
||||
];
|
||||
for (const ring of [crossing, [...crossing].reverse()]) {
|
||||
for (const polygons of [
|
||||
[[ring], [ordinary]],
|
||||
[[ordinary], [ring]],
|
||||
]) {
|
||||
const anchor = perimeterAnchorDegrees(polygons);
|
||||
if (width < 1) {
|
||||
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
|
||||
} else {
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,35 +1,42 @@
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { firePerimeterSnapshot } from './records.js';
|
||||
|
||||
// Failures stay English data. The Layers panel shows them translated.
|
||||
// A portable export (package.json): no i18n here. Failures stay English data;
|
||||
// the Layers panel shows them translated.
|
||||
const msg = (text) => text;
|
||||
|
||||
/** Request a snapshot through the bounded, same-origin WFIGS proxy. */
|
||||
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
|
||||
export function createWfigsPerimeterSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
} = {}) {
|
||||
/**
|
||||
* The rows with how fresh they are: the proxy answers from its last
|
||||
* snapshot, marked stale, while WFIGS is unreachable.
|
||||
* @returns {Promise<{rows: object[], stale: boolean, fetchedAt: number|null}>}
|
||||
*/
|
||||
async function getSnapshotDetail({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/fire-perimeters', { signal });
|
||||
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
|
||||
const payload = await readResponseJsonCapped(
|
||||
response,
|
||||
80 * 1024 * 1024,
|
||||
signal,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
if (!Array.isArray(payload?.rows))
|
||||
throw new Error(msg('Malformed perimeter snapshot'));
|
||||
return {
|
||||
rows: payload.rows,
|
||||
stale: payload.stale === true,
|
||||
fetchedAt: Number.isFinite(payload.fetchedAt) ? payload.fetchedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Current perimeters as fires and their pieces (firePerimeterSnapshot).
|
||||
* The proxy answers from its last snapshot, marked stale, while WFIGS is
|
||||
* unreachable.
|
||||
*/
|
||||
async getSnapshot({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/fire-perimeters', { signal });
|
||||
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
|
||||
const payload = await readResponseJsonCapped(
|
||||
response,
|
||||
80 * 1024 * 1024,
|
||||
signal,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
if (!Array.isArray(payload?.rows))
|
||||
throw new Error(msg('Malformed perimeter snapshot'));
|
||||
return firePerimeterSnapshot(payload.rows, {
|
||||
fetchedAt: payload.fetchedAt,
|
||||
stale: payload.stale === true,
|
||||
});
|
||||
/** The perimeter rows (see getSnapshotDetail for staleness). */
|
||||
async getSnapshot(options = {}) {
|
||||
return (await getSnapshotDetail(options)).rows;
|
||||
},
|
||||
getSnapshotDetail,
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,7 @@ const validPayload = {
|
||||
],
|
||||
};
|
||||
|
||||
test('a successful response yields the snapshot of fires and pieces', async () => {
|
||||
test('a successful response yields normalized perimeter rows', async () => {
|
||||
let requested;
|
||||
const source = createWfigsPerimeterSource({
|
||||
fetchImpl: async (url) => {
|
||||
@@ -30,13 +30,9 @@ test('a successful response yields the snapshot of fires and pieces', async () =
|
||||
});
|
||||
},
|
||||
});
|
||||
const snapshot = await source.getSnapshot();
|
||||
assert.deepEqual(
|
||||
snapshot.fires.map((fire) => fire.id),
|
||||
['2026-NMGNF-000123'],
|
||||
);
|
||||
assert.deepEqual(snapshot.pieces[0].polygons, [[ring]]);
|
||||
assert.equal(snapshot.at, null);
|
||||
const rows = await source.getSnapshot();
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
|
||||
assert.equal(requested, '/api/fire-perimeters');
|
||||
});
|
||||
|
||||
@@ -164,20 +160,22 @@ test('a failed refresh serves the last snapshot marked stale for a day, then ref
|
||||
assert.equal((await ask()).status, 502, 'a day-old snapshot is not served');
|
||||
});
|
||||
|
||||
test('the snapshot carries the proxy staleness and fetch time', async () => {
|
||||
test('the snapshot detail carries the proxy staleness and fetch time', async () => {
|
||||
const fetchedAt = Date.UTC(2026, 9, 25, 12);
|
||||
const source = createWfigsPerimeterSource({
|
||||
fetchImpl: async () => Response.json({ rows: [], stale: true, fetchedAt }),
|
||||
});
|
||||
const snapshot = await source.getSnapshot();
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.fetchedAt, fetchedAt);
|
||||
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
|
||||
assert.deepEqual(await source.getSnapshotDetail(), {
|
||||
rows: [],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshot(), []);
|
||||
});
|
||||
|
||||
test('getSnapshot works when taken off its source object', async () => {
|
||||
const { getSnapshot } = createWfigsPerimeterSource({
|
||||
fetchImpl: async () => Response.json({ rows: [] }),
|
||||
});
|
||||
assert.deepEqual((await getSnapshot()).fires, []);
|
||||
assert.deepEqual(await getSnapshot(), []);
|
||||
});
|
||||
@@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => {
|
||||
};
|
||||
await assert.rejects(
|
||||
searchHls({
|
||||
box: { west: -181, south: 0, east: -179, north: 1 },
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
fetchImpl,
|
||||
}),
|
||||
/±180/,
|
||||
/dateline/,
|
||||
);
|
||||
await assert.rejects(
|
||||
searchHls({ box: BOX, now: 'never', fetchImpl }),
|
||||
@@ -251,22 +251,6 @@ test('an invalid box or clock is refused before any request', async () => {
|
||||
assert.equal(called, false);
|
||||
});
|
||||
|
||||
test('a dateline box goes to CMR as it is: CMR reads west > east as the short box', async () => {
|
||||
const calls = [];
|
||||
const result = await searchHls({
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
days: 2,
|
||||
now: '2026-09-21T00:00:00Z',
|
||||
fetchImpl: async (url) => {
|
||||
calls.push(url);
|
||||
return response({ json: { hits: 1, items: [ummItem({})] } });
|
||||
},
|
||||
});
|
||||
assert.equal(calls.length, 2, 'one search per product');
|
||||
assert.ok(calls.every((url) => url.includes('bounding_box=179,0,-179,1')));
|
||||
assert.ok(result.candidates.some((candidate) => candidate.product === 'S30'));
|
||||
});
|
||||
|
||||
test('CMR pages follow the CMR-Search-After cursor up to 2,000 records and truncation stays honest', async () => {
|
||||
const items = (count) =>
|
||||
Array.from({ length: count }, (_, i) => ummItem({ conceptId: `G-${i}` }));
|
||||
|
||||
@@ -581,8 +581,6 @@ export function createRecentImageryLayer({
|
||||
for (const slotId of SLOT_IDS) {
|
||||
const candidate = candidateFor(shown[slotId]);
|
||||
if (candidate && _hostInfo.collection) {
|
||||
const { availableBoxes, emptyBoxes } =
|
||||
thumbnails.get(candidate.key) ?? {};
|
||||
renderer.showSlot(slotId, candidate, _box, {
|
||||
alpha: _alpha,
|
||||
splitDirection: !live
|
||||
@@ -590,8 +588,6 @@ export function createRecentImageryLayer({
|
||||
: (slotId === 'a') !== _swapped
|
||||
? 'left'
|
||||
: 'right',
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
});
|
||||
} else {
|
||||
renderer.hideSlot(slotId);
|
||||
@@ -901,22 +897,21 @@ export function createRecentImageryLayer({
|
||||
// The new automatic day's probe may have been cancelled off-screen.
|
||||
requestThumbnails();
|
||||
}
|
||||
if (pruned) syncRender();
|
||||
const followed =
|
||||
Boolean(_followKey) &&
|
||||
_followKey === _focusKey &&
|
||||
drapable(candidateFor(_followKey)) &&
|
||||
applyPreview(_followKey);
|
||||
// A pinned or previewed day that was still being probed drapes now.
|
||||
const shown = plan();
|
||||
const owned = renderer.getOwned?.() || {};
|
||||
const drapesChanged = SLOT_IDS.some(
|
||||
(slotId) => (owned[slotId]?.key || null) !== shown[slotId],
|
||||
);
|
||||
// One render per probe: the key can stay the same while its halves change.
|
||||
// A host found moved changes the divider, so the panel renders in full.
|
||||
const moved = !followed && syncHost();
|
||||
if (!followed) syncRender();
|
||||
if (drapesChanged && !pruned && !followed) syncRender();
|
||||
notify('thumbnail');
|
||||
if (pruned || followed || drapesChanged || moved) notify();
|
||||
if (pruned || followed || drapesChanged) notify();
|
||||
});
|
||||
syncHost();
|
||||
if (_box && !_candidates.length) void runSearch();
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import assert from 'node:assert/strict';
|
||||
import { until } from '../../testSupport/kartaViewFakes.mjs';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { boxKey, nonCrossingBoxes } from './model.js';
|
||||
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
|
||||
import { acquireImageryComparison } from '../../maps/imageryComparison.js';
|
||||
import { MapSourceController } from '../../maps/controller.js';
|
||||
@@ -18,16 +14,11 @@ import {
|
||||
SPLIT_PUBLISH_MS,
|
||||
createRecentImageryLayer,
|
||||
} from './index.js';
|
||||
import {
|
||||
createImageryBoxPreview,
|
||||
createRecentImageryRenderer,
|
||||
} from './rendering.js';
|
||||
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
|
||||
import { createImageryBoxPreview } from './rendering.js';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import {
|
||||
BOX,
|
||||
CANDIDATES,
|
||||
FIJI_BOX,
|
||||
boxToolFakes,
|
||||
candidate,
|
||||
fakeCatalog,
|
||||
@@ -1573,424 +1564,6 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy
|
||||
assert.equal(f.snap().notice, 'Search cancelled');
|
||||
});
|
||||
|
||||
test('a box dragged across the dateline is searched, listed and draped as one box', async () => {
|
||||
const f = fixture();
|
||||
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
|
||||
f.layer.enable();
|
||||
assert.equal(f.layer.setBox(box), true);
|
||||
assert.equal(f.snap().boxError, null);
|
||||
assert.deepEqual(f.catalog.searches.at(-1).request.box, box);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.equal(f.snap().candidates.length, 4);
|
||||
assert.equal(f.snap().preview.key, S18);
|
||||
assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped');
|
||||
assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°');
|
||||
});
|
||||
|
||||
test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => {
|
||||
const f = fixture();
|
||||
const priorGet = f.thumbnails.get;
|
||||
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
let boxes = [west];
|
||||
f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes });
|
||||
f.layer.enable();
|
||||
f.layer.setBox(box);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
f.thumbnails.probeRequested();
|
||||
const slot = Object.keys(f.owned()).find((id) => f.owned()[id]);
|
||||
assert.ok(slot, 'a day is already on the map');
|
||||
const key = f.owned()[slot].key;
|
||||
assert.deepEqual(f.owned()[slot].availableBoxes, [west]);
|
||||
boxes = [west, east];
|
||||
f.thumbnails.probe(key, 'present');
|
||||
assert.deepEqual(f.owned()[slot].availableBoxes, boxes);
|
||||
f.layer.destroy();
|
||||
});
|
||||
|
||||
const sideOf = (url) =>
|
||||
Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0
|
||||
? 'west'
|
||||
: 'east';
|
||||
/** A snapshot response; `present: null` sends no Data-Present header. */
|
||||
const snapshotAnswer = (present, status = 200) =>
|
||||
new Response('img', {
|
||||
status,
|
||||
headers: present === null ? {} : { 'Data-Present': String(present) },
|
||||
});
|
||||
|
||||
function realLayer({
|
||||
fetchImpl,
|
||||
candidates,
|
||||
maxDecoded = 16,
|
||||
halfDeadlineMs = 50,
|
||||
}) {
|
||||
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs });
|
||||
let nextUrl = 0;
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
createObjectUrl: () => `blob:${++nextUrl}`,
|
||||
revokeObjectUrl: () => {},
|
||||
maxDecoded,
|
||||
});
|
||||
const globe = fakeGlobePort();
|
||||
const layer = createRecentImageryLayer({
|
||||
catalog: {
|
||||
searchHls: async () => ({ candidates, truncated: false, errors: [] }),
|
||||
},
|
||||
renderer: createRecentImageryRenderer(),
|
||||
thumbnails: loader,
|
||||
host: () => ({ collection: globe.imagery, kind: 'globe' }),
|
||||
globeOf: () => globe,
|
||||
now: () => new Date('2026-11-13T15:00:00Z'),
|
||||
});
|
||||
layer.init({ camera: {} });
|
||||
return { layer, loader, globe };
|
||||
}
|
||||
|
||||
test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-10');
|
||||
const sides = [];
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async (url) => {
|
||||
const side = sideOf(url);
|
||||
sides.push(side);
|
||||
return snapshotAnswer(side === 'east');
|
||||
},
|
||||
});
|
||||
layer.setSources({ viirs: true });
|
||||
layer.enable();
|
||||
assert.equal(layer.setBox(FIJI_BOX), true);
|
||||
// The probe asks about both halves, wider first. The layer drapes the one with data.
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length > 0, { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(sides, ['east', 'west']);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[nonCrossingBoxes(FIJI_BOX)[1]],
|
||||
);
|
||||
assert.equal(loader.get(day.key).status, 'present');
|
||||
const snapshot = layer.getSnapshot();
|
||||
assert.equal(snapshot.candidates[0].thumbnail.status, 'present');
|
||||
assert.equal(snapshot.candidates[0].drapable, true);
|
||||
assert.equal(snapshot.auto?.key, day.key);
|
||||
layer.destroy();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
});
|
||||
|
||||
test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-10');
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async () => snapshotAnswer(false),
|
||||
});
|
||||
layer.setSources({ viirs: true });
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(
|
||||
layer.getSnapshot().candidates.some((c) => c.key === day.key),
|
||||
false,
|
||||
'an empty day leaves the strip',
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
for (const [label, box] of [
|
||||
['a plain box', { west: -98, south: 30, east: -97, north: 31 }],
|
||||
['a dateline box', FIJI_BOX],
|
||||
]) {
|
||||
test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async () => {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(box);
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length === nonCrossingBoxes(box).length, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const before = [...globe.layers];
|
||||
const added = globe.added.length;
|
||||
release();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(globe.added.length, added);
|
||||
assert.deepEqual(globe.layers, before);
|
||||
layer.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => {
|
||||
const day1 = candidate('VIIRS', '2026-11-10');
|
||||
const day2 = candidate('VIIRS', '2026-11-11');
|
||||
let eastCalls = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((resolve) => {
|
||||
releaseDay2 = resolve;
|
||||
});
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) await gate;
|
||||
else if (sideOf(url) === 'east' && ++eastCalls === 2)
|
||||
throw new TypeError('Failed to fetch');
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.setSources({ hls: false, viirs: true });
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day2.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
layer.setAssignment('a', day1.key);
|
||||
assert.equal(
|
||||
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).status, 'present');
|
||||
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[west, east],
|
||||
'a half that failed on the re-probe stays draped',
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => {
|
||||
const day1 = candidate('S30', '2026-11-10');
|
||||
const day2 = candidate('S30', '2026-11-11');
|
||||
let eastCalls = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((r) => (releaseDay2 = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
}
|
||||
if (sideOf(url) === 'east') {
|
||||
eastCalls += 1;
|
||||
if (eastCalls === 1) return snapshotAnswer(false);
|
||||
throw new TypeError('Failed to fetch');
|
||||
}
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const [west] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
assert.equal(loader.get(day1.key).emptyBoxes.length, 1);
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day2.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
layer.setAssignment('a', day1.key);
|
||||
assert.equal(
|
||||
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day1.key);
|
||||
assert.deepEqual(
|
||||
{
|
||||
available: entry.availableBoxes.length,
|
||||
empty: entry.emptyBoxes.length,
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ available: 1, empty: 1, layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
let release;
|
||||
const gate = new Promise((r) => (release = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async () => {
|
||||
await gate;
|
||||
return snapshotAnswer(null);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox({ west: -98, south: 30, east: -97, north: 31 });
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length === 1, { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
release();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
await until(() => false, { ticks: 50 });
|
||||
assert.equal(globe.layers.length, 1);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
for (const [label, failEast] of [
|
||||
['answers 503', async () => snapshotAnswer(null, 503)],
|
||||
[
|
||||
'rejects',
|
||||
async () => {
|
||||
throw new TypeError('Failed to fetch');
|
||||
},
|
||||
],
|
||||
['never answers', () => new Promise(() => {})],
|
||||
]) {
|
||||
test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async (url) =>
|
||||
sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(),
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key)?.status === 'error', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
layer.setAssignment('a', day.key);
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day.key);
|
||||
const [west] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
{
|
||||
empty: (entry.emptyBoxes ?? []).map(boxKey),
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ empty: [boxKey(west)], layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => {
|
||||
const day1 = candidate('S30', '2026-11-10');
|
||||
const day2 = candidate('S30', '2026-11-11');
|
||||
let round = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((r) => (releaseDay2 = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
}
|
||||
if (round === 0)
|
||||
return sideOf(url) === 'west'
|
||||
? snapshotAnswer(true)
|
||||
: snapshotAnswer(null);
|
||||
return sideOf(url) === 'west'
|
||||
? snapshotAnswer(null)
|
||||
: snapshotAnswer(false);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key)?.status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
round = 1;
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(
|
||||
() =>
|
||||
loader.get(day2.key)?.status === 'present' &&
|
||||
loader.get(day1.key).objectUrl === null,
|
||||
{ ticks: 2000 },
|
||||
),
|
||||
true,
|
||||
);
|
||||
layer.setAssignment('a', day1.key);
|
||||
await until(() => false, { ticks: 50 });
|
||||
await until(() => !loader.get(day1.key).loading, { ticks: 2000 });
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day1.key);
|
||||
const [, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
{
|
||||
status: entry.status,
|
||||
empty: (entry.emptyBoxes ?? []).map(boxKey),
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ status: 'present', empty: [boxKey(east)], layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => {
|
||||
for (const order of [
|
||||
[S18, V15],
|
||||
|
||||
@@ -72,11 +72,13 @@ export const PRODUCTS = Object.freeze({
|
||||
|
||||
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||
const toRadians = (degrees) => (degrees * Math.PI) / 180;
|
||||
/** A longitude brought back into ±180 after one step past it. */
|
||||
const wrapLon = (value) =>
|
||||
value > 180 ? value - 360 : value < -180 ? value + 360 : value;
|
||||
const pad2 = (value) => String(value).padStart(2, '0');
|
||||
|
||||
/**
|
||||
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
|
||||
* east are not swapped: west > east crosses the dateline and `validateBox`
|
||||
* rejects it. Null when any edge is nonfinite.
|
||||
*/
|
||||
/** A box edge as a number, or null when it is missing, blank or not numeric. */
|
||||
function edgeNumber(value) {
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
||||
@@ -85,11 +87,6 @@ function edgeNumber(value) {
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
|
||||
* east are not swapped: west > east is the short arc across the dateline.
|
||||
* Null when any edge is nonfinite.
|
||||
*/
|
||||
function normalizeBox(box) {
|
||||
if (!box || typeof box !== 'object') return null;
|
||||
const [west, south, east, north] = [
|
||||
@@ -108,45 +105,8 @@ function normalizeBox(box) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Degrees of longitude going east from `west` to `east`. A west > east pair
|
||||
* wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and
|
||||
* `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`,
|
||||
* even the long way round.
|
||||
* @param {number} west Degrees.
|
||||
* @param {number} east Degrees.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function lonSpanDeg(west, east) {
|
||||
return east >= west ? east - west : east + 360 - west;
|
||||
}
|
||||
|
||||
/** A comparable key for a degrees box. */
|
||||
export const boxKey = (box) =>
|
||||
[box.west, box.south, box.east, box.north].map(Number).join(',');
|
||||
|
||||
/**
|
||||
* One or two boxes with west <= east that cover the same area. A dateline
|
||||
* box is split at ±180 so each side is a plain rectangle for a draped layer
|
||||
* or a Worldview request. A box with a missing or nonfinite edge is [].
|
||||
* So is a dateline box of zero width (west 180, east -180).
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function nonCrossingBoxes(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
if (!normalized) return [];
|
||||
const { west, south, east, north } = normalized;
|
||||
if (!(west > east)) return [normalized];
|
||||
const parts = [];
|
||||
if (west < 180) parts.push({ west, south, east: 180, north });
|
||||
if (east > -180) parts.push({ west: -180, south, east, north });
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Side lengths of a box in km: the longitude span at its mid-latitude (the
|
||||
* short arc when the box crosses the dateline; a west <= east box is not
|
||||
* shortened), and its latitude span.
|
||||
* Side lengths of a box in km: the box's own longitude span (never the
|
||||
* shorter way round the globe) at its mid-latitude, and its latitude span.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ width: number, height: number }}
|
||||
*/
|
||||
@@ -156,7 +116,7 @@ export function boxSideKm(box) {
|
||||
const midLat = (normalized.south + normalized.north) / 2;
|
||||
return {
|
||||
width:
|
||||
lonSpanDeg(normalized.west, normalized.east) *
|
||||
(normalized.east - normalized.west) *
|
||||
KM_PER_DEG_LAT *
|
||||
Math.cos(toRadians(midLat)),
|
||||
height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,
|
||||
@@ -166,11 +126,9 @@ export function boxSideKm(box) {
|
||||
const refuse = (reason, message) => ({ ok: false, reason, message });
|
||||
|
||||
/**
|
||||
* Validate a selection box for the catalog and the tile providers. A box
|
||||
* with west > east is the short arc across the dateline and is accepted
|
||||
* when that arc is under the size cap.
|
||||
* Validate a selection box for the catalog and the tile providers.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
|
||||
* @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
|
||||
*/
|
||||
export function validateBox(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
@@ -178,6 +136,8 @@ export function validateBox(box) {
|
||||
const { west, south, east, north } = normalized;
|
||||
if (Math.abs(west) > 180 || Math.abs(east) > 180)
|
||||
return refuse('invalid', msg('Longitudes must be within ±180°'));
|
||||
if (west > east)
|
||||
return refuse('dateline', msg('Select one side of the dateline'));
|
||||
if (
|
||||
Math.abs(south) > MERCATOR_LAT_LIMIT ||
|
||||
Math.abs(north) > MERCATOR_LAT_LIMIT
|
||||
@@ -186,7 +146,7 @@ export function validateBox(box) {
|
||||
'polar',
|
||||
`Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,
|
||||
);
|
||||
if (lonSpanDeg(west, east) === 0 || north === south)
|
||||
if (east === west || north === south)
|
||||
return refuse('degenerate', msg('Box must enclose an area'));
|
||||
const { width, height } = boxSideKm(normalized);
|
||||
if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM)
|
||||
@@ -223,9 +183,7 @@ export function fitViewHeightM({ width, height, fovy } = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The centre of a box, in degrees. A dateline box (west > east) is centred
|
||||
* on the short arc, not the arithmetic mean, which would be the other side
|
||||
* of the globe.
|
||||
* The centre of a box that does not cross the dateline, in degrees.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ lon: number, lat: number } | null}
|
||||
*/
|
||||
@@ -233,18 +191,14 @@ export function boxCentre(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
if (!normalized) return null;
|
||||
return {
|
||||
lon: wrapLon(
|
||||
normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2,
|
||||
),
|
||||
lon: (normalized.west + normalized.east) / 2,
|
||||
lat: (normalized.south + normalized.north) / 2,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A square box centred on a pin, `sideKm` on the ground (the east–west extent
|
||||
* widens by 1/cos(lat)); null when the result would not validate. A pin whose
|
||||
* box passes ±180 gets the short-arc box (west > east), the same convention
|
||||
* as a dragged dateline box, with edges wrapped into ±180.
|
||||
* widens by 1/cos(lat)); null when the result would not validate.
|
||||
* @param {number} lon Degrees.
|
||||
* @param {number} lat Degrees.
|
||||
* @param {number} [sideKm]
|
||||
@@ -253,19 +207,16 @@ export function boxCentre(box) {
|
||||
export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) {
|
||||
if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0)
|
||||
return null;
|
||||
if (Math.abs(lon) > 180) return null;
|
||||
const cosLat = Math.cos(toRadians(lat));
|
||||
if (cosLat <= 0) return null;
|
||||
const halfLat = sideKm / 2 / KM_PER_DEG_LAT;
|
||||
const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat);
|
||||
// A half-width of 90° or more is not a short arc; refuse rather than wrap.
|
||||
if (halfLon >= 90) return null;
|
||||
const clampLat = (value) =>
|
||||
Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value));
|
||||
const result = validateBox({
|
||||
west: wrapLon(lon - halfLon),
|
||||
west: lon - halfLon,
|
||||
south: clampLat(lat - halfLat),
|
||||
east: wrapLon(lon + halfLon),
|
||||
east: lon + halfLon,
|
||||
north: clampLat(lat + halfLat),
|
||||
});
|
||||
return result.ok ? result.box : null;
|
||||
@@ -498,31 +449,15 @@ export function coverageFor(candidate, box) {
|
||||
.filter((ring) => Array.isArray(ring) && ring.length >= 3);
|
||||
if (!normalized || !footprints.length) return 'unknown';
|
||||
const { west, south, east, north } = normalized;
|
||||
const centre = boxCentre(normalized);
|
||||
// A dateline box is one continuous range starting at its west edge. A
|
||||
// longitude on the east side (at or past ±180) shifts by 360. One just
|
||||
// outside the west corner stays put: shifting every value below west would
|
||||
// send that corner the long way round and miss a footprint that covers it.
|
||||
const crossing = west > east;
|
||||
const project = (lon) =>
|
||||
crossing && lon < west && (lon <= east || lon - east < west - lon)
|
||||
? lon + 360
|
||||
: lon;
|
||||
const samples = [
|
||||
[project(west), south],
|
||||
[project(east), south],
|
||||
[project(east), north],
|
||||
[project(west), north],
|
||||
[project(centre.lon), centre.lat],
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
[(west + east) / 2, (south + north) / 2],
|
||||
];
|
||||
return samples.every(([lon, lat]) =>
|
||||
footprints.some((ring) =>
|
||||
pointInPolygon(
|
||||
lon,
|
||||
lat,
|
||||
crossing ? ring.map(([x, y]) => [project(x), y]) : ring,
|
||||
),
|
||||
),
|
||||
footprints.some((ring) => pointInPolygon(lon, lat, ring)),
|
||||
)
|
||||
? 'full'
|
||||
: 'partial';
|
||||
@@ -671,10 +606,6 @@ export function wvsSnapshotUrl({
|
||||
const normalized = normalizeBox(box);
|
||||
if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);
|
||||
if (!normalized) throw new TypeError('A finite box is required');
|
||||
// Worldview Snapshots rejects a BBOX whose west is greater than its east
|
||||
// (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse.
|
||||
if (normalized.west > normalized.east)
|
||||
throw new TypeError('A snapshot cannot cross the dateline');
|
||||
const bbox = [
|
||||
normalized.south,
|
||||
normalized.west,
|
||||
|
||||
@@ -3,8 +3,6 @@ import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
boxFromPin,
|
||||
lonSpanDeg,
|
||||
nonCrossingBoxes,
|
||||
boxFromRectangle,
|
||||
boxSideKm,
|
||||
coverageFor,
|
||||
@@ -53,20 +51,11 @@ function hls(product, day, clouds, extra = {}) {
|
||||
return { ...groupGranulesByDay(granules)[0], ...extra };
|
||||
}
|
||||
|
||||
test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => {
|
||||
test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {
|
||||
const reason = (box) => validateBox(box).reason;
|
||||
const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 });
|
||||
assert.equal(dateline.ok, true);
|
||||
assert.equal(dateline.box.west, 179);
|
||||
assert.equal(dateline.box.east, -179);
|
||||
assert.equal(
|
||||
reason({ west: 170, south: 0, east: -170, north: 1 }),
|
||||
'too-large',
|
||||
'a 20° dateline arc is still over the 1,000 km cap',
|
||||
);
|
||||
assert.equal(
|
||||
reason({ west: 180, south: 0, east: -180, north: 1 }),
|
||||
'degenerate',
|
||||
reason({ west: 179, south: 0, east: -179, north: 1 }),
|
||||
'dateline',
|
||||
);
|
||||
assert.equal(
|
||||
reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),
|
||||
@@ -81,6 +70,10 @@ test('validateBox refuses polar, degenerate, invalid and oversized boxes, and ac
|
||||
validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message,
|
||||
'Imagery stops at ±85.05° latitude',
|
||||
);
|
||||
assert.equal(
|
||||
validateBox({ west: 179, south: 0, east: -179, north: 1 }).message,
|
||||
'Select one side of the dateline',
|
||||
);
|
||||
assert.equal(
|
||||
validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok,
|
||||
true,
|
||||
@@ -144,14 +137,10 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400
|
||||
lon: 10,
|
||||
lat: 5,
|
||||
});
|
||||
assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), {
|
||||
lon: 180,
|
||||
lat: 1,
|
||||
});
|
||||
assert.equal(boxCentre(null), null);
|
||||
});
|
||||
|
||||
test('box width is the longitude span at the mid-latitude; a dateline box uses the short arc', () => {
|
||||
test('box width is the longitude span at the mid-latitude, never the shortest arc', () => {
|
||||
const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 });
|
||||
assert.ok(Math.abs(equator.width - 111.32) < 1e-6);
|
||||
assert.ok(Math.abs(equator.height - 111.32) < 1e-6);
|
||||
@@ -160,13 +149,6 @@ test('box width is the longitude span at the mid-latitude; a dateline box uses t
|
||||
const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 };
|
||||
assert.ok(boxSideKm(nearlyGlobal).width > 30000);
|
||||
assert.equal(validateBox(nearlyGlobal).reason, 'too-large');
|
||||
const crossing = boxSideKm({
|
||||
west: 179,
|
||||
south: -0.5,
|
||||
east: -179,
|
||||
north: 0.5,
|
||||
});
|
||||
assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width));
|
||||
});
|
||||
|
||||
test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => {
|
||||
@@ -185,12 +167,7 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha
|
||||
assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1);
|
||||
assert.equal(boxFromPin(NaN, 0), null);
|
||||
assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap');
|
||||
assert.equal(boxFromPin(181, 0), null, 'longitude out of range');
|
||||
assert.equal(
|
||||
boxFromPin(0, 0, 400000),
|
||||
null,
|
||||
'half-width of 90 degrees or more',
|
||||
);
|
||||
assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');
|
||||
assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');
|
||||
assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');
|
||||
});
|
||||
@@ -321,34 +298,6 @@ test('coverage samples the box corners and centre against the union of footprint
|
||||
assert.equal(coverageFor(withRings(null), BOX), 'unknown');
|
||||
});
|
||||
|
||||
test('coverage of a dateline box uses the short arc, not the long way', () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const ring = (west, east, south = -0.1, north = 1.1) => [
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
];
|
||||
const withRings = (...rings) => ({
|
||||
granules: rings.map((footprint) => granule({ footprint })),
|
||||
});
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(178.5, -178.5)), box),
|
||||
'full',
|
||||
'one footprint that crosses ±180',
|
||||
);
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box),
|
||||
'full',
|
||||
'a pair split exactly at ±180',
|
||||
);
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(179, 180)), box),
|
||||
'partial',
|
||||
'one side does not cover the other',
|
||||
);
|
||||
});
|
||||
|
||||
test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => {
|
||||
const candidates = [
|
||||
hls('S30', '2026-09-20', [10, null]),
|
||||
@@ -480,17 +429,6 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e
|
||||
() => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }),
|
||||
TypeError,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
wvsSnapshotUrl({
|
||||
product: 'S30',
|
||||
day: '2026-09-18',
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
width: 64,
|
||||
height: 64,
|
||||
}),
|
||||
/snapshot cannot cross the dateline/,
|
||||
);
|
||||
});
|
||||
|
||||
test('thumbnails load the focused card, then the visible cards outward, then the margins', () => {
|
||||
@@ -499,52 +437,3 @@ test('thumbnails load the focused card, then the visible cards outward, then the
|
||||
assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]);
|
||||
assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []);
|
||||
});
|
||||
|
||||
test('boxFromPin returns the short-arc box for a pin near the dateline', () => {
|
||||
const near = (a, b) => Math.abs(a - b) < 1e-6;
|
||||
const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492
|
||||
const spanOk = (box) => {
|
||||
const { width, height } = boxSideKm(box);
|
||||
assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`);
|
||||
assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`);
|
||||
assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span');
|
||||
};
|
||||
// 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side.
|
||||
for (const lon of [179.9, -179.9]) {
|
||||
const box = boxFromPin(lon, 0);
|
||||
spanOk(box);
|
||||
assert.ok(box.west < box.east, `no wrap needed at ${lon}`);
|
||||
assert.ok(near((box.west + box.east) / 2, lon));
|
||||
}
|
||||
// A pin on the line, or close enough that the box passes it, wraps.
|
||||
for (const lon of [180, -180, 179.99, -179.99]) {
|
||||
const box = boxFromPin(lon, 0);
|
||||
spanOk(box);
|
||||
assert.ok(box.west > box.east, `crossing at ${lon}`);
|
||||
assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180');
|
||||
assert.ok(
|
||||
near(
|
||||
box.west,
|
||||
(lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half,
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
nonCrossingBoxes(box).length,
|
||||
2,
|
||||
'splits for tiling and Worldview',
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon),
|
||||
) < 1e-6,
|
||||
);
|
||||
}
|
||||
// 0 is an ordinary box.
|
||||
const mid = boxFromPin(0, 0);
|
||||
spanOk(mid);
|
||||
assert.ok(mid.west < mid.east && near(mid.west, -half));
|
||||
// Off the equator the east-west extent widens but stays a short arc.
|
||||
const high = boxFromPin(-179.99, 60);
|
||||
spanOk(high);
|
||||
assert.ok(high.west > high.east);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Recent Imagery drapes two slots through the renderer's globe port, slot
|
||||
* `a` left of a swipe and slot `b` right. Each slot drapes up to two GIBS
|
||||
* layers, one per available part, on whichever surface the map stack draws.
|
||||
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
|
||||
* imagery layers (slot `a`, left of a swipe; slot `b`, right) through the
|
||||
* renderer's globe port, draped on whichever surface the map stack draws.
|
||||
* Against the basemap slot `a` splits left and slot `b` stays empty. Tile
|
||||
* requests pass a small semaphore of our own, shared by both slots, through
|
||||
* each layer's admission hook; the renderer's own request limits stay
|
||||
@@ -15,13 +15,7 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { markBaseTileset } from '../../render/baseTilesets.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import {
|
||||
PRODUCTS,
|
||||
boxKey,
|
||||
gibsTemplate,
|
||||
lonSpanDeg,
|
||||
nonCrossingBoxes,
|
||||
} from './model.js';
|
||||
import { PRODUCTS, gibsTemplate } from './model.js';
|
||||
|
||||
const SLOT_IDS = ['a', 'b'];
|
||||
const SPLITS = new Set(['left', 'right', 'none']);
|
||||
@@ -35,27 +29,8 @@ function clampAlpha(value) {
|
||||
return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;
|
||||
}
|
||||
|
||||
/** One comparable key for a slot's draped parts. */
|
||||
const partsKey = (parts) => parts.map(boxKey).sort().join(';');
|
||||
|
||||
/**
|
||||
* The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would
|
||||
* draw an empty side black, so it drapes only parts Worldview confirmed
|
||||
* present, and no part of a dateline box before the probe answers. A PNG
|
||||
* drapes every part not confirmed empty.
|
||||
*/
|
||||
function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) {
|
||||
const parts = nonCrossingBoxes(box);
|
||||
const keys = (list) => new Set(list.map(boxKey));
|
||||
if (PRODUCTS[candidate.product]?.format !== 'jpg') {
|
||||
if (!Array.isArray(emptyBoxes)) return parts;
|
||||
const empty = keys(emptyBoxes);
|
||||
return parts.filter((part) => !empty.has(boxKey(part)));
|
||||
}
|
||||
if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts;
|
||||
const proven = keys(availableBoxes);
|
||||
return parts.filter((part) => proven.has(boxKey(part)));
|
||||
}
|
||||
const boxKey = (box) =>
|
||||
[box.west, box.south, box.east, box.north].map(Number).join(',');
|
||||
|
||||
/**
|
||||
* Admit a tile request while the semaphore has room. A request that finds
|
||||
@@ -102,7 +77,7 @@ export function createRecentImageryRenderer({
|
||||
let host = NO_HOST;
|
||||
let destroyed = false;
|
||||
const admission = { limit: maxTileRequests, inFlight: 0 };
|
||||
/** @type {Record<'a'|'b', null | { layers: Array<object>, globe: object, candidate: object, parts: Array<object>, alpha: number, split: string }>} */
|
||||
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
|
||||
const owned = { a: null, b: null };
|
||||
const admit = admitTileRequests(admission, requestRender);
|
||||
|
||||
@@ -130,53 +105,36 @@ export function createRecentImageryRenderer({
|
||||
const record = owned[slotId];
|
||||
if (!record) return false;
|
||||
owned[slotId] = null;
|
||||
for (const layer of record.layers) layer.remove();
|
||||
record.layer.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
function applyLook(record) {
|
||||
for (const layer of record.layers) {
|
||||
layer.alpha = record.alpha;
|
||||
layer.split = SPLITS.has(record.split) ? record.split : 'none';
|
||||
}
|
||||
record.layer.alpha = record.alpha;
|
||||
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
|
||||
}
|
||||
|
||||
function mount(slotId, { candidate, parts, alpha, split }) {
|
||||
if (!parts.length) return false;
|
||||
owned[slotId] = {
|
||||
layers: parts.map((part) =>
|
||||
host.globe.imagery.add(specFor(candidate, part)),
|
||||
),
|
||||
globe: host.globe,
|
||||
candidate,
|
||||
parts,
|
||||
alpha,
|
||||
split,
|
||||
};
|
||||
function mount(slotId, { candidate, box, alpha, split }) {
|
||||
const layer = host.globe.imagery.add(specFor(candidate, box));
|
||||
owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split };
|
||||
applyLook(owned[slotId]);
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Drape the parts of a candidate's box that the evidence allows (see drapedParts).
|
||||
* The same candidate on the same port keeps the layer of each unchanged part.
|
||||
* Drape a candidate into a slot. The same candidate on the same host only
|
||||
* updates its look; anything else replaces the slot's layer.
|
||||
* @param {'a'|'b'} slotId
|
||||
* @param {object} candidate
|
||||
* @param {object} box Degrees box.
|
||||
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look]
|
||||
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]
|
||||
* @returns {boolean} Whether a layer is now draped for the slot.
|
||||
*/
|
||||
showSlot(
|
||||
slotId,
|
||||
candidate,
|
||||
box,
|
||||
{
|
||||
alpha = 1,
|
||||
splitDirection = 'none',
|
||||
availableBoxes = null,
|
||||
emptyBoxes = null,
|
||||
} = {},
|
||||
{ alpha = 1, splitDirection = 'none' } = {},
|
||||
) {
|
||||
if (destroyed || !candidate?.key || !box) return false;
|
||||
if (!host.globe) {
|
||||
@@ -185,52 +143,21 @@ export function createRecentImageryRenderer({
|
||||
}
|
||||
const current = owned[slotId];
|
||||
const look = { alpha: clampAlpha(alpha), split: splitDirection };
|
||||
const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes });
|
||||
if (
|
||||
current &&
|
||||
current.globe === host.globe &&
|
||||
current.candidate.key === candidate.key &&
|
||||
parts.length
|
||||
boxKey(current.box) === boxKey(box)
|
||||
) {
|
||||
if (partsKey(current.parts) !== partsKey(parts)) {
|
||||
const previous = new Map(
|
||||
current.parts.map((part, i) => [boxKey(part), current.layers[i]]),
|
||||
);
|
||||
// A new half goes right above the slot's surviving half, so both
|
||||
// halves keep the same place against the other slot.
|
||||
const survivor = parts
|
||||
.map((part) => previous.get(boxKey(part)))
|
||||
.find(Boolean);
|
||||
const at = survivor
|
||||
? host.globe.imagery.list().indexOf(survivor) + 1
|
||||
: undefined;
|
||||
const layers = parts.map((part) => {
|
||||
const key = boxKey(part);
|
||||
const layer = previous.get(key);
|
||||
previous.delete(key);
|
||||
return (
|
||||
layer ?? host.globe.imagery.add(specFor(candidate, part), at)
|
||||
);
|
||||
});
|
||||
for (const layer of previous.values()) layer.remove();
|
||||
Object.assign(current, { layers, parts, ...look });
|
||||
applyLook(current);
|
||||
requestRender('recent-imagery-show');
|
||||
} else if (
|
||||
current.alpha !== look.alpha ||
|
||||
current.split !== look.split
|
||||
) {
|
||||
if (current.alpha !== look.alpha || current.split !== look.split) {
|
||||
Object.assign(current, look);
|
||||
applyLook(current);
|
||||
requestRender('recent-imagery-look');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const removed = removeOwned(slotId);
|
||||
if (!mount(slotId, { candidate, parts, ...look })) {
|
||||
if (removed) requestRender('recent-imagery-hide');
|
||||
return false;
|
||||
}
|
||||
removeOwned(slotId);
|
||||
mount(slotId, { candidate, box, ...look });
|
||||
requestRender('recent-imagery-show');
|
||||
return true;
|
||||
},
|
||||
@@ -294,7 +221,7 @@ export function createRecentImageryRenderer({
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */
|
||||
/** Number of layers this renderer owns (never above two). */
|
||||
ownedCount() {
|
||||
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
|
||||
},
|
||||
@@ -320,11 +247,11 @@ let previewSeq = 0;
|
||||
|
||||
/** A box with no area has no fill: a press, or a drag along one axis. */
|
||||
const hasArea = (box) =>
|
||||
Boolean(box) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south;
|
||||
Boolean(box) && box.east > box.west && box.north > box.south;
|
||||
|
||||
/** A box with no extent draws nothing: a press that has not moved yet. */
|
||||
const hasExtent = (box) =>
|
||||
Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south);
|
||||
Boolean(box) && (box.east > box.west || box.north > box.south);
|
||||
|
||||
/**
|
||||
* The box tool's preview: the box being dragged, a translucent fill and a
|
||||
|
||||
@@ -5,9 +5,7 @@ import {
|
||||
createImageryBoxPreview,
|
||||
createRecentImageryRenderer,
|
||||
} from './rendering.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { boxKey, nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX } from './testDoubles.mjs';
|
||||
import { BOX } from './testDoubles.mjs';
|
||||
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
@@ -273,210 +271,3 @@ test('the box preview draws a ground fill and a draped dashed edge, hidden rathe
|
||||
box = { west: -96, south: 32, east: -95, north: 33 };
|
||||
assert.doesNotThrow(() => preview.changed());
|
||||
});
|
||||
|
||||
test('a dateline box drapes one layer on each side of ±180 and removes both', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
assert.equal(
|
||||
renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }),
|
||||
true,
|
||||
);
|
||||
assert.equal(renderer.ownedCount(), 1);
|
||||
assert.equal(globe.layers.length, 2);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((item) => item.spec.rectangle),
|
||||
[
|
||||
{ west: 179, south: 0, east: 180, north: 1 },
|
||||
{ west: -180, south: 0, east: -179, north: 1 },
|
||||
],
|
||||
);
|
||||
assert.equal(globe.layers[0].alpha, 0.4);
|
||||
assert.equal(globe.layers[1].alpha, 0.4);
|
||||
assert.equal(globe.layers[0].split, 'left');
|
||||
assert.equal(globe.layers[1].split, 'left');
|
||||
renderer.setAlpha('a', 0.2);
|
||||
assert.equal(globe.layers[0].alpha, 0.2);
|
||||
assert.equal(globe.layers[1].alpha, 0.2);
|
||||
renderer.showSlot('a', S30, box, { alpha: 0.2 });
|
||||
assert.equal(globe.added.length, 2, 'the same box does not remount');
|
||||
renderer.hideSlot('a');
|
||||
assert.equal(globe.layers.length, 0);
|
||||
});
|
||||
|
||||
test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.equal(
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[east],
|
||||
);
|
||||
renderer.showSlot('b', VIIRS, FIJI_BOX, {
|
||||
availableBoxes: [east, west],
|
||||
splitDirection: 'right',
|
||||
});
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.split),
|
||||
['none', 'right', 'right'],
|
||||
);
|
||||
assert.equal(globe.layers.length, 3);
|
||||
|
||||
const next = fakeGlobePort();
|
||||
renderer.rebind({ collection: {}, kind: 'globe', globe: next });
|
||||
assert.deepEqual(
|
||||
next.layers.map((layer) => layer.spec.rectangle),
|
||||
[east, west, east],
|
||||
);
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] });
|
||||
assert.equal(next.layers.length, 4);
|
||||
renderer.destroy();
|
||||
assert.equal(next.layers.length, 0);
|
||||
});
|
||||
|
||||
test('no allowed half, or halves of another box, drapes nothing', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
for (const availableBoxes of [[], [BOX]]) {
|
||||
assert.equal(
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }),
|
||||
false,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(renderer.showSlot('a', VIIRS, BOX), true);
|
||||
assert.equal(globe.layers.length, 1);
|
||||
assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true);
|
||||
assert.equal(globe.layers.length, 3);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('evidence going from none to empty removes the drape', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
renderer.showSlot('a', S30, FIJI_BOX);
|
||||
assert.equal(globe.layers.length, 2);
|
||||
assert.equal(
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
availableBoxes: [],
|
||||
emptyBoxes: nonCrossingBoxes(FIJI_BOX),
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => {
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
for (const [product, expected] of [
|
||||
[S30, [west, east]],
|
||||
[VIIRS, [east]],
|
||||
]) {
|
||||
const { renderer, globe } = fixture();
|
||||
renderer.showSlot('a', product, FIJI_BOX, {
|
||||
availableBoxes: [east],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
expected,
|
||||
);
|
||||
renderer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => {
|
||||
const renderer = createRecentImageryRenderer();
|
||||
const globe = fakeGlobePort();
|
||||
renderer.rebind({ collection: {}, kind: 'globe', globe });
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
const layerFor = (box) =>
|
||||
globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box));
|
||||
|
||||
// An HLS day drapes both halves before its probe answers.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' });
|
||||
const kept = layerFor(west);
|
||||
assert.ok(kept);
|
||||
const added = globe.added.length;
|
||||
|
||||
// The probe confirms the east half empty: only the east layer goes.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
alpha: 0.4,
|
||||
splitDirection: 'left',
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [east],
|
||||
});
|
||||
assert.equal(kept.removed, false, 'the west layer survives the narrowing');
|
||||
assert.equal(globe.added.length, added, 'narrowing adds no layer');
|
||||
assert.equal(layerFor(east), undefined);
|
||||
|
||||
// A later probe admits east again: only the east layer is added.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
alpha: 0.4,
|
||||
splitDirection: 'left',
|
||||
availableBoxes: [west, east],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
assert.equal(kept.removed, false, 'the west layer survives the widening');
|
||||
assert.equal(globe.added.length, added + 1);
|
||||
assert.equal(kept.alpha, 0.4);
|
||||
assert.equal(kept.split, 'left');
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('widening slot a over the dateline keeps it below slot b on both sides', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
const topOn = (box) =>
|
||||
globe.layers
|
||||
.filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box))
|
||||
.at(-1)
|
||||
.spec.url.includes('S30')
|
||||
? 'A'
|
||||
: 'B';
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] });
|
||||
renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] });
|
||||
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] });
|
||||
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('the drag preview draws a wrapped fill and outline across the dateline', async () => {
|
||||
const draw = fakeDrawPort();
|
||||
let box = { west: 179, south: 0, east: 179, north: 0 };
|
||||
const preview = createImageryBoxPreview({}, () => box, { draw });
|
||||
const [fills, outlines] = draw.sets.values();
|
||||
preview.setVisible(true);
|
||||
|
||||
box = { ...box, east: -179 };
|
||||
preview.changed();
|
||||
assert.equal(fills.items.size, 0);
|
||||
assert.equal(outlines.items.get('edge').show, true);
|
||||
assert.deepEqual(
|
||||
outlines.items.get('edge').positions[1],
|
||||
fromDegrees(-179, 0),
|
||||
);
|
||||
|
||||
box = { ...box, north: 1 };
|
||||
preview.changed();
|
||||
assert.equal(fills.items.get('box').show, true);
|
||||
assert.deepEqual(fills.items.get('box').geometry.rect, box);
|
||||
const edge = outlines.items.get('edge');
|
||||
assert.equal(edge.show, true);
|
||||
assert.deepEqual(edge.positions, [
|
||||
fromDegrees(179, 0),
|
||||
fromDegrees(-179, 0),
|
||||
fromDegrees(-179, 1),
|
||||
fromDegrees(179, 1),
|
||||
fromDegrees(179, 0),
|
||||
]);
|
||||
await preview.destroy();
|
||||
});
|
||||
@@ -1,107 +1,10 @@
|
||||
import { searchHls } from './catalog.js';
|
||||
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
|
||||
|
||||
/**
|
||||
* Deadline for one half's response headers, so a day whose other half
|
||||
* answered is not held at "checking".
|
||||
*/
|
||||
const DEFAULT_HALF_DEADLINE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Worldview Snapshots rejects a BBOX with west > east, so a dateline box is
|
||||
* probed as its two non-crossing halves, wider first. A plain box is its
|
||||
* one normalized half. A day has data when either half does.
|
||||
*/
|
||||
function requestBoxes(box) {
|
||||
return nonCrossingBoxes(box).sort(
|
||||
(a, b) => b.east - b.west - (a.east - a.west),
|
||||
);
|
||||
}
|
||||
|
||||
/** A response's Data-Present answer in lower case, or '' when it failed or has none. */
|
||||
export const dataPresent = (response) =>
|
||||
response?.ok
|
||||
? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase()
|
||||
: '';
|
||||
|
||||
/**
|
||||
* One half's snapshot fetch, raced against its own deadline so a half that
|
||||
* never answers, even over a transport that ignores AbortSignal, still
|
||||
* settles. Its deadline cancels only this half. The caller can cancel it
|
||||
* at any time, including while its body is being read.
|
||||
*/
|
||||
function probeHalf(
|
||||
url,
|
||||
{ fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl },
|
||||
) {
|
||||
const controller = new AbortController();
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = null;
|
||||
const finishTimeout = () => {
|
||||
if (timer !== null) clearTimeoutImpl(timer);
|
||||
timer = null;
|
||||
};
|
||||
const stop = (reason) => {
|
||||
controller.abort(reason);
|
||||
finishTimeout();
|
||||
// Settle even if the transport ignores abort.
|
||||
reject(reason);
|
||||
};
|
||||
if (signal?.aborted) {
|
||||
stop(signal.reason);
|
||||
return;
|
||||
}
|
||||
signal?.addEventListener('abort', () => stop(signal.reason), {
|
||||
once: true,
|
||||
});
|
||||
if (deadlineMs > 0)
|
||||
timer = setTimeoutImpl(
|
||||
() =>
|
||||
stop(new DOMException('Thumbnail half timed out', 'TimeoutError')),
|
||||
deadlineMs,
|
||||
);
|
||||
let promise;
|
||||
try {
|
||||
promise = Promise.resolve(fetchImpl(url, { signal: controller.signal }));
|
||||
} catch (error) {
|
||||
finishTimeout();
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
promise.then(
|
||||
(value) => {
|
||||
finishTimeout();
|
||||
resolve(value);
|
||||
},
|
||||
(error) => {
|
||||
finishTimeout();
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-enumerable per-half evidence for the box's non-crossing halves:
|
||||
* presentBoxes lists the halves Worldview confirmed present, emptyBoxes
|
||||
* the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js.
|
||||
*/
|
||||
function withHalves(response, { presentBoxes, emptyBoxes }) {
|
||||
Object.defineProperties(response, {
|
||||
presentBoxes: { value: presentBoxes, configurable: true },
|
||||
emptyBoxes: { value: emptyBoxes, configurable: true },
|
||||
});
|
||||
return response;
|
||||
}
|
||||
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
|
||||
|
||||
/**
|
||||
* NASA-compatible imagery acquisition; transport and URL builders are replaceable.
|
||||
* Thumbnail responses must expose Data-Present: true for image admission, or
|
||||
* false for confirmed empty coverage, including injected getThumbnail sources.
|
||||
* getThumbnail also sets presentBoxes and emptyBoxes (see withHalves),
|
||||
* also on the error it throws when another half was confirmed empty.
|
||||
* Without per-half evidence the renderer drapes every side of an HLS
|
||||
* dateline box and no side of a VIIRS one.
|
||||
*/
|
||||
export function createRecentImagerySource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
@@ -109,68 +12,24 @@ export function createRecentImagerySource({
|
||||
thumbnailUrl = wvsSnapshotUrl,
|
||||
tileTemplate = gibsTemplate,
|
||||
credit = 'NASA GIBS',
|
||||
halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS,
|
||||
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
|
||||
clearTimeoutImpl = (id) => globalThis.clearTimeout(id),
|
||||
} = {}) {
|
||||
return {
|
||||
credit,
|
||||
searchHls: (query) => search({ ...query, fetchImpl }),
|
||||
async getThumbnail(candidate, box, { size = 256, signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const halves = requestBoxes(box);
|
||||
const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0;
|
||||
const results = await Promise.allSettled(
|
||||
halves.map((half) =>
|
||||
probeHalf(
|
||||
thumbnailUrl({
|
||||
product: candidate.product,
|
||||
day: candidate.day,
|
||||
box: half,
|
||||
width: size,
|
||||
height: size,
|
||||
}),
|
||||
{
|
||||
fetchImpl,
|
||||
signal,
|
||||
deadlineMs,
|
||||
setTimeoutImpl,
|
||||
clearTimeoutImpl,
|
||||
},
|
||||
),
|
||||
),
|
||||
const response = await fetchImpl(
|
||||
thumbnailUrl({
|
||||
product: candidate.product,
|
||||
day: candidate.day,
|
||||
box,
|
||||
width: size,
|
||||
height: size,
|
||||
}),
|
||||
{ signal },
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
// Per half, its Data-Present answer or null when it did not answer.
|
||||
const answers = results.map((result) =>
|
||||
result.status === 'fulfilled' ? dataPresent(result.value) : null,
|
||||
);
|
||||
const halvesWhere = (value) =>
|
||||
halves.filter((_, i) => answers[i] === value);
|
||||
// A missing answer is an error unless another half proved data. The
|
||||
// error keeps a half confirmed empty (see withHalves).
|
||||
const failure = results.find((result) => result.status === 'rejected');
|
||||
if (failure && !answers.includes('true')) {
|
||||
const emptyBoxes = halvesWhere('false');
|
||||
if (Object.isExtensible(failure.reason))
|
||||
withHalves(
|
||||
failure.reason,
|
||||
emptyBoxes.length
|
||||
? { presentBoxes: [], emptyBoxes }
|
||||
: { presentBoxes: null, emptyBoxes: null },
|
||||
);
|
||||
throw failure.reason;
|
||||
}
|
||||
// Show the first half with data (the wider wins a tie), else the first
|
||||
// not confirmed empty, so an unreadable answer is never called empty.
|
||||
// Every half answered here unless one proved data.
|
||||
let shown = answers.indexOf('true');
|
||||
if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false');
|
||||
if (shown < 0) shown = 0;
|
||||
return withHalves(results[shown].value, {
|
||||
presentBoxes: halvesWhere('true'),
|
||||
emptyBoxes: halvesWhere('false'),
|
||||
});
|
||||
return response;
|
||||
},
|
||||
getTileTemplate: (product, day) => tileTemplate(product, day),
|
||||
};
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { manualTimers } from './testDoubles.mjs';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
|
||||
test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => {
|
||||
const controller = new AbortController();
|
||||
const query = {
|
||||
box: { west: 0, east: 1, south: 0, north: 1 },
|
||||
signal: controller.signal,
|
||||
};
|
||||
const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal };
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
const calls = [];
|
||||
const fetchImpl = async (...args) => {
|
||||
calls.push(args);
|
||||
return new Response('image');
|
||||
};
|
||||
const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); };
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl,
|
||||
search: async (request) => {
|
||||
@@ -23,263 +16,27 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt
|
||||
assert.equal(request.box, query.box);
|
||||
return [candidate];
|
||||
},
|
||||
thumbnailUrl: ({ product, day, width }) =>
|
||||
`https://imagery.example/${product}/${day}/${width}`,
|
||||
tileTemplate: (product, day) =>
|
||||
`https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
|
||||
thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`,
|
||||
tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
|
||||
credit: 'Example imagery',
|
||||
});
|
||||
assert.deepEqual(await source.searchHls(query), [candidate]);
|
||||
assert.equal(
|
||||
await (
|
||||
await source.getThumbnail(candidate, query.box, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
).text(),
|
||||
'image',
|
||||
);
|
||||
assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image');
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256');
|
||||
// The fetch gets a private signal chained to the caller's.
|
||||
const halfSignal = calls[0][1].signal;
|
||||
assert.notEqual(halfSignal, controller.signal);
|
||||
assert.equal(halfSignal.aborted, false);
|
||||
controller.abort();
|
||||
assert.equal(halfSignal.aborted, true);
|
||||
assert.equal(
|
||||
source.getTileTemplate(candidate.product, candidate.day),
|
||||
'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}',
|
||||
);
|
||||
assert.equal(calls[0][1].signal, controller.signal);
|
||||
assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}');
|
||||
assert.equal(source.credit, 'Example imagery');
|
||||
});
|
||||
|
||||
test('cancelled thumbnail acquisition does not return stale responses or retry', async () => {
|
||||
const controller = new AbortController();
|
||||
const box = { west: 0, south: 0, east: 1, north: 1 };
|
||||
let calls = 0;
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: () => 'https://imagery.example/thumbnail',
|
||||
fetchImpl: async () => {
|
||||
calls++;
|
||||
controller.abort();
|
||||
return new Response('image');
|
||||
},
|
||||
fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); },
|
||||
});
|
||||
await assert.rejects(
|
||||
source.getThumbnail({}, box, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
await assert.rejects(
|
||||
source.getThumbnail({}, box, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
|
||||
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => {
|
||||
const requested = [];
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: ({ box }) => {
|
||||
requested.push(box);
|
||||
return 'https://imagery.example/thumbnail';
|
||||
},
|
||||
fetchImpl: async () => new Response('image'),
|
||||
});
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
await source.getThumbnail(candidate, {
|
||||
west: 179.9,
|
||||
south: 0,
|
||||
east: -179,
|
||||
north: 1,
|
||||
});
|
||||
assert.deepEqual(requested, [
|
||||
{ west: -180, south: 0, east: -179, north: 1 },
|
||||
{ west: 179.9, south: 0, east: 180, north: 1 },
|
||||
]);
|
||||
requested.length = 0;
|
||||
await source.getThumbnail(candidate, {
|
||||
west: 179,
|
||||
south: 0,
|
||||
east: -179.9,
|
||||
north: 1,
|
||||
});
|
||||
assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 });
|
||||
assert.equal(requested.length, 2);
|
||||
assert.ok(requested.every((box) => box.west <= box.east));
|
||||
});
|
||||
|
||||
const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 };
|
||||
// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG.
|
||||
const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' };
|
||||
const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 };
|
||||
const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 };
|
||||
|
||||
const dated = (present, body = 'image') =>
|
||||
new Response(body, { headers: { 'Data-Present': present } });
|
||||
function halvesSource(answers, options = {}) {
|
||||
const requested = [];
|
||||
const source = createRecentImagerySource({
|
||||
...options,
|
||||
thumbnailUrl: ({ box }) =>
|
||||
`https://imagery.example/${box.west}/${box.east}`,
|
||||
fetchImpl: async (url) => {
|
||||
requested.push(url);
|
||||
const answer = answers[url.split('imagery.example/')[1]];
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer.clone ? answer : answer();
|
||||
},
|
||||
});
|
||||
return { source, requested };
|
||||
}
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
|
||||
test('a crossing box probes both halves and is present when only the narrow half has data', async () => {
|
||||
const { source, requested } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(requested.length, 2);
|
||||
assert.equal(response.headers.get('Data-Present'), 'true');
|
||||
assert.equal(await response.text(), 'narrow');
|
||||
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
|
||||
assert.deepEqual(response.emptyBoxes, [WIDE_BOX]);
|
||||
});
|
||||
|
||||
test('a crossing box with data only on the wider half is present and shows the wider side', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('true', 'wide'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'wide');
|
||||
});
|
||||
|
||||
test('a crossing box is empty only when both halves are confirmed empty', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(response.headers.get('Data-Present'), 'false');
|
||||
assert.deepEqual(response.presentBoxes, []);
|
||||
assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]);
|
||||
});
|
||||
|
||||
test('a crossing box is not called empty when the other half failed', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': () => new Response('x', { status: 503 }),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(response.ok, false);
|
||||
});
|
||||
|
||||
test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('true', 'wide'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'wide');
|
||||
assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]);
|
||||
});
|
||||
|
||||
test('a rejected half does not hide data on the other half, and never reads as empty', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': new Error('network'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'narrow');
|
||||
const failing = halvesSource({
|
||||
'-180/-179': new Error('network'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
await assert.rejects(
|
||||
failing.source.getThumbnail(candidate, NARROW_WEST),
|
||||
/network/,
|
||||
);
|
||||
});
|
||||
|
||||
for (const [label, answer] of [
|
||||
['rejected', new Error('network')],
|
||||
['hung', () => new Promise(() => {})],
|
||||
['answered without a presence', () => dated('unknown', 'maybe')],
|
||||
]) {
|
||||
for (const product of [JPEG_CANDIDATE, candidate]) {
|
||||
test(`a ${product.product} half that ${label} is neither present nor empty`, async () => {
|
||||
const { source } = halvesSource(
|
||||
{ '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') },
|
||||
{ halfDeadlineMs: 20 },
|
||||
);
|
||||
const response = await source.getThumbnail(product, NARROW_WEST);
|
||||
assert.equal(response.headers.get('Data-Present'), 'true');
|
||||
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
|
||||
assert.deepEqual(response.emptyBoxes, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => {
|
||||
const controller = new AbortController();
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: () => 'https://example.invalid/',
|
||||
halfDeadlineMs: 10000,
|
||||
fetchImpl: () => {
|
||||
controller.abort();
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
const outcome = await Promise.race([
|
||||
source
|
||||
.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal })
|
||||
.then(
|
||||
() => 'resolved',
|
||||
(error) => error.name,
|
||||
),
|
||||
new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)),
|
||||
]);
|
||||
assert.equal(outcome, 'AbortError');
|
||||
});
|
||||
|
||||
test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => {
|
||||
const hang = () => new Promise(() => {});
|
||||
const { source, requested } = halvesSource(
|
||||
{ '-180/-179': hang, '179.9/180': hang },
|
||||
{ halfDeadlineMs: 10 },
|
||||
);
|
||||
await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), {
|
||||
name: 'TimeoutError',
|
||||
});
|
||||
assert.equal(requested.length, 2);
|
||||
});
|
||||
|
||||
test("the caller's cancellation rejects at once and stops every half", async () => {
|
||||
const aborted = [];
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: ({ box }) => String(box.west),
|
||||
fetchImpl: (url, { signal }) => {
|
||||
signal.addEventListener('abort', () => aborted.push(url), { once: true });
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
await assert.rejects(result, { name: 'AbortError' });
|
||||
assert.deepEqual(aborted, ['-180', '179.9']);
|
||||
});
|
||||
|
||||
test('a successful probe leaves no deadline timer behind', async () => {
|
||||
const timers = manualTimers();
|
||||
const { source } = halvesSource(
|
||||
{ '-180/-179': dated('true'), '179.9/180': dated('false') },
|
||||
timers,
|
||||
);
|
||||
await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
|
||||
assert.equal(timers.armed(), 0);
|
||||
assert.equal(timers.cleared.length, 2);
|
||||
});
|
||||
@@ -16,13 +16,6 @@ export const BOX = Object.freeze({
|
||||
north: 30.3,
|
||||
});
|
||||
|
||||
export const FIJI_BOX = Object.freeze({
|
||||
west: 179,
|
||||
south: -18,
|
||||
east: -177,
|
||||
north: -17,
|
||||
});
|
||||
|
||||
export const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
/** Timers that fire only when the test says so. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per
|
||||
* candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that
|
||||
* candidate day. The response's `Data-Present` header is the only proof that
|
||||
* a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and
|
||||
* `Acquisition-Time` carries the sensing time. Fetches are bounded, and so
|
||||
* are decoded images: residency is least-recently-USED, where a request or a
|
||||
@@ -8,28 +8,16 @@
|
||||
* card on every render, so a read that counted would evict the visible cards
|
||||
* first). Eviction revokes the image only; what the probe proved is kept.
|
||||
*/
|
||||
import { boxKey, thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource, dataPresent } from './source.js';
|
||||
import { thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
|
||||
const EMPTY = Object.freeze({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */
|
||||
function keepProvenHalves(previous, next, opposite) {
|
||||
if (!Array.isArray(next) || !Array.isArray(opposite)) return previous;
|
||||
const drop = new Set([...next, ...opposite].map(boxKey));
|
||||
return [
|
||||
...next,
|
||||
...(previous ?? []).filter((half) => !drop.has(boxKey(half))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options]
|
||||
*/
|
||||
@@ -102,22 +90,18 @@ export function createThumbnailLoader({
|
||||
let status = 'error';
|
||||
let objectUrl = null;
|
||||
let acquisitionTime = null;
|
||||
// Per-half evidence (see withHalves in source.js), or null without it.
|
||||
let availableBoxes = null;
|
||||
let emptyBoxes = null;
|
||||
let cancelled = false;
|
||||
try {
|
||||
const response = await requestThumbnail(entry.candidate, entry.box, {
|
||||
size,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Each half's explicit answer counts even when the shown response fails.
|
||||
availableBoxes = response?.presentBoxes ?? null;
|
||||
emptyBoxes = response?.emptyBoxes ?? null;
|
||||
if (controller.signal.aborted) {
|
||||
cancelled = true;
|
||||
} else if (response?.ok) {
|
||||
const present = dataPresent(response);
|
||||
const present = String(
|
||||
response.headers?.get?.('Data-Present') ?? '',
|
||||
).toLowerCase();
|
||||
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
|
||||
if (present === 'false') {
|
||||
status = 'empty';
|
||||
@@ -133,11 +117,7 @@ export function createThumbnailLoader({
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || error?.name === 'AbortError')
|
||||
cancelled = true;
|
||||
else {
|
||||
status = 'error';
|
||||
availableBoxes = error?.presentBoxes ?? availableBoxes;
|
||||
emptyBoxes = error?.emptyBoxes ?? emptyBoxes;
|
||||
}
|
||||
else status = 'error';
|
||||
} finally {
|
||||
inFlight -= 1;
|
||||
entry.loading = false;
|
||||
@@ -149,17 +129,6 @@ export function createThumbnailLoader({
|
||||
pump();
|
||||
return;
|
||||
}
|
||||
// Each half keeps its latest explicit answer.
|
||||
entry.availableBoxes = keepProvenHalves(
|
||||
entry.availableBoxes,
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
);
|
||||
entry.emptyBoxes = keepProvenHalves(
|
||||
entry.emptyBoxes,
|
||||
emptyBoxes,
|
||||
availableBoxes,
|
||||
);
|
||||
// A failed re-fetch of an evicted image keeps what the day proved.
|
||||
if (status !== 'error' || entry.status !== 'present') {
|
||||
entry.status = status;
|
||||
@@ -227,8 +196,6 @@ export function createThumbnailLoader({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
controller: null,
|
||||
touched: 0,
|
||||
@@ -305,7 +272,7 @@ export function createThumbnailLoader({
|
||||
/**
|
||||
* Read a day's state. A read is not a use: it never changes residency.
|
||||
* @param {string} key Candidate key.
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array<object> | null, emptyBoxes: Array<object> | null, loading: boolean }}
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}
|
||||
*/
|
||||
get(key) {
|
||||
const entry = entries.get(key);
|
||||
@@ -314,8 +281,6 @@ export function createThumbnailLoader({
|
||||
status: entry.status,
|
||||
objectUrl: entry.objectUrl,
|
||||
acquisitionTime: entry.acquisitionTime,
|
||||
availableBoxes: entry.availableBoxes,
|
||||
emptyBoxes: entry.emptyBoxes,
|
||||
loading: entry.loading,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs';
|
||||
import { BOX, response, settle } from './testDoubles.mjs';
|
||||
|
||||
const candidate = (product, day) => ({
|
||||
key: `${product}:${day}`,
|
||||
product,
|
||||
day,
|
||||
});
|
||||
|
||||
/** A fetch whose responses the test releases, in any order. */
|
||||
function fakeFetch() {
|
||||
@@ -64,8 +68,6 @@ test('Data-Present decides the day: present with an object URL and sensing time,
|
||||
status: 'present',
|
||||
objectUrl: 'blob:1',
|
||||
acquisitionTime: '2026-09-18T17:12:00Z',
|
||||
availableBoxes: [BOX],
|
||||
emptyBoxes: [],
|
||||
loading: false,
|
||||
});
|
||||
assert.equal(loader.get('L30:2026-09-16').status, 'empty');
|
||||
@@ -335,75 +337,6 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
|
||||
assert.deepEqual(revoked, ['blob:1']);
|
||||
});
|
||||
|
||||
test('the loader proves a dateline day present from one half and hands that half on', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const time = day.day + 'T22:10:00Z';
|
||||
const { loader } = fixture({
|
||||
fetchImpl: async (url) => {
|
||||
const east =
|
||||
new URL(url).searchParams.get('BBOX').split(',')[1] === '-180';
|
||||
return response({
|
||||
headers: east
|
||||
? { 'Data-Present': 'true', 'Acquisition-Time': time }
|
||||
: { 'Data-Present': 'false' },
|
||||
});
|
||||
},
|
||||
});
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settle();
|
||||
const entry = loader.get(day.key);
|
||||
assert.equal(entry.status, 'present');
|
||||
assert.equal(entry.acquisitionTime, time);
|
||||
assert.ok(entry.objectUrl);
|
||||
assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a dateline day whose halves both hang is an error, not "checking" forever', async () => {
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl: () => new Promise(() => {}),
|
||||
halfDeadlineMs: 20,
|
||||
});
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
});
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const settled = new Promise((resolve) => loader.subscribe(resolve));
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settled;
|
||||
assert.equal(loader.get(day.key).status, 'error');
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present day drops a half only when it is confirmed empty', async () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
const answers = [
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west], emptyBoxes: [east] },
|
||||
];
|
||||
const { loader } = fixture({
|
||||
maxDecoded: 1,
|
||||
requestThumbnail: async () =>
|
||||
Object.assign(
|
||||
response({ headers: { 'Data-Present': 'true' } }),
|
||||
answers.shift(),
|
||||
),
|
||||
});
|
||||
const day1 = candidate('VIIRS', '2026-11-04');
|
||||
const day2 = candidate('VIIRS', '2026-11-05');
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
loader.request(day2, box);
|
||||
await settle();
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
|
||||
const { loader, fetch } = fixture({ maxInFlight: 1 });
|
||||
const stale = candidate('S30', '2026-09-10');
|
||||
|
||||
@@ -292,8 +292,6 @@ function recordingRendering(state) {
|
||||
if (point) point.show = show;
|
||||
},
|
||||
_setPointsShown() {},
|
||||
_startPace() {},
|
||||
_stopPace() {},
|
||||
_setOrbitPathShown(noradId, show) {
|
||||
if (state._orbitPaths.has(noradId)) rings.set(noradId, show);
|
||||
},
|
||||
|
||||
@@ -30,6 +30,7 @@ export function createLifecycle({
|
||||
// Unregistered on destroy, so a page that builds the app again holds no old layer; init
|
||||
// registers it again.
|
||||
let uncover = worldClock.register(clockSource);
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
/** Run the shared per-frame tick before each frame draws. */
|
||||
@@ -97,8 +98,7 @@ export function createLifecycle({
|
||||
|
||||
enable(viewer) {
|
||||
layerState._enabled = true;
|
||||
// Drawn as often as the dots move on screen (rendering.js, the pace).
|
||||
parts.rendering._startPace();
|
||||
holdContinuousRender('satellites'); // per-frame animator (perf wave 2)
|
||||
parts.rendering._setPointsShown(
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
@@ -137,7 +137,7 @@ export function createLifecycle({
|
||||
parts.catalog._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
layerState._enabled = false;
|
||||
parts.rendering._stopPace();
|
||||
releaseContinuousRender('satellites');
|
||||
parts.rendering._setPointsShown(false);
|
||||
parts.rendering._setOrbitPathsShown(false);
|
||||
for (const model of parts.stationModels ?? [])
|
||||
@@ -165,7 +165,7 @@ export function createLifecycle({
|
||||
parts.catalog._abortActiveUpdates();
|
||||
uncover?.();
|
||||
uncover = null;
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
releaseContinuousRender('satellites'); // direct-destroy path (perf wave 2 fix)
|
||||
layerState._enabled = false;
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -2,11 +2,6 @@ import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { gstime } from 'satellite.js';
|
||||
import { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
import {
|
||||
createRenderPace,
|
||||
createScreenSpeed,
|
||||
paceHzForSpeed,
|
||||
} from '../../renderPace.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ORBIT_REBAKE_MS,
|
||||
@@ -109,49 +104,6 @@ export function createRendering({
|
||||
/** The frame the tick last ran in: the tracked sample's cache key. */
|
||||
let renderedFrame = -1;
|
||||
|
||||
// The pace: how often the dots are drawn while nothing else draws. A dot
|
||||
// in low orbit crosses under half a pixel a second on the whole globe and
|
||||
// hundreds of pixels a second from close by, so the rate follows the
|
||||
// fastest dot in view (renderPace.js) instead of holding the loop at the
|
||||
// display's rate.
|
||||
const pace = createRenderPace({
|
||||
owner: 'satellites',
|
||||
render: services.render,
|
||||
});
|
||||
const screenSpeed = createScreenSpeed();
|
||||
/** While dots fade for a focus change, they are drawn this often. */
|
||||
const PACE_FADE_HZ = 20;
|
||||
/** The least time a reading spans: shorter, and the clock's jitter shows. */
|
||||
const PACE_READ_MS = 100;
|
||||
/** Wall time of the last reading of the dots' speed, and its result. */
|
||||
let paceWallMs = 0;
|
||||
let pacePxPerSec = 0;
|
||||
/** Where the eye was at the last reading: a dot's move is taken from it. */
|
||||
const paceEye = { x: 0, y: 0, z: 0 };
|
||||
const paceEyeMove = { x: 0, y: 0, z: 0 };
|
||||
let paceFading = false;
|
||||
/** Whether the layer is on and paced: its dots' speed is read. */
|
||||
let pacing = false;
|
||||
|
||||
/** Set the rate from the fastest dot seen; called once a drawn frame. */
|
||||
function _applyPace() {
|
||||
let hz = paceHzForSpeed(pacePxPerSec);
|
||||
if (paceFading && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
|
||||
pace.set(hz);
|
||||
}
|
||||
|
||||
function _startPace() {
|
||||
pacing = true;
|
||||
paceWallMs = 0;
|
||||
pacePxPerSec = 0;
|
||||
pace.start();
|
||||
}
|
||||
|
||||
function _stopPace() {
|
||||
pacing = false;
|
||||
pace.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
|
||||
* aligned with live SGP4 positions propagated at another epoch: a column-
|
||||
@@ -702,26 +654,6 @@ export function createRendering({
|
||||
|
||||
function _reckonPoints(nowMs) {
|
||||
const gmst = gstime(new Date(nowMs));
|
||||
// The pace's reading, at most every PACE_READ_MS: how far the fastest
|
||||
// dot in view moved on screen since the last one.
|
||||
const wallMs = performance.now();
|
||||
const sinceS = (wallMs - paceWallMs) / 1000;
|
||||
const reading = pacing && wallMs - paceWallMs >= PACE_READ_MS;
|
||||
const camera = reading ? findCamera(layerState._viewer) : null;
|
||||
const view = camera?.pose?.() ?? null;
|
||||
const eye = view?.position;
|
||||
// The eye's own move since the last reading: a camera riding one
|
||||
// satellite sees its neighbours nearly still.
|
||||
if (eye) {
|
||||
paceEyeMove.x = eye.x - paceEye.x;
|
||||
paceEyeMove.y = eye.y - paceEye.y;
|
||||
paceEyeMove.z = eye.z - paceEye.z;
|
||||
}
|
||||
const measure =
|
||||
reading &&
|
||||
sinceS < 5 &&
|
||||
screenSpeed.begin(view, camera?.viewport?.().height, paceEyeMove);
|
||||
const lastWallMs = paceWallMs;
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
if (!point.show || noradId === layerState._trackedNorad) continue;
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
@@ -737,24 +669,7 @@ export function createRendering({
|
||||
reckonEarthFixed(sample, nowMs, gmst, point.pos);
|
||||
_markDirty(noradId);
|
||||
sat.reckonedAtMs = nowMs;
|
||||
if (!reading) continue;
|
||||
// Where the dot was at the last reading, kept on its satellite. One
|
||||
// not read then (hidden, or just loaded) is not measured: it jumps.
|
||||
const from = (sat.paceFrom ??= { x: 0, y: 0, z: 0, atMs: -1 });
|
||||
if (measure && from.atMs === lastWallMs) screenSpeed.add(from, point.pos);
|
||||
from.x = point.pos.x;
|
||||
from.y = point.pos.y;
|
||||
from.z = point.pos.z;
|
||||
from.atMs = wallMs;
|
||||
}
|
||||
if (!reading) return;
|
||||
if (eye) {
|
||||
paceEye.x = eye.x;
|
||||
paceEye.y = eye.y;
|
||||
paceEye.z = eye.z;
|
||||
}
|
||||
if (measure) pacePxPerSec = screenSpeed.pxPerSec(sinceS);
|
||||
paceWallMs = wallMs;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -776,7 +691,6 @@ export function createRendering({
|
||||
renderedFrame = Number.isFinite(t?.frame) ? t.frame : renderedFrame + 1;
|
||||
if (layerState._enabled) _tickAfterFrame();
|
||||
_flushPoints();
|
||||
_applyPace();
|
||||
}
|
||||
|
||||
/** The tick's part read before the frame's own sample is taken. */
|
||||
@@ -819,17 +733,9 @@ export function createRendering({
|
||||
|
||||
if (layerState._params.showPoints) {
|
||||
const worldMs = layerState.now();
|
||||
// The dots move at the pace, not on every drawn frame: moving them
|
||||
// asks for the next frame, so a frame drawn for any reason would keep
|
||||
// the loop drawing; and a drag over the whole globe need not send
|
||||
// every dot to the GPU sixty times a second to move it a hair.
|
||||
if (pace.take()) {
|
||||
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
|
||||
layerState._lastReckonMs = worldMs;
|
||||
_reckonPoints(worldMs);
|
||||
}
|
||||
} else {
|
||||
pacePxPerSec = 0;
|
||||
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
|
||||
layerState._lastReckonMs = worldMs;
|
||||
_reckonPoints(worldMs);
|
||||
}
|
||||
|
||||
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
|
||||
@@ -875,10 +781,8 @@ export function createRendering({
|
||||
if (
|
||||
!layerState._params.showPoints ||
|
||||
!focusPassIsNeeded(target, layerState._activeFocusCount)
|
||||
) {
|
||||
paceFading = false;
|
||||
)
|
||||
return;
|
||||
}
|
||||
if (nowMs - layerState._lastFocusUpdate < 80) return;
|
||||
layerState._lastFocusUpdate = nowMs;
|
||||
const query = findQuery(layerState._viewer);
|
||||
@@ -933,7 +837,6 @@ export function createRendering({
|
||||
).color,
|
||||
});
|
||||
layerState._activeFocusCount = result.activeCount;
|
||||
paceFading = Boolean(result.transitioning);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1036,9 +939,6 @@ export function createRendering({
|
||||
_propagateAll,
|
||||
_reckonPoints,
|
||||
_preRenderTick,
|
||||
_startPace,
|
||||
_stopPace,
|
||||
_paceForTest: () => ({ ...pace.state(), pxPerSec: pacePxPerSec }),
|
||||
_updatePointFocus,
|
||||
applySatellitePointFocusDeemphasis,
|
||||
_flushPoints,
|
||||
|
||||
@@ -5,8 +5,6 @@ import { VISIBILITY_UPDATE_MS } from './policy.js';
|
||||
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { PACE_MAX_HZ, PACE_MIN_HZ } from '../../renderPace.js';
|
||||
import { createVesselIconBook } from './iconBook.js';
|
||||
|
||||
// The layer must let the scene idle: it asks for frames for forced passes,
|
||||
// for vessels that move, and one trailing frame after the camera stops, and
|
||||
@@ -272,7 +270,7 @@ test('a placement that places nothing asks for no frames; one that places a draw
|
||||
assert.deepEqual(requests, ['ais-vessels-placement']);
|
||||
});
|
||||
|
||||
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel, at most 30 a second; a slow one three times a second', (t) => {
|
||||
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel; a slow one once a second', (t) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
@@ -297,24 +295,23 @@ test('a vessel moving visibly asks for its next frame as soon as it moves half a
|
||||
};
|
||||
drawnVisual({ camera, scene: {}, canvas: { clientHeight: 1000 } });
|
||||
// How long after a pass the next frame is asked for, once the vessel moved
|
||||
// `dLat` in the 40 ms since the pass before (passes come at most 30 a
|
||||
// second, so a frame 16 ms on would not move it).
|
||||
// `dLat` in the 16 ms since the pass before.
|
||||
const waitAfterStep = (dLat) => {
|
||||
layer.testing._runPlacementPassForTest();
|
||||
advance(1_000); // whatever frame that asked for comes and goes
|
||||
assert.equal(timers.size, 0);
|
||||
mono += 40;
|
||||
mono += 16;
|
||||
spot = { lat: spot.lat + dLat, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.equal(timers.size, 1);
|
||||
const [timer] = [...timers.values()];
|
||||
return timer.at - now();
|
||||
};
|
||||
// About 11 m in a pass, 20 km away: over half a pixel, so the next frame
|
||||
// is asked for within the pass's own span.
|
||||
assert.ok(waitAfterStep(0.0001) <= 40);
|
||||
// About 1 cm in a frame: half a pixel takes seconds, so at the floor.
|
||||
assert.ok(Math.abs(waitAfterStep(0.0000001) - 1000 / PACE_MIN_HZ) < 1e-6);
|
||||
// About 11 m in a frame, 20 km away: over half a pixel, so the next frame
|
||||
// is asked for within the frame.
|
||||
assert.ok(waitAfterStep(0.0001) <= 16);
|
||||
// About 1 cm in a frame: half a pixel takes seconds, so once a second.
|
||||
assert.equal(waitAfterStep(0.0000001), 1000);
|
||||
// A 2D view 40 km across in 1,000 px: 11 m is over a quarter pixel, so the
|
||||
// next frame comes within two frames.
|
||||
camera.frustum = new Cesium.OrthographicOffCenterFrustum({
|
||||
@@ -327,20 +324,7 @@ test('a vessel moving visibly asks for its next frame as soon as it moves half a
|
||||
});
|
||||
camera.viewMatrix = Cesium.Matrix4.IDENTITY;
|
||||
drawnVisual({ camera, scene: {}, canvas: { clientWidth: 1000 } });
|
||||
assert.ok(waitAfterStep(0.0001) <= 80);
|
||||
// A frame sooner than a thirtieth of a second after a pass moves nothing:
|
||||
// the next pass is asked for when one may come.
|
||||
mono += 100;
|
||||
spot = { lat: spot.lat + 0.001, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
advance(1_000);
|
||||
const drawn = layer.testing._vesselVisualForTest(record).drawnLat;
|
||||
mono += 16;
|
||||
spot = { lat: spot.lat + 0.001, lon: spot.lon };
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.equal(layer.testing._vesselVisualForTest(record).drawnLat, drawn);
|
||||
const [held] = [...timers.values()];
|
||||
assert.ok(Math.abs(held.at - now() - (1000 / PACE_MAX_HZ - 16)) < 1e-6);
|
||||
assert.ok(waitAfterStep(0.0001) <= 32);
|
||||
});
|
||||
|
||||
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (t) => {
|
||||
@@ -738,49 +722,3 @@ test('following the clock, a vessel the visibility pass shows before the clock p
|
||||
);
|
||||
assert.ok(Math.abs(Cesium.Math.toDegrees(latitude) - 52.43) < 1e-6);
|
||||
});
|
||||
|
||||
test('a placement pass writes the vessels it moved to the set at once, not one a vessel', (t) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
globalThis.document = { getElementById: () => null };
|
||||
t.after(() => {
|
||||
if (originalDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = originalDocument;
|
||||
});
|
||||
const spots = new Map([
|
||||
['111', { lat: 51.93, lon: 4.05 }],
|
||||
['222', { lat: 51.94, lon: 4.06 }],
|
||||
]);
|
||||
const { layer, camera } = setup({
|
||||
placement: { layer: () => ({ place: (id) => spots.get(id) }) },
|
||||
});
|
||||
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
|
||||
camera.frustum = { fovy: 1 };
|
||||
const writes = [];
|
||||
const icons = createVesselIconBook({
|
||||
id: 'vessels',
|
||||
upsert: (list) => writes.push(list.map((item) => item.id)),
|
||||
remove: noop,
|
||||
});
|
||||
const records = [
|
||||
{ mmsi: '111', lat: 51.93, lon: 4.05 },
|
||||
{ mmsi: '222', lat: 51.94, lon: 4.06 },
|
||||
];
|
||||
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
|
||||
bindFakeCesiumScene(viewer);
|
||||
layer.testing._setVesselStateForTest({ viewer, records, icons });
|
||||
for (const record of records) {
|
||||
const visual = layer.testing._prepareVesselVisualForTest(record);
|
||||
visual.visible = true;
|
||||
// Drawn already, as the layer draws a vessel it was sent.
|
||||
icons.put({ id: visual.iconId }, { expiresAt: null });
|
||||
}
|
||||
layer.testing._runPlacementPassForTest();
|
||||
mono += 100;
|
||||
for (const [id, spot] of spots)
|
||||
spots.set(id, { lat: spot.lat + 0.001, lon: spot.lon });
|
||||
writes.length = 0;
|
||||
layer.testing._runPlacementPassForTest();
|
||||
assert.deepEqual(writes, [['111', '222']]);
|
||||
});
|
||||
+19
-108
@@ -48,19 +48,13 @@ import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
import { PACE_MAX_HZ, PACE_MIN_HZ, PACE_STEP_PX } from '../../renderPace.js';
|
||||
|
||||
/** A moving vessel's next frame is asked for once it would move this far on
|
||||
* screen (pixels), so it glides when it moves visibly and the scene idles
|
||||
* when it does not. */
|
||||
const VESSEL_STEP_PX = PACE_STEP_PX;
|
||||
/** A frame is asked for at least this often while any drawn vessel moves:
|
||||
* the floor every moving layer keeps (renderPace.js). */
|
||||
const PLACEMENT_FRAME_MS = 1000 / PACE_MIN_HZ;
|
||||
/** And at most this often: the most a moving layer draws (renderPace.js). */
|
||||
const PLACEMENT_MIN_WAIT_MS = 1000 / PACE_MAX_HZ;
|
||||
/** While vessels' emphasis changes for a focus, they are drawn this often. */
|
||||
const VESSEL_FOCUS_FPS = 20;
|
||||
const VESSEL_STEP_PX = 0.5;
|
||||
/** A frame is asked for at least this often while any drawn vessel moves. */
|
||||
const PLACEMENT_FRAME_MS = 1000;
|
||||
/** How often each vessel not drawn moves on as the world clock plays (wall
|
||||
* ms), so one that comes into view is judged where it is. */
|
||||
const HIDDEN_FOLLOW_MS = 250;
|
||||
@@ -488,12 +482,6 @@ export function createRendering({
|
||||
function putIcon(visual, item) {
|
||||
if (!segmentsOn()) {
|
||||
planFrom.delete(item.id);
|
||||
// In a placement pass, written with the pass's others at its end:
|
||||
// one write to the set, not one a vessel.
|
||||
if (placedIcons && state.icons.expiresAt(item.id) === undefined) {
|
||||
placedIcons.push(item);
|
||||
return;
|
||||
}
|
||||
state.icons.put(item, { expiresAt: null });
|
||||
return;
|
||||
}
|
||||
@@ -1001,88 +989,26 @@ export function createRendering({
|
||||
return Math.abs(atMs - clockStep.atMs) * clockStep.pxPerMs < VESSEL_STEP_PX;
|
||||
}
|
||||
|
||||
// Live with a host-supplied placement, vessels move on between refreshes.
|
||||
// Drawn ones move once the fastest would have moved VESSEL_STEP_PX on
|
||||
// screen since the pass that last moved them, at least three times a second
|
||||
// and at most thirty (renderPace.js), and
|
||||
// at once when the camera moves or zooms, new rows come or a vessel comes
|
||||
// into view (underClockStep, on wall time). Moving an icon asks for a
|
||||
// frame, so moving them on every frame would draw every frame: the frames
|
||||
// between are left alone, and the next one is asked for when it is due.
|
||||
let placementDue = true;
|
||||
/** The icons a placement pass moved, while it runs (`putIcon`). */
|
||||
let placedIcons = null;
|
||||
/** Wall ms of the last pass that moved live-placed vessels. */
|
||||
let placedWallMs = -Infinity;
|
||||
// Live with a host-supplied placement, vessels move on between refreshes:
|
||||
// drawn where it places them every frame, with the next frame asked for
|
||||
// as soon as a drawn vessel would move visibly, so they move while the
|
||||
// scene idles.
|
||||
function followPlacements() {
|
||||
const nowMs = vesselState._aisRuntime.now();
|
||||
const wallMs = performance.now();
|
||||
// Never more often than a moving layer draws: a pass moving icons asks
|
||||
// for a frame of its own, so without this a vessel close by moving
|
||||
// over half a pixel a frame would draw every frame.
|
||||
const sinceMs = wallMs - placedWallMs;
|
||||
if (!placementDue && sinceMs < PLACEMENT_MIN_WAIT_MS) {
|
||||
askFrameIn(PLACEMENT_MIN_WAIT_MS - sinceMs);
|
||||
return;
|
||||
}
|
||||
if (!placementDue && underClockStep(nowMs, wallMs)) {
|
||||
askFrameIn(
|
||||
Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
PLACEMENT_FRAME_MS - (wallMs - clockStep.wallMs),
|
||||
VESSEL_STEP_PX / clockStep.pxPerMs - (nowMs - clockStep.atMs),
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
placementDue = false;
|
||||
placedWallMs = wallMs;
|
||||
const motion = startMotionPass();
|
||||
placedIcons = [];
|
||||
try {
|
||||
// Drawn vessels only, as a sprite or a model: a hidden one is placed
|
||||
// again when it is drawn.
|
||||
for (const record of state.records.all) {
|
||||
const visual = visualRecords.get(record);
|
||||
if (!visual?.position) continue;
|
||||
if (!drawnNow(record, visual)) continue;
|
||||
const placed = services.placement.place(record.id, nowMs);
|
||||
if (placed) motion.moving = true;
|
||||
const { lat, lon } = placed ?? record;
|
||||
// How fast it moves is measured over the time since it was last
|
||||
// placed.
|
||||
const elapsedMs =
|
||||
placed && visual.placedAtMs > 0
|
||||
? nowMs - visual.placedAtMs
|
||||
: undefined;
|
||||
visual.placedAtMs = placed ? nowMs : undefined;
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveDrawnVisual(
|
||||
record,
|
||||
visual,
|
||||
lat,
|
||||
lon,
|
||||
motion,
|
||||
elapsedMs > 0 ? elapsedMs : undefined,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
const moved = placedIcons;
|
||||
placedIcons = null;
|
||||
state.icons?.putMany(moved);
|
||||
// Drawn vessels only, as a sprite or a model: a hidden one is placed
|
||||
// again when it is drawn.
|
||||
for (const record of state.records.all) {
|
||||
const visual = visualRecords.get(record);
|
||||
if (!visual?.position) continue;
|
||||
if (!drawnNow(record, visual)) continue;
|
||||
const placed = services.placement.place(record.id, nowMs);
|
||||
if (placed) motion.moving = true;
|
||||
const { lat, lon } = placed ?? record;
|
||||
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
|
||||
moveDrawnVisual(record, visual, lat, lon, motion);
|
||||
}
|
||||
askMotionFrame(motion);
|
||||
noteClockStep(nowMs, motion);
|
||||
}
|
||||
|
||||
/** Move live-placed vessels on the next frame however little they moved,
|
||||
* and ask for that frame: new rows came, or a vessel came into view. */
|
||||
function placeNow() {
|
||||
if (!services.placement || followsClock(vesselState)) return;
|
||||
placementDue = true;
|
||||
if (state.feed.enabled) governorRequestRender('ais-vessels-placement');
|
||||
}
|
||||
|
||||
// One pass of moving vessels: whether any drawn vessel is moving, how far
|
||||
@@ -1200,12 +1126,6 @@ export function createRendering({
|
||||
/** Ask for a vessel frame `waitMs` from now; one already asked for no
|
||||
* later stands. */
|
||||
function askFrameIn(waitMs) {
|
||||
// A frame sooner than the next pass may come would move nothing, then
|
||||
// ask again: two frames a move.
|
||||
waitMs = Math.max(
|
||||
waitMs,
|
||||
PLACEMENT_MIN_WAIT_MS - (performance.now() - placedWallMs),
|
||||
);
|
||||
const runtime = vesselState._aisRuntime;
|
||||
const dueMs = runtime.now() + waitMs;
|
||||
if (placementFrameTimer !== null) {
|
||||
@@ -1223,7 +1143,6 @@ export function createRendering({
|
||||
function cancelPlacementFrame() {
|
||||
motionPassWallMs = null;
|
||||
forgetClockStep();
|
||||
placementDue = true;
|
||||
drawnBehind = false;
|
||||
hiddenFollowedAtWallMs = null;
|
||||
if (placementFrameTimer === null) return;
|
||||
@@ -1252,8 +1171,6 @@ export function createRendering({
|
||||
function updateVisibility(force = false) {
|
||||
if (!state.feed.enabled) return;
|
||||
if (force) governorRequestRender('ais-vessels-update');
|
||||
// New rows are drawn where they were reported: placed before they show.
|
||||
if (force) placementDue = true;
|
||||
const now = focusNowMs(performance.now());
|
||||
const focusTarget = getFocusTarget();
|
||||
const regularPass =
|
||||
@@ -1313,13 +1230,9 @@ export function createRendering({
|
||||
// The time the clock pass drew (a playing clock's time moves on within
|
||||
// the frame), so only vessels it did not reach are moved.
|
||||
const catchUpAtMs = worldMs === null ? null : (clockPassAtMs ?? worldMs);
|
||||
let cameIntoView = false;
|
||||
for (const record of state.records.all) {
|
||||
const visual = getVisual(record);
|
||||
const wasVisible = visual.visible;
|
||||
visual.visible = isVisible(visual.cullPosition, occluder, record);
|
||||
// One that comes into view was not placed while hidden.
|
||||
if (visual.visible && wasVisible === false) cameIntoView = true;
|
||||
// One in view that the clock passes have not moved to the time yet
|
||||
// (a seek while paused shows it before its turn) is moved there and
|
||||
// judged again: no later pass would move it while the clock rests.
|
||||
@@ -1333,7 +1246,6 @@ export function createRendering({
|
||||
if (visual.seen !== seenYet(record)) syncRecordIcon(record);
|
||||
if (visual.visible) labelCandidates.push(record);
|
||||
}
|
||||
if (cameIntoView) placeNow();
|
||||
updateClusteredLabels(labelCandidates);
|
||||
}
|
||||
if (focusPass && query && pose) {
|
||||
@@ -1346,9 +1258,8 @@ export function createRendering({
|
||||
cameraDistanceFor: (position) => distance(pose.position, position),
|
||||
});
|
||||
state.activeFocusCount = result.activeCount;
|
||||
// Drawn while emphasis changes, at the rate fades draw elsewhere.
|
||||
if (result.activeCount > 0 || result.transitioning)
|
||||
holdContinuousRender('ais-vessels', { maxFps: VESSEL_FOCUS_FPS });
|
||||
holdContinuousRender('ais-vessels');
|
||||
else releaseContinuousRender('ais-vessels');
|
||||
}
|
||||
}
|
||||
|
||||
+43
-14
@@ -37,7 +37,8 @@ import { alongLength } from '../../geo/polyline.js';
|
||||
import { clusterScreenPoints } from '../../geo/screenCluster.js';
|
||||
import { provideUnboundDraw } from '../rendererOf.js';
|
||||
import { blobUrl, listenerList, toCartesian, uncaught } from './common.js';
|
||||
import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
|
||||
import { createGpuIcons, gpuIconCapabilities } from './gpuIcons.js';
|
||||
import { viewLayout } from '../../data/viewSheet.js';
|
||||
import { blendHost } from './setBlend.js';
|
||||
import { createModelSets } from './drawModels.js';
|
||||
import { materialTexture } from './internals.js';
|
||||
@@ -714,7 +715,7 @@ const animating = (record) => record.gpu?.animating();
|
||||
export function createCesiumDraw({
|
||||
scene,
|
||||
report,
|
||||
capabilities = new Set(GPU_ICON_CAPABILITIES),
|
||||
capabilities = new Set(gpuIconCapabilities(scene)),
|
||||
requestRender: requestFrame = null,
|
||||
date = null,
|
||||
now = () => performance.now(),
|
||||
@@ -796,20 +797,16 @@ export function createCesiumDraw({
|
||||
setsVersion += 1;
|
||||
};
|
||||
record.rebuild = rebuild;
|
||||
// A set whose owner asks for its frames is changed in place without
|
||||
// asking for one: the owner writes it as a frame begins (asking then
|
||||
// would draw that frame twice), or its next frame draws the change.
|
||||
const ownerFrames = () => spec.motionClock?.frames === 'owner';
|
||||
// Changed in place: what height queries see through may have changed.
|
||||
const patched = () => {
|
||||
setsVersion += 1;
|
||||
if (!ownerFrames()) requestRender();
|
||||
requestRender();
|
||||
};
|
||||
// Icons changed in place: height queries see through the sets' pick
|
||||
// ids, which an icon keeps, so only icons added or gone change them.
|
||||
const iconsPatched = (synced) => {
|
||||
if (synced === ICONS_CHANGED) setsVersion += 1;
|
||||
if (!ownerFrames()) requestRender();
|
||||
requestRender();
|
||||
};
|
||||
// A shape's pulse the renderer cannot run is refused before anything
|
||||
// changes.
|
||||
@@ -929,9 +926,7 @@ export function createCesiumDraw({
|
||||
spec.motionClock?.kind === 'live'
|
||||
) {
|
||||
spec.motionClock = options.motionClock;
|
||||
// A set whose owner asks for its frames reads the new delay in
|
||||
// the owner's next one: the delay alone asks for none.
|
||||
if (options.motionClock.frames !== 'owner') requestRender();
|
||||
requestRender();
|
||||
return;
|
||||
}
|
||||
// Refused, changing nothing, where icons on the GPU cannot take it
|
||||
@@ -1135,6 +1130,7 @@ export function createCesiumDraw({
|
||||
toColor,
|
||||
imageOf: (record, image) => iconImage(record, image),
|
||||
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
|
||||
viewsOf: (id) => viewSheets.get(id),
|
||||
requestRender: (reason) => {
|
||||
if (!live()) return;
|
||||
if (requestFrame) requestFrame(reason);
|
||||
@@ -1152,9 +1148,9 @@ export function createCesiumDraw({
|
||||
function onGpu(record, list, replacing = false, force = false) {
|
||||
if (record.kind !== 'icons') return false;
|
||||
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
|
||||
gpu.check(list, record.spec);
|
||||
gpu.check(list, record.spec, record);
|
||||
if (record.gpu) return true;
|
||||
if (!replacing) gpu.check(record.items.values(), record.spec);
|
||||
if (!replacing) gpu.check(record.items.values(), record.spec, record);
|
||||
record.gpu = gpu.attach(record);
|
||||
record.billboards = null;
|
||||
record.billboardHost = null;
|
||||
@@ -1676,6 +1672,9 @@ export function createCesiumDraw({
|
||||
// when its icon is drawn, and registering an atlas again swaps the images
|
||||
// of the icons that drew from it.
|
||||
const atlases = new Map();
|
||||
// View sheets icons draw subjects of, by id (`viewSheets`): each as its
|
||||
// image and checked layout, a new object whenever it is registered.
|
||||
const viewSheets = new Map();
|
||||
/** The blob each material or quad draws, held while it lives (`holdImage`). */
|
||||
const heldBlobs = new WeakMap();
|
||||
|
||||
@@ -6030,6 +6029,32 @@ export function createCesiumDraw({
|
||||
}
|
||||
if (changed) scene.requestRender();
|
||||
},
|
||||
...(capabilities.has('viewSheets')
|
||||
? {
|
||||
views(id, sheet) {
|
||||
viewSheets.set(
|
||||
id,
|
||||
Object.freeze({
|
||||
image: sheet.image,
|
||||
layout: viewLayout(sheet),
|
||||
grey: sheet.grey === true,
|
||||
}),
|
||||
);
|
||||
let changed = false;
|
||||
for (const record of sets.values())
|
||||
if (
|
||||
record.kind === 'icons' &&
|
||||
record.gpu &&
|
||||
record.views === id
|
||||
) {
|
||||
record.gpu.reviews();
|
||||
setsVersion += 1;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) scene.requestRender();
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -6154,7 +6179,11 @@ provideUnboundDraw((viewer) => {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: uncaught,
|
||||
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
|
||||
capabilities: new Set([
|
||||
...gpuIconCapabilities(scene),
|
||||
'fields',
|
||||
'modelParts',
|
||||
]),
|
||||
});
|
||||
unboundParts.set(part.port, part);
|
||||
const offs = [
|
||||
|
||||
@@ -2294,7 +2294,7 @@ test('points show only within their display range', () => {
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('the fire perimeters layer draws holed ground fills and draped outlines on a viewer of its own', async () => {
|
||||
test('the fire perimeters layer draws holed ground fills and draped fire lines on a viewer of its own', async () => {
|
||||
const { createFirePerimetersLayer } =
|
||||
await import('../../layers/perimeters/index.js');
|
||||
const scene = fakeScene();
|
||||
@@ -2313,19 +2313,9 @@ test('the fire perimeters layer draws holed ground fills and draped outlines on
|
||||
];
|
||||
const layer = createFirePerimetersLayer({
|
||||
source: {
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
revision: 'r',
|
||||
fires: [{ id: 'a', containedPct: 0, anchor: { lon: -108, lat: 35.2 } }],
|
||||
pieces: [
|
||||
{
|
||||
fireId: 'a',
|
||||
born: null,
|
||||
polygons: [[outer, hole]],
|
||||
outline: [outer, hole],
|
||||
},
|
||||
],
|
||||
}),
|
||||
getSnapshot: async () => [
|
||||
{ stableId: 'a', containedPct: 0, polygons: [[outer, hole]] },
|
||||
],
|
||||
},
|
||||
});
|
||||
layer.init(viewer);
|
||||
@@ -2346,9 +2336,9 @@ test('the fire perimeters layer draws holed ground fills and draped outlines on
|
||||
assert.equal(instance.geometry._polygonHierarchy.holes.length, 1);
|
||||
const [line] = of(Cesium.GroundPolylinePrimitive);
|
||||
assert.equal(line.classificationType, Cesium.ClassificationType.BOTH);
|
||||
assert.equal(line.geometryInstances.length, 2, 'the hole is outlined too');
|
||||
assert.equal(line.geometryInstances.length, 1, 'the exterior ring only');
|
||||
assert.equal(line.geometryInstances[0].geometry.width, 2);
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:line:0');
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:0');
|
||||
layer.destroy();
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
@@ -8883,3 +8873,39 @@ 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();
|
||||
});
|
||||
@@ -163,8 +163,6 @@ export function createSceneFrame(viewer) {
|
||||
const holds = new Map();
|
||||
// Told when the first hold is taken and the last released.
|
||||
const heldListeners = listenerList(uncaught);
|
||||
// Told every hold taken or released.
|
||||
const holdsListeners = listenerList(uncaught);
|
||||
const pendingRenders = new Set();
|
||||
const gone = () => disposed || scene.isDestroyed?.();
|
||||
const sceneTime = (time) =>
|
||||
@@ -252,7 +250,6 @@ export function createSceneFrame(viewer) {
|
||||
holds.set(reason, (holds.get(reason) ?? 0) + 1);
|
||||
if (!gone()) scene.requestRender();
|
||||
if (first) heldListeners.fire(true);
|
||||
holdsListeners.fire();
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
@@ -263,11 +260,9 @@ export function createSceneFrame(viewer) {
|
||||
// What changed in the last held frame still gets drawn.
|
||||
if (!gone()) scene.requestRender();
|
||||
if (holds.size === 0) heldListeners.fire(false);
|
||||
holdsListeners.fire();
|
||||
};
|
||||
},
|
||||
onHeldChange: (cb) => heldListeners.on(cb),
|
||||
onHoldsChange: (cb) => holdsListeners.on(cb),
|
||||
mode: () => (scene.requestRenderMode ? 'demand' : 'continuous'),
|
||||
diagnostics: () => ({
|
||||
mode: port.mode(),
|
||||
@@ -336,7 +331,6 @@ export function createSceneFrame(viewer) {
|
||||
for (const off of removers.splice(0)) off();
|
||||
for (const list of Object.values(listeners)) list.clear();
|
||||
heldListeners.clear();
|
||||
holdsListeners.clear();
|
||||
holds.clear();
|
||||
// Waits settle rather than stay attached to a scene gone quiet.
|
||||
for (const done of [...pendingRenders]) done();
|
||||
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user