mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-24 04:02:19 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
170b817679 | ||
|
|
d50f04efeb | ||
|
|
43bd25382d | ||
|
|
1f105a68af | ||
|
|
ec2f7d8ca7 | ||
|
|
51bf3d0807 | ||
|
|
d303d48693 |
No files matched your search
+1
-2
@@ -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 | 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; 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)" |
|
||||
| **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 |
|
||||
@@ -428,7 +428,6 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p
|
||||
| **DataSF Analysis Neighborhoods** (41 SF neighborhood polygons) | `neighborhoods/` | **PDDL 1.0** (public domain) | ✅ (no restrictions) | "City & County of San Francisco — DataSF" (courtesy — not legally required) |
|
||||
| **Natural Earth countries, states and provinces** (260 admin-0/map units + 4,587 admin-1 polygons) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **Natural Earth disputed areas** (11 of the source's 99 features, hand-picked; [list](src/data/local_data/natural_earth/README.md#disputed-areas-disputed_areasjson)) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **Home countries** (the opening's start view, 518 time zones → 247 country points) | `src/data/homeCountries.js` (built by `scripts/build-home-countries.mjs` from tzdata `zone.tab`, `tzdata.zi` and the Natural Earth countries pack) | **Public domain** (tzdata and Natural Earth) | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **Natural Earth populated places** (7,342 points: name, position, rank) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **Wikidata cities** (31,827 settlements of 15,000 people or more: name, position, population, country) | `wikidata_cities/` | **CC0 1.0** (public domain dedication) | ✅ (no restrictions) | "City, town and village names from Wikidata (CC0)" (courtesy credit — not legally required) |
|
||||
| **Wikidata places** (137,662 settlements of 1,000 to 14,999 people, none in the cities pack, in 732 tiles of 5°: name, position, population, country) | `wikidata_places/` | **CC0 1.0** (public domain dedication) | ✅ (no restrictions) | "City, town and village names from Wikidata (CC0)" (courtesy credit — not legally required) |
|
||||
|
||||
@@ -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 and reported containment | WFIGS / NIFC | 🟢 |
|
||||
| 🔥 **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 | 🟢 |
|
||||
| 🚢 **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,9 +0,0 @@
|
||||
- The app opens with the loading screen's logo turning into the globe: the eye
|
||||
flies at you and opens onto the app as it grows, and the planet in the pupil
|
||||
becomes the real globe, which grows to the whole planet, turns and stops over
|
||||
your country, taken from the browser's time zone. The title's logo goes back
|
||||
to that view. A link to only a view plays it too, closing in on that view
|
||||
after the turn; a link that follows or selects something or opens Street Level
|
||||
photos, a link that cannot be opened, a Stories link, an embedded view,
|
||||
reduced motion and `?intro=0` open as before. The address keeps out of the
|
||||
flight, so a reload during it reopens on the view it ends at (gekh, #1909).
|
||||
@@ -0,0 +1,8 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,4 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,3 @@
|
||||
- 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).
|
||||
+23
-31
@@ -1123,17 +1123,18 @@ 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 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`.
|
||||
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`.
|
||||
|
||||
## Scope display controls
|
||||
|
||||
@@ -5311,24 +5312,6 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> clock goes live and the camera flies to the view the app started from (the
|
||||
> host's `homeView`, else its `startView`, else the whole planet), letting go
|
||||
> of whatever it follows as Reset Globe does (`returnToStart()`).
|
||||
> On a bare address, the standalone app starts 23,000 km above the country of
|
||||
> the browser's time zone, looking straight down. It falls back to a preferred
|
||||
> language's region, then to the default start view. The lookup runs in the
|
||||
> browser (`src/homeCountry.js` and `src/data/homeCountries.js`).
|
||||
> Once the startup restore settles and at least one second has passed, the
|
||||
> loading text fades and the logo glides to the centre. The eye grows past the
|
||||
> screen edges as the drawn planet in its pupil gives way to the globe. The
|
||||
> globe grows to whole-planet size and turns once west to east, stopping over
|
||||
> the destination. For a closer or angled view, the camera then approaches or
|
||||
> turns to match it (`src/app/openingIntro.js`).
|
||||
> A bare address or a link that restores only a view plays the opening.
|
||||
> Links that follow or select something or open Street Level photos skip it,
|
||||
> as do failed, refused or superseded restores, a newer navigation, Stories
|
||||
> links, embedded views, reduced motion and `?intro=0`.
|
||||
> A press, click, key, touch or wheel event lands the opening immediately.
|
||||
> Another camera move stops the opening where the camera stands. During the
|
||||
> flight the address keeps the destination and globe-in-view recovery waits.
|
||||
> Welcome appears once the opening ends and the loading cover has faded.
|
||||
> - **Context, Cockpit, and Radio interaction contract:** explicit Contacts and
|
||||
> Radio actions and successful Cockpit actions can reveal Context. Contacts
|
||||
> uses the dedicated right-side chooser. Space Missions has its own rail
|
||||
@@ -6344,7 +6327,12 @@ 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`
|
||||
- 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.
|
||||
- Layer management in `src/data/manager.js`
|
||||
- Map stack switching in `src/mapStackController.js`
|
||||
- Voice control in `src/voice/` (OpenAI Realtime over WebRTC)
|
||||
@@ -6422,7 +6410,11 @@ 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. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
|
||||
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`.
|
||||
|
||||
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
|
||||
|
||||
+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 |
|
||||
| `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_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) |
|
||||
|
||||
+28
-1
@@ -629,7 +629,12 @@ 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),
|
||||
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`),
|
||||
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
|
||||
@@ -700,6 +705,28 @@ 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
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Writes src/data/homeCountries.js: each time zone's country, and where the
|
||||
// opening stops over that country.
|
||||
//
|
||||
// node scripts/build-home-countries.mjs [zone.tab] [tzdata.zi]
|
||||
//
|
||||
// Zones come from tzdata's zone.tab (macOS and most Linux systems ship it and
|
||||
// tzdata.zi at /usr/share/zoneinfo), with the names ICU gives them
|
||||
// (Asia/Calcutta for Asia/Kolkata) and the older names tzdata.zi links to
|
||||
// them (Asia/Choibalsan): a browser may give any of them. A country's point
|
||||
// lies inside its largest part in the Natural Earth countries pack (the
|
||||
// contiguous United States, mainland France), or is its first zone's place
|
||||
// where the pack has no such country.
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
countryAnchor,
|
||||
countryByCode,
|
||||
} from '../server/providers/news/areas.js';
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const zoneTab = process.argv[2] ?? '/usr/share/zoneinfo/zone.tab';
|
||||
const zoneLinks = process.argv[3] ?? '/usr/share/zoneinfo/tzdata.zi';
|
||||
const out = new URL('src/data/homeCountries.js', root);
|
||||
|
||||
const COUNTRY = /^[A-Z]{2}$/;
|
||||
const ZONE = /^[A-Za-z0-9_+-]+(?:\/[A-Za-z0-9_+-]+)*$/;
|
||||
const round = (value) => Math.round(value * 10) / 10;
|
||||
|
||||
/** ISO 6709 `±DDMM[SS]±DDDMM[SS]` → [lat, lon]. */
|
||||
function iso6709(text) {
|
||||
const [, lat, lon] =
|
||||
text.match(
|
||||
/^([+-]\d{2}[0-5]\d(?:[0-5]\d)?)([+-]\d{3}[0-5]\d(?:[0-5]\d)?)$/,
|
||||
) ?? [];
|
||||
if (!lat) throw new Error(`zone.tab: bad place ${text}`);
|
||||
const part = (s, degreeDigits) => {
|
||||
const sign = s[0] === '-' ? -1 : 1;
|
||||
const d = s.slice(1);
|
||||
const deg = Number(d.slice(0, degreeDigits));
|
||||
const min = Number(d.slice(degreeDigits, degreeDigits + 2));
|
||||
const sec = Number(d.slice(degreeDigits + 2) || 0);
|
||||
return sign * (deg + min / 60 + sec / 3600);
|
||||
};
|
||||
const place = [part(lat, 2), part(lon, 3)];
|
||||
if (Math.abs(place[0]) > 90 || Math.abs(place[1]) > 180)
|
||||
throw new Error(`zone.tab: place out of range ${text}`);
|
||||
return place;
|
||||
}
|
||||
|
||||
const zones = new Map();
|
||||
const centres = new Map();
|
||||
const icuName = (zone) => {
|
||||
try {
|
||||
return new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions()
|
||||
.timeZone;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
for (const line of readFileSync(zoneTab, 'utf8').split('\n')) {
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const [country, place, zone] = line.split('\t');
|
||||
if (!COUNTRY.test(country) || !zone || !ZONE.test(zone))
|
||||
throw new Error(`zone.tab: bad line ${JSON.stringify(line)}`);
|
||||
const coordinates = iso6709(place);
|
||||
zones.set(zone, country);
|
||||
const icu = icuName(zone);
|
||||
if (icu && icu !== zone && !zones.has(icu)) zones.set(icu, country);
|
||||
if (centres.has(country)) continue;
|
||||
const entry = countryByCode(country);
|
||||
const point = entry ? countryAnchor(entry) : null;
|
||||
centres.set(
|
||||
country,
|
||||
point ? [round(point.lat), round(point.lon)] : coordinates.map(round),
|
||||
);
|
||||
}
|
||||
// Older Area/Place names (Asia/Choibalsan, Europe/Uzhgorod), from tzdata.zi's
|
||||
// `L <zone> <older name>` links, each with the country of the zone ICU reads
|
||||
// it as: a link can lead to another country's zone with the same clocks
|
||||
// (Africa/Timbuktu to Abidjan). Bare names (CET, Japan) are left out: some
|
||||
// are clocks several countries keep.
|
||||
for (const line of readFileSync(zoneLinks, 'utf8').split('\n')) {
|
||||
const [kind, , name] = line.split(' ');
|
||||
if (kind !== 'L') continue;
|
||||
if (!name || !ZONE.test(name)) throw new Error(`tzdata.zi: bad link ${line}`);
|
||||
if (!name.includes('/') || zones.has(name)) continue;
|
||||
const country = zones.get(icuName(name));
|
||||
if (!country) continue;
|
||||
zones.set(name, country);
|
||||
}
|
||||
|
||||
const sortedEntries = (map) =>
|
||||
[...map].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
const lines = [
|
||||
'// Generated by scripts/build-home-countries.mjs. Do not edit by hand.',
|
||||
'// Sources: tzdata zone.tab and tzdata.zi (public domain) and the Natural',
|
||||
'// Earth countries pack in src/data/local_data/natural_earth (public domain).',
|
||||
'',
|
||||
"/** ISO 3166 country → [lat, lon]: in its largest part, else its first zone's place. */",
|
||||
'export const COUNTRY_CENTRES = {',
|
||||
...sortedEntries(centres).map(
|
||||
([country, [lat, lon]]) => ` ${country}: [${lat}, ${lon}],`,
|
||||
),
|
||||
'};',
|
||||
'',
|
||||
'/** Time zone (tzdata, ICU and older names) → ISO 3166 country. */',
|
||||
'export const ZONE_COUNTRIES = {',
|
||||
...sortedEntries(zones).map(
|
||||
([zone, country]) => ` '${zone}': '${country}',`,
|
||||
),
|
||||
'};',
|
||||
'',
|
||||
];
|
||||
writeFileSync(out, lines.join('\n'));
|
||||
console.log(
|
||||
`${fileURLToPath(out)}: ${centres.size} countries, ${zones.size} zones`,
|
||||
);
|
||||
@@ -469,6 +469,8 @@
|
||||
"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",
|
||||
@@ -1447,6 +1449,7 @@
|
||||
"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",
|
||||
|
||||
@@ -194,6 +194,8 @@
|
||||
"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",
|
||||
@@ -279,6 +281,7 @@
|
||||
"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",
|
||||
@@ -4303,7 +4306,6 @@
|
||||
"src/render/contract/index.js",
|
||||
"src/sources/sourceSlot.js",
|
||||
"src/app/sources.js",
|
||||
"src/app/openingIntro.js",
|
||||
"src/app/startupChrome.js",
|
||||
"src/app/stateChannel.js",
|
||||
"src/app/surfaceServices.js",
|
||||
@@ -4853,6 +4855,7 @@
|
||||
"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",
|
||||
@@ -8191,6 +8194,7 @@
|
||||
"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",
|
||||
|
||||
@@ -396,8 +396,7 @@ async function runArbitrationSection(page, { shots, consoleErrors }) {
|
||||
observer.observe(document, { childList: true, subtree: true });
|
||||
});
|
||||
try {
|
||||
// Disable the opening so only the cockpit holds the launcher back.
|
||||
await page.goto(`${APP_URL}/?welcome=1&intro=0`, { waitUntil: 'domcontentloaded' });
|
||||
await page.goto(`${APP_URL}/?welcome=1`, { waitUntil: 'domcontentloaded' });
|
||||
} finally {
|
||||
await page.removeScriptToEvaluateOnNewDocument(earlyCockpitBlocker.identifier);
|
||||
}
|
||||
|
||||
@@ -225,12 +225,9 @@ function newFixture(overrides = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Load without the opening so its flight cannot move the camera during
|
||||
* the gate's own moves, then dismiss the first-run dialog. */
|
||||
/** Load the app and dismiss the first-run dialog. */
|
||||
async function boot(page, url) {
|
||||
const address = new URL(url);
|
||||
address.searchParams.set('intro', '0');
|
||||
await page.goto(address.href, { waitUntil: 'domcontentloaded' });
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => Boolean(window.__godsEyeView?.dataManager), {
|
||||
timeout: 150_000,
|
||||
});
|
||||
|
||||
@@ -23,6 +23,7 @@ const API_URL =
|
||||
'attr_IncidentTypeCategory',
|
||||
'attr_FireDiscoveryDateTime',
|
||||
'poly_DateCurrent',
|
||||
'poly_PolygonDateTime',
|
||||
'attr_FireCause',
|
||||
'attr_FireBehaviorGeneral',
|
||||
'attr_TotalIncidentPersonnel',
|
||||
|
||||
@@ -67,6 +67,8 @@ 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,
|
||||
@@ -75,6 +77,7 @@ export function createApplicationCatalog({
|
||||
metadata = APPLICATION_LAYER_METADATA,
|
||||
vesselOptions,
|
||||
newsOptions,
|
||||
perimeterOptions,
|
||||
resolveAsset,
|
||||
nepalBoundaryResolver,
|
||||
streetLevelProviders,
|
||||
@@ -145,6 +148,7 @@ export function createApplicationCatalog({
|
||||
createApplicationEarthquakes({ source: sources.earthquakes }),
|
||||
createApplicationAirQuality({ source: sources['air-quality'] }),
|
||||
createApplicationFirePerimeters({
|
||||
...perimeterOptions,
|
||||
source: sources['fire-perimeters'],
|
||||
}),
|
||||
createApplicationGnssIntegrity({
|
||||
|
||||
@@ -7,6 +7,8 @@ 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();
|
||||
@@ -254,3 +256,48 @@ 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,8 +6,11 @@ import {
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
|
||||
/** Wire WFIGS fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters(options) {
|
||||
/** Wire fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters({
|
||||
inciweb = true,
|
||||
...options
|
||||
} = {}) {
|
||||
return createFirePerimetersLayer({
|
||||
overlayHost: {
|
||||
setEntries: overlays.setOverlayEntries,
|
||||
@@ -15,10 +18,17 @@ export function createApplicationFirePerimeters(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
...(inciweb !== false && {
|
||||
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,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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,410 +0,0 @@
|
||||
import { START_VIEW } from '../camera.js';
|
||||
import { normalizeCameraLongitude } from '../director/camera.js';
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
import { isEmbedded } from './embed.js';
|
||||
|
||||
/**
|
||||
* The opening: once the world has loaded, the loading screen's logo turns
|
||||
* into the globe, which grows to the whole planet's size, turns there to a
|
||||
* stop over the view it ends at and only then closes in on a closer one.
|
||||
* Everything is timed from one clock, in ms.
|
||||
*/
|
||||
export const OPENING = Object.freeze({
|
||||
/** The words under the logo fade. */
|
||||
textMs: 105,
|
||||
/** The logo moves to the centre. */
|
||||
centreMs: 630,
|
||||
// The rest is timed from the end of the move.
|
||||
/** The eye grows past the screen's edges. */
|
||||
eyeMs: 770,
|
||||
/** The drawn planet fades into the real one. */
|
||||
pupilMs: Object.freeze([420, 840]),
|
||||
/** The camera's flight starts. */
|
||||
flightStartMs: 210,
|
||||
/** The globe grows to the whole planet's size. */
|
||||
zoomMs: 1120,
|
||||
/** It turns there, slowing to a stop over the view it ends at: the turn
|
||||
* starts halfway through the zoom and ends this long after it. */
|
||||
spinMs: 1820,
|
||||
/** Then the camera closes in on a closer view (a shared one), per tenfold
|
||||
* change of height, within `approachMs`. */
|
||||
approachPerDecadeMs: 770,
|
||||
approachMs: Object.freeze([840, 2800]),
|
||||
/** How far the globe turns, degrees. */
|
||||
spinDeg: 360,
|
||||
});
|
||||
|
||||
const EARTH_RADIUS_M = 6371000;
|
||||
// public/logo.svg geometry, in its viewBox units.
|
||||
const EYE_CENTRE = Object.freeze({ x: 568.8, y: 379 });
|
||||
const EYE_WIDTH = 726.3;
|
||||
/** The empty circle inside the eye's ring, the app's window. */
|
||||
const WINDOW = Object.freeze({ x: 567, y: 382, r: 226 });
|
||||
/** How far past the screen's corners the window opens. */
|
||||
const WINDOW_COVER_MARGIN = 1.15;
|
||||
/** Never start further out than this, metres. */
|
||||
const MAX_FAR_HEIGHT_M = 4e8;
|
||||
/** The whole planet in view. */
|
||||
const PLANET_HEIGHT_M = START_VIEW.height;
|
||||
|
||||
/** Openings in progress on this page. */
|
||||
let playing = 0;
|
||||
|
||||
/**
|
||||
* Whether an opening is playing: the far start shows the globe as a speck,
|
||||
* which the globe-in-view recovery would otherwise turn the camera back to.
|
||||
*/
|
||||
export function openingPlaying() {
|
||||
return playing > 0;
|
||||
}
|
||||
|
||||
const clamp01 = (x) => Math.min(1, Math.max(0, x));
|
||||
const easeInCubic = (x) => x ** 3;
|
||||
const easeOutCubic = (x) => 1 - (1 - x) ** 3;
|
||||
const easeInOutCubic = (x) =>
|
||||
x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;
|
||||
const smoothstep = (x) => x * x * (3 - 2 * x);
|
||||
const span = (t, [from, to]) => clamp01((t - from) / (to - from));
|
||||
/** An angle, radians, the short way round. */
|
||||
const shortWay = (angle) =>
|
||||
angle - 2 * Math.PI * Math.round(angle / (2 * Math.PI));
|
||||
|
||||
/** Where each part of the opening stands `t` ms after it starts. */
|
||||
export function openingStage(t) {
|
||||
const move = clamp01(t / OPENING.centreMs);
|
||||
const after = t - OPENING.centreMs;
|
||||
const eye = clamp01(after / OPENING.eyeMs);
|
||||
return {
|
||||
/** The words' opacity. */
|
||||
text: 1 - clamp01(t / OPENING.textMs),
|
||||
/** How far the logo has moved to the centre, 0–1. */
|
||||
centre: easeInOutCubic(move),
|
||||
/** Whether the screen is shut except inside the eye. */
|
||||
shut: move >= 1,
|
||||
/** How far the eye has grown towards covering the screen, 0–1. */
|
||||
eyeGrowth: easeInCubic(eye),
|
||||
/** The eye's own opacity, and that of the shutter around it. */
|
||||
eyeOpacity: 1 - span(eye, [0.6, 1]),
|
||||
shutterOpacity: 1 - span(eye, [0.85, 1]),
|
||||
pupilOpacity: 1 - span(after, OPENING.pupilMs),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera's flight in, from `farHeight` over the equator, looking straight
|
||||
* down. The globe first grows to the whole planet's size (or `target`'s
|
||||
* height when that is further out), turns `spinDeg` west to east there,
|
||||
* slowing to a stop over `target`, and only then closes in on a closer
|
||||
* `target`, turning to its heading, pitch and roll (radians) on the way.
|
||||
* With nothing to close in on, it grows to `target`'s height.
|
||||
* Returns `{ ms, pose(at) }`: its length, and its pose `at` ms into it.
|
||||
*/
|
||||
export function openingFlight({ target, farHeight }) {
|
||||
const headingTo = shortWay(target.heading ?? 0);
|
||||
const rollTo = shortWay(target.roll ?? 0);
|
||||
const pitchTo = target.pitch ?? -Math.PI / 2;
|
||||
const turns =
|
||||
Math.abs(headingTo) > 1e-3 ||
|
||||
Math.abs(rollTo) > 1e-3 ||
|
||||
Math.abs(pitchTo + Math.PI / 2) > 1e-3;
|
||||
const above = Math.max(PLANET_HEIGHT_M, target.height);
|
||||
const decades = Math.log10(above / target.height);
|
||||
const [shortest, longest] = OPENING.approachMs;
|
||||
const approachMs =
|
||||
decades > 0.05 || turns
|
||||
? Math.min(
|
||||
longest,
|
||||
Math.max(shortest, decades * OPENING.approachPerDecadeMs),
|
||||
)
|
||||
: 0;
|
||||
const planet = approachMs ? above : target.height;
|
||||
const ms = OPENING.zoomMs + OPENING.spinMs + approachMs;
|
||||
const logLerp = (from, to, k) =>
|
||||
Math.exp(Math.log(from) + (Math.log(to) - Math.log(from)) * k);
|
||||
// The turn starts halfway through the zoom, as the drawn planet fades out.
|
||||
const spinFrom = OPENING.zoomMs / 2;
|
||||
const spinLength = OPENING.zoomMs + OPENING.spinMs - spinFrom;
|
||||
return {
|
||||
ms,
|
||||
pose(at) {
|
||||
const t = Math.min(Math.max(at, 0), ms);
|
||||
const zoom = smoothstep(clamp01(t / OPENING.zoomMs));
|
||||
const spin = easeOutCubic(clamp01((t - spinFrom) / spinLength));
|
||||
const approach = approachMs
|
||||
? clamp01((t - OPENING.zoomMs - OPENING.spinMs) / approachMs)
|
||||
: 0;
|
||||
const turning = easeInOutCubic(approach);
|
||||
return {
|
||||
lon: normalizeCameraLongitude(
|
||||
target.lon + OPENING.spinDeg * (1 - spin),
|
||||
),
|
||||
lat: target.lat * spin,
|
||||
height:
|
||||
approach > 0
|
||||
? logLerp(planet, target.height, smoothstep(approach))
|
||||
: logLerp(farHeight, planet, zoom),
|
||||
heading: headingTo * turning,
|
||||
pitch: -Math.PI / 2 + (pitchTo + Math.PI / 2) * turning,
|
||||
roll: rollTo * turning,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The globe's radius on screen, pixels, from `height` metres straight above
|
||||
* it, through a lens of vertical angle `fovy` on a view `viewportHeight`
|
||||
* pixels tall.
|
||||
*/
|
||||
export function globeRadiusPx(height, { fovy, viewportHeight }) {
|
||||
const angle = Math.asin(EARTH_RADIUS_M / (EARTH_RADIUS_M + height));
|
||||
return (Math.tan(angle) / Math.tan(fovy / 2)) * (viewportHeight / 2);
|
||||
}
|
||||
|
||||
/** The height at which the globe's radius on screen is `radiusPx`. */
|
||||
export function heightForGlobeRadius(radiusPx, { fovy, viewportHeight }) {
|
||||
const tangent = (radiusPx * Math.tan(fovy / 2)) / (viewportHeight / 2);
|
||||
return EARTH_RADIUS_M / Math.sin(Math.atan(tangent)) - EARTH_RADIUS_M;
|
||||
}
|
||||
|
||||
/**
|
||||
* How much the eye must grow, about its centre at the centre of `view`, for
|
||||
* its window (the empty circle inside its ring, `windowRadius` pixels) to
|
||||
* reach past the view's corners.
|
||||
*/
|
||||
function eyeCoverScale(windowRadius, view) {
|
||||
return (
|
||||
(WINDOW_COVER_MARGIN * Math.hypot(view.width, view.height)) /
|
||||
2 /
|
||||
windowRadius
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The cover around the eye's window: a shape the loading screen's colour, as
|
||||
* large as any screen, with the empty circle inside the eye's ring cut out of
|
||||
* it. It sits under the logo's parts and grows with the eye, so the screen is
|
||||
* shut but for that circle.
|
||||
*/
|
||||
function eyeShutter(eye) {
|
||||
const far = 1e5;
|
||||
// Centred where the eye grows from, so the two grow as one.
|
||||
const { x, y } = EYE_CENTRE;
|
||||
const { x: cx, y: cy, r } = WINDOW;
|
||||
const shutter = eye.ownerDocument.createElementNS(
|
||||
'http://www.w3.org/2000/svg',
|
||||
'path',
|
||||
);
|
||||
shutter.setAttribute(
|
||||
'd',
|
||||
`M${x - far},${y - far}H${x + far}V${y + far}H${x - far}Z` +
|
||||
`M${cx - r},${cy}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0Z`,
|
||||
);
|
||||
shutter.style.fill = 'var(--bg-dark)';
|
||||
shutter.setAttribute('fill-rule', 'evenodd');
|
||||
shutter.dataset.openingShutter = '';
|
||||
eye.parentNode.insertBefore(shutter, eye.parentNode.firstElementChild);
|
||||
return shutter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page opens with the opening: not where motion is reduced, not
|
||||
* in an embedded view (its host drives the camera, and an inline panel's host
|
||||
* may stop animation frames), not on a Stories link (Stories opens its own
|
||||
* view) and not with `?intro=0`.
|
||||
*/
|
||||
export function openingWanted(win = globalThis.window) {
|
||||
if (!win) return false;
|
||||
if (win.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
|
||||
return false;
|
||||
if (isEmbedded(win.location)) return false;
|
||||
const params = new URLSearchParams(win.location?.search ?? '');
|
||||
return !(
|
||||
params.get('intro') === '0' ||
|
||||
params.has('story') ||
|
||||
params.has('stories')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Play the opening over `loadingScreen`, ending where the camera stands (the
|
||||
* start view, or the view a link opened). Returns null when it does not
|
||||
* play: without the logo's own parts (an <img> logo opens as with reduced
|
||||
* motion), or for a camera at or below the ellipsoid. Else `done`, which
|
||||
* settles when the camera has stopped, and `cancel()`. A press, a click, a
|
||||
* key, a touch or the wheel skips to the end; any other camera move stops it
|
||||
* where it is. The loading screen is `hidden` once the real globe shows, or
|
||||
* at once on a cancel.
|
||||
* @param {{viewer: object, loadingScreen: HTMLElement, win?: Window,
|
||||
* camera?: object}} options `camera` is the viewer's camera port unless given.
|
||||
*/
|
||||
export function playOpeningIntro({
|
||||
viewer,
|
||||
loadingScreen,
|
||||
win = globalThis.window,
|
||||
camera = null,
|
||||
}) {
|
||||
if (!openingWanted(win)) return null;
|
||||
camera ??= findCamera(viewer);
|
||||
if (!camera) return null;
|
||||
const target = camera.pose();
|
||||
if (
|
||||
!Number.isFinite(target.height) ||
|
||||
target.height <= 0 ||
|
||||
!Number.isFinite(target.lon) ||
|
||||
!Number.isFinite(target.lat)
|
||||
)
|
||||
return null;
|
||||
const doc = loadingScreen.ownerDocument;
|
||||
const logo = loadingScreen.querySelector('.loader-logo');
|
||||
const svg = logo?.querySelector('svg');
|
||||
const eye = svg?.querySelector('#outer_eye');
|
||||
// The drawn planet: its blue disc, continents and grid.
|
||||
const disc = svg?.querySelector('#inner_eye');
|
||||
if (!eye || !disc) return null;
|
||||
const pupil = [
|
||||
disc,
|
||||
svg.querySelector('#globe'),
|
||||
svg.querySelector('#globe_cage'),
|
||||
].filter(Boolean);
|
||||
// Each part fades from its own opacity: the grid is translucent.
|
||||
const ownOpacity = pupil.map((element) => {
|
||||
const opacity = Number.parseFloat(win.getComputedStyle(element).opacity);
|
||||
return Number.isFinite(opacity) ? opacity : 1;
|
||||
});
|
||||
const shutter = eyeShutter(eye);
|
||||
|
||||
loadingScreen.classList.add('opening');
|
||||
playing += 1;
|
||||
// Cancel the logo gaze's offset (src/logoGaze.js): the pupil starts centred.
|
||||
for (const element of pupil) element.style.transform = 'none';
|
||||
const pupilRect = disc.getBoundingClientRect();
|
||||
const eyeRect = eye.getBoundingClientRect();
|
||||
const view = (
|
||||
doc.getElementById('cesiumContainer') ?? doc.documentElement
|
||||
).getBoundingClientRect();
|
||||
const viewportHeight = view.height || win.innerHeight;
|
||||
const lens = { fovy: target.fovy, viewportHeight };
|
||||
const pupilRadius = pupilRect.width / 2;
|
||||
const farHeight = Math.min(
|
||||
MAX_FAR_HEIGHT_M,
|
||||
Math.max(target.height * 2, heightForGlobeRadius(pupilRadius, lens)),
|
||||
);
|
||||
const toCentre = {
|
||||
x: view.left + view.width / 2 - (pupilRect.left + pupilRect.width / 2),
|
||||
y: view.top + view.height / 2 - (pupilRect.top + pupilRect.height / 2),
|
||||
};
|
||||
const startRadius = globeRadiusPx(farHeight, lens);
|
||||
// Where the far start is capped (a wide screen), the globe there is larger
|
||||
// than the drawn planet: the logo grows to it on its way to the centre,
|
||||
// under the cover, and matches it from then on.
|
||||
const discScale = pupilRadius > 0 ? startRadius / pupilRadius : 1;
|
||||
const eyeCover = eyeRect.width
|
||||
? eyeCoverScale((eyeRect.width * WINDOW.r) / EYE_WIDTH, {
|
||||
width: view.width || win.innerWidth,
|
||||
height: viewportHeight,
|
||||
})
|
||||
: 1;
|
||||
|
||||
let driving = false;
|
||||
/** The camera as the opening last left it. */
|
||||
let placed = null;
|
||||
const place = ({ lon, lat, height, heading, pitch, roll = 0 }) => {
|
||||
driving = true;
|
||||
try {
|
||||
camera.setView({
|
||||
destination: { lon, lat, height },
|
||||
orientation: { heading, pitch, roll },
|
||||
});
|
||||
} finally {
|
||||
driving = false;
|
||||
}
|
||||
placed = camera.pose();
|
||||
};
|
||||
// A move made on the renderer's own camera sends no command.
|
||||
const movedElsewhere = () => {
|
||||
const now = camera.pose();
|
||||
return (
|
||||
Math.abs(now.lat - placed.lat) > 1e-6 ||
|
||||
Math.abs(normalizeCameraLongitude(now.lon - placed.lon)) > 1e-6 ||
|
||||
Math.abs(now.height - placed.height) > 1
|
||||
);
|
||||
};
|
||||
|
||||
let resolveDone;
|
||||
const done = new Promise((resolve) => {
|
||||
resolveDone = resolve;
|
||||
});
|
||||
let frame = 0;
|
||||
let finished = false;
|
||||
const hide = () => loadingScreen.classList.add('hidden');
|
||||
const stopCommands = camera.onCommand(() => {
|
||||
if (!driving) finish();
|
||||
});
|
||||
const inputs = ['pointerdown', 'click', 'wheel', 'keydown', 'touchstart'];
|
||||
const onInput = () => finish({ land: true });
|
||||
for (const type of inputs)
|
||||
win.addEventListener(type, onInput, { capture: true, passive: true });
|
||||
|
||||
function finish({ land = false } = {}) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
playing -= 1;
|
||||
try {
|
||||
if (frame) win.cancelAnimationFrame(frame);
|
||||
stopCommands();
|
||||
for (const type of inputs)
|
||||
win.removeEventListener(type, onInput, { capture: true });
|
||||
if (land) place(target);
|
||||
} finally {
|
||||
hide();
|
||||
resolveDone();
|
||||
}
|
||||
}
|
||||
|
||||
const flight = openingFlight({ target, farHeight });
|
||||
const start = win.performance.now();
|
||||
const step = () => {
|
||||
frame = 0;
|
||||
if (finished) return;
|
||||
try {
|
||||
if (placed && movedElsewhere()) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
const t = win.performance.now() - start;
|
||||
const flown = t - OPENING.centreMs - OPENING.flightStartMs;
|
||||
if (flown >= flight.ms) {
|
||||
finish({ land: true });
|
||||
return;
|
||||
}
|
||||
const stage = openingStage(t);
|
||||
const pose = flight.pose(flown);
|
||||
place(pose);
|
||||
const scale =
|
||||
(globeRadiusPx(pose.height, lens) / startRadius) *
|
||||
(1 + (discScale - 1) * stage.centre);
|
||||
loadingScreen.style.setProperty('--opening-text', stage.text);
|
||||
// Once the logo is centred, the shutter around the eye is the cover.
|
||||
loadingScreen.style.setProperty('--opening-veil', stage.shut ? 0 : 1);
|
||||
logo.style.transform = `translate(${toCentre.x * stage.centre}px, ${
|
||||
toCentre.y * stage.centre
|
||||
}px) scale(${scale})`;
|
||||
const eyeScale = `scale(${1 + (eyeCover - 1) * stage.eyeGrowth})`;
|
||||
eye.style.transform = eyeScale;
|
||||
eye.style.opacity = stage.eyeOpacity;
|
||||
shutter.style.transform = eyeScale;
|
||||
shutter.style.opacity = stage.shutterOpacity;
|
||||
pupil.forEach((element, i) => {
|
||||
element.style.opacity = ownOpacity[i] * stage.pupilOpacity;
|
||||
});
|
||||
if (stage.pupilOpacity === 0) hide();
|
||||
frame = win.requestAnimationFrame(step);
|
||||
} catch (error) {
|
||||
finish();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
step();
|
||||
return { done, cancel: () => finish() };
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import {
|
||||
OPENING,
|
||||
globeRadiusPx,
|
||||
heightForGlobeRadius,
|
||||
openingFlight,
|
||||
openingPlaying,
|
||||
openingStage,
|
||||
openingWanted,
|
||||
playOpeningIntro,
|
||||
} from './openingIntro.js';
|
||||
|
||||
const LENS = { fovy: Math.PI / 4, viewportHeight: 800 };
|
||||
const TARGET = { lon: 10.4, lat: 51.1, height: 23e6, heading: 0, pitch: -1 };
|
||||
const LANDED = { lon: TARGET.lon, lat: TARGET.lat, height: TARGET.height };
|
||||
const PLANET_FLIGHT_MS = OPENING.zoomMs + OPENING.spinMs;
|
||||
|
||||
test('the words fade, then the eye opens past the screen before the globe arrives', () => {
|
||||
const start = openingStage(0);
|
||||
assert.equal(start.text, 1);
|
||||
assert.equal(start.shut, false);
|
||||
assert.equal(start.pupilOpacity, 1);
|
||||
assert.equal(openingStage(OPENING.textMs).text, 0, 'the words go first');
|
||||
assert.ok(openingStage(OPENING.textMs).centre < 0.5);
|
||||
const centred = openingStage(OPENING.centreMs);
|
||||
assert.equal(centred.text, 0);
|
||||
assert.equal(centred.centre, 1);
|
||||
assert.equal(centred.shut, true, 'shut but for the eye');
|
||||
assert.equal(centred.eyeGrowth, 0);
|
||||
const half = openingStage(OPENING.centreMs + OPENING.eyeMs / 2);
|
||||
assert.ok(half.eyeGrowth > 0 && half.eyeGrowth < 0.5, 'it speeds up');
|
||||
assert.equal(half.pupilOpacity, 1, 'the planet stays in the pupil');
|
||||
const open = openingStage(OPENING.centreMs + OPENING.eyeMs);
|
||||
assert.equal(open.eyeGrowth, 1);
|
||||
assert.equal(open.eyeOpacity, 0);
|
||||
assert.equal(open.shutterOpacity, 0);
|
||||
const real = openingStage(OPENING.centreMs + OPENING.pupilMs[1]);
|
||||
assert.equal(real.pupilOpacity, 0);
|
||||
});
|
||||
|
||||
const FAR = 4e8;
|
||||
const PLANET = { lon: 10.4, lat: 51.1, height: 23e6 };
|
||||
const unwrap = (lon, near) => lon + 360 * Math.round((near - lon) / 360);
|
||||
|
||||
test('the globe grows to the planet first, then turns there to a stop', () => {
|
||||
const flight = openingFlight({ target: PLANET, farHeight: FAR });
|
||||
assert.equal(flight.ms, PLANET_FLIGHT_MS, 'nothing to close in on');
|
||||
const start = flight.pose(0);
|
||||
assert.ok(Math.abs(start.height - FAR) < 1);
|
||||
assert.equal(start.lat, 0);
|
||||
assert.ok(
|
||||
Math.abs(flight.pose(OPENING.zoomMs).height - PLANET.height) < 1,
|
||||
'the whole planet first',
|
||||
);
|
||||
// Unwrapped longitude falls all the way (the camera moves west, so the
|
||||
// surface turns east), from halfway through the zoom, slowing to a stop.
|
||||
const spinFrom = OPENING.zoomMs / 2;
|
||||
let previous = PLANET.lon + OPENING.spinDeg;
|
||||
let previousStep = Infinity;
|
||||
for (let i = 0; i <= 100; i++) {
|
||||
const at = spinFrom + ((flight.ms - spinFrom) * i) / 100;
|
||||
const pose = flight.pose(at);
|
||||
if (at >= OPENING.zoomMs)
|
||||
assert.ok(Math.abs(pose.height - PLANET.height) < 1, 'turns at size');
|
||||
assert.ok(pose.lon >= -180 && pose.lon < 180);
|
||||
const lon = unwrap(pose.lon, previous);
|
||||
const step = previous - lon;
|
||||
assert.ok(step >= -1e-9, 'west to east');
|
||||
if (i > 1) assert.ok(step <= previousStep + 1e-9, 'the turn slows');
|
||||
previous = lon;
|
||||
previousStep = step;
|
||||
}
|
||||
assert.ok(Math.abs(previous - PLANET.lon) < 1e-9, 'one whole turn');
|
||||
const end = flight.pose(flight.ms);
|
||||
assert.ok(Math.abs(end.lon - PLANET.lon) < 1e-9);
|
||||
assert.ok(Math.abs(end.lat - PLANET.lat) < 1e-9);
|
||||
assert.equal(end.pitch, -Math.PI / 2);
|
||||
});
|
||||
|
||||
test('a closer view at an angle is closed in on after the turn', () => {
|
||||
const angled = {
|
||||
lon: 2.35,
|
||||
lat: 48.86,
|
||||
height: 5000,
|
||||
heading: 5.5,
|
||||
pitch: -0.5,
|
||||
};
|
||||
const flight = openingFlight({ target: angled, farHeight: FAR });
|
||||
assert.ok(flight.ms > PLANET_FLIGHT_MS);
|
||||
assert.ok(flight.ms <= PLANET_FLIGHT_MS + OPENING.approachMs[1]);
|
||||
const turned = flight.pose(PLANET_FLIGHT_MS);
|
||||
assert.ok(Math.abs(turned.height - 23e6) < 1, 'over the whole planet');
|
||||
assert.ok(Math.abs(turned.lon - angled.lon) < 1e-9);
|
||||
assert.ok(Math.abs(turned.lat - angled.lat) < 1e-9);
|
||||
assert.ok(Math.abs(turned.heading) < 1e-12);
|
||||
assert.equal(turned.pitch, -Math.PI / 2, 'straight down until then');
|
||||
const end = flight.pose(flight.ms);
|
||||
// 5.5 rad turns the short way round: -0.78 rad.
|
||||
assert.ok(Math.abs(end.heading - (5.5 - 2 * Math.PI)) < 1e-9);
|
||||
assert.ok(Math.abs(end.pitch - angled.pitch) < 1e-9);
|
||||
assert.ok(Math.abs(end.height - angled.height) < 1e-6);
|
||||
assert.ok(Math.abs(end.lon - angled.lon) < 1e-9);
|
||||
});
|
||||
|
||||
test('a view further out than the planet turns at that height', () => {
|
||||
const far = { lon: -97.74, lat: 0, height: 2.8e8 };
|
||||
const flight = openingFlight({ target: far, farHeight: FAR });
|
||||
assert.equal(flight.ms, PLANET_FLIGHT_MS);
|
||||
assert.ok(Math.abs(flight.pose(OPENING.zoomMs).height - far.height) < 1);
|
||||
assert.ok(Math.abs(flight.pose(flight.ms).height - far.height) < 1);
|
||||
});
|
||||
|
||||
test('the far start draws the globe the size of the pupil', () => {
|
||||
for (const radius of [12, 20, 64]) {
|
||||
const height = heightForGlobeRadius(radius, LENS);
|
||||
assert.ok(Math.abs(globeRadiusPx(height, LENS) - radius) < 1e-6);
|
||||
}
|
||||
assert.ok(globeRadiusPx(4e8, LENS) < globeRadiusPx(23e6, LENS));
|
||||
});
|
||||
|
||||
test('reduced motion, embedded views, Stories links and ?intro=0 open without it', () => {
|
||||
const win = (search, reduced = false) => ({
|
||||
location: { search },
|
||||
matchMedia: () => ({ matches: reduced }),
|
||||
});
|
||||
assert.equal(openingWanted(win('')), true);
|
||||
assert.equal(openingWanted(win('', true)), false);
|
||||
assert.equal(openingWanted(win('?intro=0')), false);
|
||||
assert.equal(openingWanted(win('?story=abc')), false);
|
||||
assert.equal(openingWanted(win('?stories')), false);
|
||||
assert.equal(openingWanted(win('?intro=1')), true);
|
||||
assert.equal(openingWanted(win('?embed=1')), false);
|
||||
globalThis.GEV_EMBED_INLINE = true;
|
||||
try {
|
||||
assert.equal(openingWanted(win('')), false);
|
||||
} finally {
|
||||
delete globalThis.GEV_EMBED_INLINE;
|
||||
}
|
||||
});
|
||||
|
||||
// A loading screen and a camera port; the test runs the frames by hand.
|
||||
function stage({
|
||||
target = TARGET,
|
||||
width = 1280,
|
||||
height = 800,
|
||||
fovy = Math.PI / 4,
|
||||
disc = null,
|
||||
} = {}) {
|
||||
const window = new Window({ width, height });
|
||||
const doc = window.document;
|
||||
doc.body.innerHTML = `
|
||||
<style>.cls-4 { opacity: 0.63; }</style>
|
||||
<div id="cesiumContainer"></div>
|
||||
<div id="loading-screen"><span class="loader-logo"><svg>
|
||||
<path id="outer_eye" d="M0,10C0,0,20,0,20,10C20,20,0,20,0,10ZM5,10h1"/>
|
||||
<path id="inner_eye"/>
|
||||
<path id="globe"/><path id="globe_cage" class="cls-4"/>
|
||||
</svg></span></div>`;
|
||||
const screen = doc.getElementById('loading-screen');
|
||||
doc.getElementById('cesiumContainer').getBoundingClientRect = () => ({
|
||||
left: 0,
|
||||
top: 0,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
if (disc) {
|
||||
doc.getElementById('inner_eye').getBoundingClientRect = () => ({
|
||||
left: (width - disc) / 2,
|
||||
top: (height - disc) / 2,
|
||||
width: disc,
|
||||
height: disc,
|
||||
});
|
||||
}
|
||||
let now = 0;
|
||||
let frames = [];
|
||||
window.performance.now = () => now;
|
||||
window.requestAnimationFrame = (fn) => frames.push(fn);
|
||||
window.cancelAnimationFrame = () => {
|
||||
frames = [];
|
||||
};
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
const views = [];
|
||||
const commandListeners = new Set();
|
||||
let current = { ...target, fovy };
|
||||
const camera = {
|
||||
pose: () => ({ ...current }),
|
||||
rawMove(pose) {
|
||||
current = { ...pose, fovy };
|
||||
},
|
||||
setView(spec) {
|
||||
views.push(spec);
|
||||
current = { ...spec.destination, ...spec.orientation, fovy };
|
||||
for (const cb of commandListeners) cb({ kind: 'setView' });
|
||||
},
|
||||
onCommand(cb) {
|
||||
commandListeners.add(cb);
|
||||
return () => commandListeners.delete(cb);
|
||||
},
|
||||
};
|
||||
return {
|
||||
window,
|
||||
screen,
|
||||
views,
|
||||
camera,
|
||||
commandListeners,
|
||||
doc,
|
||||
current: () => current,
|
||||
play: () =>
|
||||
playOpeningIntro({
|
||||
viewer: {},
|
||||
loadingScreen: screen,
|
||||
win: window,
|
||||
camera,
|
||||
}),
|
||||
advance(ms) {
|
||||
now += ms;
|
||||
const run = frames;
|
||||
frames = [];
|
||||
for (const fn of run) fn();
|
||||
},
|
||||
advanceTo(ms, stepMs = 1000 / 60) {
|
||||
while (now < ms) this.advance(Math.min(stepMs, ms - now));
|
||||
},
|
||||
otherMove: () => {
|
||||
for (const cb of [...commandListeners]) cb({ kind: 'flyTo' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the opening runs to the start view, then hides the cover', async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
assert.ok(opening);
|
||||
assert.equal(openingPlaying(), true);
|
||||
assert.ok(s.screen.classList.contains('opening'));
|
||||
assert.ok(s.views[0].destination.height > TARGET.height * 2, 'far start');
|
||||
const shutter = s.screen.querySelector('[data-opening-shutter]');
|
||||
assert.ok(shutter, 'the cover around the eye');
|
||||
assert.match(
|
||||
shutter.getAttribute('d'),
|
||||
/ZM341,382a226,226 0 1,0 452,0a226,226 0 1,0 -452,0Z$/,
|
||||
'the empty circle inside the ring',
|
||||
);
|
||||
assert.equal(shutter.getAttribute('fill-rule'), 'evenodd');
|
||||
s.advance(OPENING.centreMs);
|
||||
assert.equal(s.screen.style.getPropertyValue('--opening-veil'), '0');
|
||||
s.advance(Math.max(OPENING.eyeMs, OPENING.pupilMs[1]));
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
s.advance(10000);
|
||||
await opening.done;
|
||||
const last = s.views.at(-1);
|
||||
assert.deepEqual(last.destination, LANDED);
|
||||
assert.equal(last.orientation.heading, TARGET.heading);
|
||||
assert.equal(last.orientation.pitch, TARGET.pitch);
|
||||
assert.equal(openingPlaying(), false);
|
||||
assert.equal(s.commandListeners.size, 0);
|
||||
});
|
||||
|
||||
test("the person's input skips to the start view", async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
s.window.dispatchEvent(new s.window.Event('keydown'));
|
||||
await opening.done;
|
||||
assert.deepEqual(s.views.at(-1).destination, LANDED);
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
assert.equal(openingPlaying(), false);
|
||||
});
|
||||
|
||||
test('another camera move stops it where it is', async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
const count = s.views.length;
|
||||
s.otherMove();
|
||||
await opening.done;
|
||||
s.advance(1000);
|
||||
assert.equal(s.views.length, count, 'no more frames');
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
});
|
||||
|
||||
const HOME = { ...TARGET, pitch: -Math.PI / 2, roll: 0 };
|
||||
const CLOSE = {
|
||||
lon: 2.3522,
|
||||
lat: 48.8566,
|
||||
height: 5000,
|
||||
heading: 0,
|
||||
pitch: -0.61,
|
||||
roll: Math.PI / 6,
|
||||
};
|
||||
|
||||
test("a move made on the renderer's own camera stops it there", async () => {
|
||||
const s = stage({ target: HOME });
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
const park = { ...HOME, lon: -121.49, lat: 38.5816, height: 900 };
|
||||
s.camera.rawMove(park);
|
||||
s.advance(16);
|
||||
assert.equal(s.current().lat, park.lat);
|
||||
s.advanceTo(15000);
|
||||
await opening.done;
|
||||
assert.equal(s.current().lat, park.lat);
|
||||
});
|
||||
|
||||
test('a shared roll survives the landing and a skip', async () => {
|
||||
for (const skip of [false, true]) {
|
||||
const s = stage({ target: CLOSE });
|
||||
const opening = s.play();
|
||||
if (skip) {
|
||||
s.advance(2000);
|
||||
s.window.dispatchEvent(new s.window.Event('keydown'));
|
||||
} else {
|
||||
s.advanceTo(15000);
|
||||
}
|
||||
await opening.done;
|
||||
assert.ok(Math.abs(s.views.at(-1).orientation.roll - CLOSE.roll) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('a view at or below the ellipsoid plays no opening', () => {
|
||||
for (const height of [-100, 0]) {
|
||||
const s = stage({ target: { ...CLOSE, lon: 35.5, lat: 31.5, height } });
|
||||
assert.equal(s.play(), null);
|
||||
assert.equal(s.views.length, 0);
|
||||
assert.equal(s.screen.classList.contains('opening'), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('a view just below the planet height lands without a jump', async () => {
|
||||
const target = { ...HOME, lon: 10, lat: 50, height: 21e6 };
|
||||
const flight = openingFlight({ target, farHeight: FAR });
|
||||
const s = stage({ target });
|
||||
const opening = s.play();
|
||||
s.advanceTo(OPENING.centreMs + OPENING.flightStartMs + flight.ms + 50, 1);
|
||||
await opening.done;
|
||||
assert.equal(s.views.at(-1).destination.height, target.height);
|
||||
assert.ok(Math.abs(s.views.at(-2).destination.height - target.height) < 1000);
|
||||
});
|
||||
|
||||
test('on any screen the drawn planet matches the globe once the logo is centred', () => {
|
||||
for (const [width, height] of [
|
||||
[1280, 800],
|
||||
[2560, 1440],
|
||||
[3440, 1440],
|
||||
[3840, 2160],
|
||||
]) {
|
||||
const fovy = 2 * Math.atan((Math.tan(Math.PI / 6) * height) / width);
|
||||
const s = stage({ target: HOME, width, height, fovy, disc: 64 });
|
||||
const opening = s.play();
|
||||
const logo = s.screen.querySelector('.loader-logo');
|
||||
for (const at of [900, 1800]) {
|
||||
s.advanceTo(at);
|
||||
const scale = Number(/scale\(([^)]+)\)/.exec(logo.style.transform)[1]);
|
||||
const radius = globeRadiusPx(s.current().height, {
|
||||
fovy,
|
||||
viewportHeight: height,
|
||||
});
|
||||
assert.ok(
|
||||
Math.abs(32 * scale - radius) < 1,
|
||||
`${width}×${height} at ${at} ms`,
|
||||
);
|
||||
}
|
||||
opening.cancel();
|
||||
}
|
||||
});
|
||||
|
||||
test("the logo's grid fades from its own opacity", () => {
|
||||
const s = stage();
|
||||
const cage = s.doc.getElementById('globe_cage');
|
||||
const opening = s.play();
|
||||
assert.equal(Number(s.window.getComputedStyle(cage).opacity), 0.63);
|
||||
// Halfway through the drawn planet's fade.
|
||||
const [from, to] = OPENING.pupilMs;
|
||||
s.advance(OPENING.centreMs + (from + to) / 2);
|
||||
assert.ok(
|
||||
Math.abs(Number(s.window.getComputedStyle(cage).opacity) - 0.315) < 0.01,
|
||||
);
|
||||
opening.cancel();
|
||||
});
|
||||
|
||||
test('a lone click lands the opening before its handler reads the camera', async () => {
|
||||
const s = stage({ target: CLOSE });
|
||||
const opening = s.play();
|
||||
s.advanceTo(3000);
|
||||
const button = s.doc.createElement('button');
|
||||
s.doc.body.appendChild(button);
|
||||
let seen;
|
||||
button.addEventListener('click', () => {
|
||||
seen = s.current();
|
||||
});
|
||||
button.click();
|
||||
assert.equal(seen.height, CLOSE.height);
|
||||
await opening.done;
|
||||
});
|
||||
@@ -1,10 +1,6 @@
|
||||
import { initFirstRunExperience } from '../firstRunExperience.js';
|
||||
|
||||
/**
|
||||
* Reveal welcome controls only after restoration and the loading transition.
|
||||
* `playOpening` plays the opening (src/app/openingIntro.js) on a bare address
|
||||
* or a share of only a view.
|
||||
*/
|
||||
/** Reveal welcome controls only after restoration and the loading transition. */
|
||||
export function startApplicationChrome({
|
||||
loadingScreen,
|
||||
styleManager,
|
||||
@@ -12,87 +8,32 @@ export function startApplicationChrome({
|
||||
signal,
|
||||
initializeWelcome = initFirstRunExperience,
|
||||
initializeSettings,
|
||||
playOpening = null,
|
||||
}) {
|
||||
let disposed = false;
|
||||
let firstRun;
|
||||
let opening = null;
|
||||
let revealTimer;
|
||||
let resolveDelay;
|
||||
const minimumDelay = new Promise((resolve) => {
|
||||
resolveDelay = resolve;
|
||||
});
|
||||
const delayTimer = setTimeout(resolveDelay, 1000);
|
||||
// A navigation stamped after this (a search, a posted view, a later link)
|
||||
// owns the camera: the opening must not take it back.
|
||||
const generationAtStart = styleManager._navigationGeneration;
|
||||
const revealFirstRun = () => {
|
||||
if (disposed || signal.aborted || firstRun) return;
|
||||
firstRun = initializeWelcome?.({ styleManager, dataManager });
|
||||
clearTimeout(revealTimer);
|
||||
loadingScreen.removeEventListener('transitionend', revealFirstRun);
|
||||
};
|
||||
// Welcome waits for the cover's fade, or for 900 ms where none ends.
|
||||
const revealAfterCover = () => {
|
||||
if (disposed || signal.aborted) return;
|
||||
loadingScreen.addEventListener('transitionend', revealFirstRun, {
|
||||
once: true,
|
||||
});
|
||||
revealTimer = setTimeout(revealFirstRun, 900);
|
||||
};
|
||||
void Promise.all([styleManager.initialRestorePromise, minimumDelay])
|
||||
.catch(() => {
|
||||
/* Restoration reports its own outcome through the controls. */
|
||||
})
|
||||
.then(([restored] = []) => {
|
||||
.then(() => {
|
||||
if (disposed || signal.aborted) return;
|
||||
// A bare address, or a share of only a view, opens with the opening
|
||||
// unless a newer navigation took the camera or the link was refused.
|
||||
// Hold the restored address through the flight so a reload or a copied
|
||||
// link opens at the destination.
|
||||
const shareLink = styleManager.shareLinkManager;
|
||||
const generation = Number.isInteger(restored?.navigationToken)
|
||||
? restored.navigationToken
|
||||
: generationAtStart;
|
||||
const navigatedSince =
|
||||
Number.isFinite(generation) &&
|
||||
styleManager._navigationGeneration !== generation;
|
||||
const wanted =
|
||||
!!playOpening &&
|
||||
!navigatedSince &&
|
||||
!shareLink?.rejectedShareCode &&
|
||||
(!styleManager.hasShareState || sharesOnlyAView(restored));
|
||||
if (wanted) shareLink?.holdWrites?.(true, 'opening');
|
||||
try {
|
||||
opening = wanted
|
||||
? playOpening({ viewer: styleManager.viewer, loadingScreen })
|
||||
: null;
|
||||
} catch (error) {
|
||||
console.error('The opening failed', error);
|
||||
opening = null;
|
||||
}
|
||||
const release = () => shareLink?.holdWrites?.(false, 'opening');
|
||||
if (opening) {
|
||||
// The cover fades long before a played-out opening ends; a skip
|
||||
// hides it only as the opening ends.
|
||||
let coverFaded = false;
|
||||
const onCoverFaded = () => {
|
||||
coverFaded = true;
|
||||
};
|
||||
loadingScreen.addEventListener('transitionend', onCoverFaded, {
|
||||
once: true,
|
||||
});
|
||||
void opening.done.then(() => {
|
||||
release();
|
||||
loadingScreen.removeEventListener('transitionend', onCoverFaded);
|
||||
if (coverFaded) revealFirstRun();
|
||||
else revealAfterCover();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (wanted) release();
|
||||
loadingScreen.classList.add('hidden');
|
||||
revealAfterCover();
|
||||
loadingScreen.addEventListener('transitionend', revealFirstRun, {
|
||||
once: true,
|
||||
});
|
||||
revealTimer = setTimeout(revealFirstRun, 900);
|
||||
});
|
||||
const keySetup = Promise.resolve(
|
||||
signal.aborted ? null : initializeSettings?.({ signal }),
|
||||
@@ -103,7 +44,6 @@ export function startApplicationChrome({
|
||||
);
|
||||
return async () => {
|
||||
disposed = true;
|
||||
opening?.cancel();
|
||||
clearTimeout(delayTimer);
|
||||
clearTimeout(revealTimer);
|
||||
resolveDelay();
|
||||
@@ -112,17 +52,3 @@ export function startApplicationChrome({
|
||||
(await keySetup.catch(() => null))?.destroy();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a start-up share restore left only a view: the camera landed where
|
||||
* the link points and nothing is followed or selected for it.
|
||||
*/
|
||||
function sharesOnlyAView(restored) {
|
||||
return (
|
||||
restored?.status === 'settled' &&
|
||||
restored.share?.camera === 'applied' &&
|
||||
restored.tracking?.status === 'skipped' &&
|
||||
restored.tracking.reason === 'no-shared-target' &&
|
||||
!restored.thing
|
||||
);
|
||||
}
|
||||
+5
-5
@@ -22,7 +22,6 @@ import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
|
||||
import { createRecentImageryPanel } from '../ui/recentImagery.js';
|
||||
import { createDataLibrary } from '../library/controller.js';
|
||||
import { flyToLibraryExtent } from '../library/camera.js';
|
||||
import { openingPlaying } from './openingIntro.js';
|
||||
import { createLibraryBrowser } from '../ui/libraryBrowser.js';
|
||||
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
|
||||
import { localGeoJsonServices } from './localGeojsonServices.js';
|
||||
@@ -40,6 +39,7 @@ import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
|
||||
import {
|
||||
getRenderGovernorDiagnostics,
|
||||
governorRequestRender,
|
||||
FOLLOW_FRAME_RATE,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
} from '../renderGovernor.js';
|
||||
@@ -89,9 +89,8 @@ export function createApplicationTools({
|
||||
installGlobeInViewRecovery(viewer, {
|
||||
// The scope mask hides everything outside its keyhole.
|
||||
keyholeRadius: () => (isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0),
|
||||
// An authored scene frames its own shots, holds included, and the
|
||||
// opening starts with the globe as a speck.
|
||||
paused: () => sceneDirector.running || openingPlaying(),
|
||||
// An authored scene frames its own shots, holds included.
|
||||
paused: () => sceneDirector.running,
|
||||
}),
|
||||
);
|
||||
onSceneDirector?.(sceneDirector);
|
||||
@@ -275,7 +274,8 @@ 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');
|
||||
if (followed)
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
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):has(#intel-hud[data-variant='minimal'].active) #cesium-credits",
|
||||
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #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(#gev-omnibar):has(#command-dock > #gev-voice-control))';
|
||||
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(.has-omnibar.dock-has-voice *)';
|
||||
const OMNIBAR = Object.freeze({
|
||||
dock: `${OMNIBAR_SCOPE} #command-dock`,
|
||||
credit: `${OMNIBAR_SCOPE} :is(#cesium-credits, #gev-credits)`,
|
||||
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`,
|
||||
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`,
|
||||
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):has(#intel-hud[data-variant='minimal'].active) #cesium-credits";
|
||||
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #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\\):has\\( #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
|
||||
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):is\\( \\.hud-minimal-active \\*, #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,6 +10,7 @@ import { straightSegment } from './fixCurve.js';
|
||||
import {
|
||||
norm180,
|
||||
distance,
|
||||
distanceSquared,
|
||||
clone,
|
||||
copyInto,
|
||||
toDegrees,
|
||||
@@ -385,8 +386,32 @@ 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. */
|
||||
/** How far ahead (ms) a placed contact's segment runs before it is asked
|
||||
* again, in view and near the eye. */
|
||||
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) {
|
||||
@@ -465,6 +490,8 @@ 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 = () =>
|
||||
@@ -492,7 +519,8 @@ export function createAircraftIcons({
|
||||
const motionClock = (scene) =>
|
||||
scene
|
||||
? { kind: 'scene' }
|
||||
: { kind: 'live', delayMs: displayDelay.currentMs };
|
||||
: // The layer's pace asks for the frames its moving rows need.
|
||||
{ kind: 'live', delayMs: displayDelay.currentMs, frames: 'owner' };
|
||||
|
||||
/**
|
||||
* Once a frame: move the display delay on, and put the set's motion on
|
||||
@@ -815,12 +843,28 @@ 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 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.
|
||||
* 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.
|
||||
* @returns {boolean} False when there is no placement, the layer follows
|
||||
* the world clock, or it has no answer for this contact.
|
||||
*/
|
||||
@@ -839,7 +883,7 @@ export function createAircraftIcons({
|
||||
)
|
||||
return true;
|
||||
easeEnds.delete(icao24);
|
||||
const t1 = t + PLACED_PLAN_MS;
|
||||
const t1 = t + _placedPlanMs(icao24, from);
|
||||
const to = vec();
|
||||
const end = placeAt(icao24, t1 + leadMs, info, history, to);
|
||||
const motion = end
|
||||
@@ -903,12 +947,17 @@ 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) {
|
||||
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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -930,6 +979,7 @@ 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);
|
||||
@@ -952,10 +1002,13 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1043,6 +1096,7 @@ export function createAircraftIcons({
|
||||
if (!_aboveHorizon(position, occluder)) continue;
|
||||
if (inView && !inView(position)) continue;
|
||||
rotor.drawn = frame;
|
||||
rotorDrawnAtMs = nowMs;
|
||||
if (tracked) {
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
continue;
|
||||
@@ -1106,6 +1160,11 @@ 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), {
|
||||
@@ -1178,6 +1237,7 @@ export function createAircraftIcons({
|
||||
_fleetLook,
|
||||
_turnRotors,
|
||||
_rotorsTurning,
|
||||
_rotorDrawnAtMs,
|
||||
_addIcon,
|
||||
_forgetContact,
|
||||
_iconIds,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createAircraftIcons,
|
||||
createContactIcons,
|
||||
floorCoastArc,
|
||||
placedPlanSpread,
|
||||
} from './aircraftIconLayer.js';
|
||||
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
|
||||
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
|
||||
@@ -37,7 +38,11 @@ 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 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.equal(icons._displayMs(), Date.now() - 30_000);
|
||||
following = true;
|
||||
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
|
||||
@@ -45,7 +50,11 @@ 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 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
icons._disposeIcons();
|
||||
});
|
||||
|
||||
@@ -68,7 +77,11 @@ 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 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 30_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
// 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);
|
||||
@@ -76,7 +89,11 @@ 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 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 32_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
assert.equal(icons._displayMs(), Date.now() - 32_000);
|
||||
// Following the world clock: no delay, and it is not moved on meanwhile.
|
||||
following = true;
|
||||
@@ -87,7 +104,11 @@ 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 });
|
||||
assert.deepEqual(set.spec.motionClock, {
|
||||
kind: 'live',
|
||||
delayMs: 34_000,
|
||||
frames: 'owner',
|
||||
});
|
||||
icons._disposeIcons();
|
||||
});
|
||||
|
||||
@@ -481,3 +502,110 @@ test('back at live, a placed contact eases from where it is drawn over a recover
|
||||
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
|
||||
);
|
||||
});
|
||||
|
||||
/** A layer whose placement has every contact flying east from `at(id)`. */
|
||||
function placedFleet(ids, at) {
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(ids.map((id) => [id, [{ epochMs: WORLD_MS }]])),
|
||||
records: { data: new Map(ids.map((id) => [id, {}])) },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
placeAt: (id, wallMs, _info, _history, out) => {
|
||||
Object.assign(out, at(id, wallMs));
|
||||
return { courseDeg: 90, speedMps: 200 };
|
||||
},
|
||||
});
|
||||
for (const id of ids)
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: at(id, WORLD_MS),
|
||||
motion: { kind: 'hold', courseDeg: 90 },
|
||||
course: 90,
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: -Infinity },
|
||||
);
|
||||
return { icons, set: state._icons };
|
||||
}
|
||||
|
||||
test('a placed fleet planned in one pass runs out spread over the passes after it, not together', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const ids = Array.from({ length: 400 }, (_, i) =>
|
||||
(0xa00000 + i * 37).toString(16),
|
||||
);
|
||||
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`,
|
||||
);
|
||||
// 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`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a placed contact far from the eye or out of view is planned for longer than a near one in view', (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')}`);
|
||||
|
||||
// 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');
|
||||
},
|
||||
}),
|
||||
);
|
||||
icons._planIcon('f');
|
||||
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a throw ${length('f')}`);
|
||||
});
|
||||
@@ -14,6 +14,12 @@ 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';
|
||||
@@ -119,6 +125,70 @@ 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;
|
||||
|
||||
@@ -952,6 +1022,7 @@ export function createAircraftModels({
|
||||
}
|
||||
}
|
||||
state._icons?.flush();
|
||||
pace.set(_paceHz());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -970,7 +1041,14 @@ export function createAircraftModels({
|
||||
|
||||
if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts();
|
||||
parts.icons._syncImageSwitch();
|
||||
parts.icons._replanExpired(t);
|
||||
// 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,
|
||||
);
|
||||
const renderTime = parts.motion._displayTimeAt(
|
||||
t,
|
||||
state._scratchFleetRenderTime,
|
||||
@@ -1136,5 +1214,11 @@ export function createAircraftModels({
|
||||
_handBackDeselected,
|
||||
_updateTrackedModel,
|
||||
_fleetTick,
|
||||
_paceHz,
|
||||
_startPace: () => {
|
||||
paceReadMs = -Infinity;
|
||||
pace.start();
|
||||
},
|
||||
_stopPace: pace.stop,
|
||||
};
|
||||
}
|
||||
@@ -114,11 +114,14 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
|
||||
};
|
||||
let now = 1_000_000;
|
||||
let iconRecedeSyncs = 0;
|
||||
const replanViews = [];
|
||||
const parts = {
|
||||
icons: {
|
||||
_displayMs: () => now,
|
||||
_syncImageSwitch() {},
|
||||
_replanExpired() {},
|
||||
_replanExpired(_t, view) {
|
||||
replanViews.push(view);
|
||||
},
|
||||
_focusIcons() {},
|
||||
_occluder: () => null,
|
||||
_aboveHorizon: () => true,
|
||||
@@ -160,6 +163,9 @@ 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);
|
||||
@@ -476,3 +482,15 @@ 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);
|
||||
});
|
||||
@@ -64,7 +64,8 @@ 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 now). */
|
||||
/** 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). */
|
||||
const AGE_FIELD = 'ageHours';
|
||||
/** Spatial scope kinds `query()` accepts. */
|
||||
const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
@@ -582,6 +583,8 @@ 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(
|
||||
@@ -595,6 +598,7 @@ export async function selectAnalystRows(
|
||||
ref = null,
|
||||
inScope = null,
|
||||
now = Date.now(),
|
||||
recordsAt = null,
|
||||
isCurrent = () => true,
|
||||
distanceOf = null,
|
||||
} = {},
|
||||
@@ -603,8 +607,10 @@ 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(((now - t) / 3_600_000) * 10) / 10
|
||||
? Math.round(((ref - t) / 3_600_000) * 10) / 10
|
||||
: null;
|
||||
};
|
||||
const distance = (row) => {
|
||||
@@ -771,6 +777,7 @@ 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;
|
||||
@@ -786,6 +793,7 @@ 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) || {};
|
||||
@@ -1048,6 +1056,7 @@ export function createAnalystEngine(providers) {
|
||||
: null,
|
||||
inScope,
|
||||
now: providers.now?.() ?? Date.now(),
|
||||
recordsAt,
|
||||
isCurrent,
|
||||
});
|
||||
if (!selection || !isCurrent()) return cancelled();
|
||||
@@ -1147,6 +1156,7 @@ 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,6 +896,24 @@ 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,6 +34,7 @@ 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,
|
||||
@@ -448,31 +449,34 @@ 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 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.)
|
||||
// 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.)
|
||||
//
|
||||
// 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
|
||||
// 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
|
||||
// promptness goes with them, silently. This test is where that shows up.
|
||||
test('aircraft brackets stay prompt because the aircraft layers hold the render loop', async () => {
|
||||
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');
|
||||
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,
|
||||
/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',
|
||||
/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',
|
||||
);
|
||||
assert.match(
|
||||
source,
|
||||
/releaseContinuousRender\('(flights|military)'\)/,
|
||||
`${file}: and the hold must be released, or the governor can never idle`,
|
||||
/parts\.rendering\._stopPace\(\)/,
|
||||
`${file}: and the pace must be stopped, or the governor can never idle`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -57,6 +57,34 @@ 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 = [];
|
||||
|
||||
@@ -1,776 +0,0 @@
|
||||
// Generated by scripts/build-home-countries.mjs. Do not edit by hand.
|
||||
// Sources: tzdata zone.tab and tzdata.zi (public domain) and the Natural
|
||||
// Earth countries pack in src/data/local_data/natural_earth (public domain).
|
||||
|
||||
/** ISO 3166 country → [lat, lon]: in its largest part, else its first zone's place. */
|
||||
export const COUNTRY_CENTRES = {
|
||||
AD: [42.5, 1.6],
|
||||
AE: [23.9, 54.3],
|
||||
AF: [33.8, 66],
|
||||
AG: [17.1, -61.8],
|
||||
AI: [18.2, -63.1],
|
||||
AL: [41.1, 20.1],
|
||||
AM: [40.3, 44.9],
|
||||
AO: [-12.3, 17.6],
|
||||
AQ: [-80.6, 20.8],
|
||||
AR: [-35.2, -65.1],
|
||||
AS: [-14.3, -170.7],
|
||||
AT: [47.6, 14.1],
|
||||
AU: [-25.6, 134.4],
|
||||
AW: [12.5, -70],
|
||||
AX: [60.2, 19.9],
|
||||
AZ: [40.3, 47.7],
|
||||
BA: [44.2, 17.8],
|
||||
BB: [13.2, -59.6],
|
||||
BD: [23.9, 90.2],
|
||||
BE: [50.6, 4.6],
|
||||
BF: [12.3, -1.8],
|
||||
BG: [42.8, 25.2],
|
||||
BH: [26.1, 50.5],
|
||||
BI: [-3.4, 29.9],
|
||||
BJ: [9.6, 2.3],
|
||||
BL: [17.9, -62.8],
|
||||
BM: [32.3, -64.8],
|
||||
BN: [4.5, 114.6],
|
||||
BO: [-16.7, -64.7],
|
||||
BQ: [12.2, -68.3],
|
||||
BR: [-10.8, -53.1],
|
||||
BS: [24.7, -78],
|
||||
BT: [27.4, 90.4],
|
||||
BW: [-22.2, 23.8],
|
||||
BY: [53.5, 28],
|
||||
BZ: [17.2, -88.7],
|
||||
CA: [57.9, -102.4],
|
||||
CC: [-12.2, 96.9],
|
||||
CD: [-2.9, 23.6],
|
||||
CF: [6.6, 20.5],
|
||||
CG: [-0.8, 15.2],
|
||||
CH: [46.8, 8.2],
|
||||
CI: [7.6, -5.6],
|
||||
CK: [-21.2, -159.8],
|
||||
CL: [-35.4, -71.2],
|
||||
CM: [5.7, 12.7],
|
||||
CN: [36.6, 103.8],
|
||||
CO: [3.9, -73.1],
|
||||
CR: [10, -84.2],
|
||||
CU: [21.6, -79],
|
||||
CV: [15.1, -23.6],
|
||||
CW: [12.2, -69],
|
||||
CX: [-10.4, 105.7],
|
||||
CY: [34.9, 33],
|
||||
CZ: [49.7, 15.3],
|
||||
DE: [51.1, 10.4],
|
||||
DJ: [11.8, 42.6],
|
||||
DK: [56.2, 9.4],
|
||||
DM: [15.4, -61.4],
|
||||
DO: [18.9, -70.5],
|
||||
DZ: [28.1, 2.7],
|
||||
EC: [-1.4, -78.4],
|
||||
EE: [58.7, 25.8],
|
||||
EG: [26.5, 29.9],
|
||||
EH: [24.2, -12.2],
|
||||
ER: [15.4, 38.8],
|
||||
ES: [40.4, -3.6],
|
||||
ET: [8.6, 39.6],
|
||||
FI: [64.5, 26.3],
|
||||
FJ: [-17.8, 178],
|
||||
FK: [-51.7, -58.8],
|
||||
FM: [6.9, 158.2],
|
||||
FO: [62.1, -7],
|
||||
FR: [46.6, 2.5],
|
||||
GA: [-0.6, 11.8],
|
||||
GB: [53.9, -2.5],
|
||||
GD: [12.1, -61.7],
|
||||
GE: [42.2, 43.5],
|
||||
GF: [4.9, -52.3],
|
||||
GG: [49.5, -2.6],
|
||||
GH: [8, -1.2],
|
||||
GI: [36.1, -5.3],
|
||||
GL: [74.8, -41.4],
|
||||
GM: [13.4, -15.4],
|
||||
GN: [10.4, -10.9],
|
||||
GP: [16.2, -61.5],
|
||||
GQ: [1.6, 10.5],
|
||||
GR: [39.5, 22.6],
|
||||
GS: [-54.4, -36.7],
|
||||
GT: [15.7, -90.4],
|
||||
GU: [13.4, 144.8],
|
||||
GW: [12.1, -14.9],
|
||||
GY: [4.8, -59],
|
||||
HK: [22.4, 114.2],
|
||||
HN: [14.8, -86.6],
|
||||
HR: [45.2, 16.4],
|
||||
HT: [18.9, -72.7],
|
||||
HU: [47.2, 19.4],
|
||||
ID: [-0.2, 114],
|
||||
IE: [53.2, -8.1],
|
||||
IL: [31.4, 34.7],
|
||||
IM: [54.2, -4.5],
|
||||
IN: [22.9, 79.6],
|
||||
IO: [-7.3, 72.4],
|
||||
IQ: [33, 43.7],
|
||||
IR: [32.6, 54.3],
|
||||
IS: [65, -18.6],
|
||||
IT: [43.5, 12.2],
|
||||
JE: [49.2, -2.1],
|
||||
JM: [18.2, -77.3],
|
||||
JO: [31.2, 36.8],
|
||||
JP: [36.7, 138],
|
||||
KE: [0.6, 37.8],
|
||||
KG: [41.5, 74.5],
|
||||
KH: [12.7, 104.9],
|
||||
KI: [1.9, -157.4],
|
||||
KM: [-11.7, 43.3],
|
||||
KN: [17.3, -62.8],
|
||||
KP: [40.2, 127.2],
|
||||
KR: [36.5, 127.9],
|
||||
KW: [29.3, 47.6],
|
||||
KY: [19.3, -81.3],
|
||||
KZ: [48.2, 67.3],
|
||||
LA: [18.5, 103.7],
|
||||
LB: [33.9, 35.9],
|
||||
LC: [13.9, -61],
|
||||
LI: [47.1, 9.5],
|
||||
LK: [7.6, 80.7],
|
||||
LR: [6.5, -9.3],
|
||||
LS: [-29.6, 28.2],
|
||||
LT: [55.3, 23.9],
|
||||
LU: [49.8, 6.1],
|
||||
LV: [56.9, 24.9],
|
||||
LY: [27, 18],
|
||||
MA: [29.8, -8.4],
|
||||
MC: [43.7, 7.4],
|
||||
MD: [47.2, 28.5],
|
||||
ME: [42.8, 19.2],
|
||||
MF: [18.1, -63.1],
|
||||
MG: [-19.4, 46.7],
|
||||
MH: [7.1, 171.2],
|
||||
MK: [41.6, 21.7],
|
||||
ML: [17.3, -3.5],
|
||||
MM: [21.2, 96.5],
|
||||
MN: [46.8, 103.1],
|
||||
MO: [22.1, 113.6],
|
||||
MP: [15.2, 145.7],
|
||||
MQ: [14.6, -61.1],
|
||||
MR: [20.3, -10.3],
|
||||
MS: [16.7, -62.2],
|
||||
MT: [35.9, 14.4],
|
||||
MU: [-20.3, 57.6],
|
||||
MV: [4.2, 73.5],
|
||||
MW: [-13.2, 34.3],
|
||||
MX: [23.9, -102.5],
|
||||
MY: [3.6, 114.7],
|
||||
MZ: [-17.3, 35.5],
|
||||
NA: [-22.1, 17.2],
|
||||
NC: [-21.3, 165.5],
|
||||
NE: [17.4, 9.4],
|
||||
NF: [-29, 168],
|
||||
NG: [9.6, 8.1],
|
||||
NI: [12.8, -85],
|
||||
NL: [52.3, 5.6],
|
||||
NO: [64.2, 14],
|
||||
NP: [28.2, 83.9],
|
||||
NR: [-0.5, 166.9],
|
||||
NU: [-19, -169.9],
|
||||
NZ: [-44, 170.5],
|
||||
OM: [20.6, 56.1],
|
||||
PA: [8.5, -80.1],
|
||||
PE: [-9.2, -74.4],
|
||||
PF: [-17.7, -149.4],
|
||||
PG: [-6.6, 144.3],
|
||||
PH: [16, 121.4],
|
||||
PK: [29.9, 69.3],
|
||||
PL: [52.1, 19.4],
|
||||
PM: [47, -56.3],
|
||||
PN: [-24.4, -128.3],
|
||||
PR: [18.2, -66.5],
|
||||
PS: [31.9, 35.3],
|
||||
PT: [39.7, -8],
|
||||
PW: [7.5, 134.6],
|
||||
PY: [-23.2, -58.4],
|
||||
QA: [25.3, 51.2],
|
||||
RE: [-20.9, 55.5],
|
||||
RO: [45.9, 25],
|
||||
RS: [44.2, 20.8],
|
||||
RU: [61.7, 99.1],
|
||||
RW: [-2, 29.9],
|
||||
SA: [24.1, 44.5],
|
||||
SB: [-9.6, 160.2],
|
||||
SC: [-4.7, 55.5],
|
||||
SD: [16, 29.9],
|
||||
SE: [62.8, 16.7],
|
||||
SG: [1.4, 103.8],
|
||||
SH: [-16, -5.7],
|
||||
SI: [46.1, 14.8],
|
||||
SJ: [78, 16],
|
||||
SK: [48.7, 19.5],
|
||||
SL: [8.6, -11.8],
|
||||
SM: [43.9, 12.4],
|
||||
SN: [14.4, -14.5],
|
||||
SO: [4.8, 45.7],
|
||||
SR: [4.1, -55.9],
|
||||
SS: [7.3, 30.3],
|
||||
ST: [0.2, 6.6],
|
||||
SV: [13.7, -88.9],
|
||||
SX: [18, -63.1],
|
||||
SY: [35, 38.5],
|
||||
SZ: [-26.6, 31.5],
|
||||
TC: [21.8, -71.7],
|
||||
TD: [15.3, 18.6],
|
||||
TF: [-49.3, 69.5],
|
||||
TG: [8.5, 1],
|
||||
TH: [15.1, 101],
|
||||
TJ: [38.5, 71],
|
||||
TK: [-9.4, -171.2],
|
||||
TL: [-8.8, 125.9],
|
||||
TM: [39.1, 59.4],
|
||||
TN: [34.1, 9.5],
|
||||
TO: [-21.2, -175.2],
|
||||
TR: [39, 35.4],
|
||||
TT: [10.4, -61.3],
|
||||
TV: [-8.5, 179.2],
|
||||
TW: [23.8, 121],
|
||||
TZ: [-6.3, 34.8],
|
||||
UA: [49.2, 31.3],
|
||||
UG: [1.3, 32.4],
|
||||
UM: [5.9, -162.1],
|
||||
US: [39.5, -99.1],
|
||||
UY: [-32.8, -56],
|
||||
UZ: [41.8, 63.1],
|
||||
VA: [41.9, 12.5],
|
||||
VC: [13.3, -61.2],
|
||||
VE: [7.1, -66.2],
|
||||
VG: [18.4, -64.6],
|
||||
VI: [17.7, -64.8],
|
||||
VN: [16, 107.9],
|
||||
VU: [-15.2, 166.9],
|
||||
WF: [-13.3, -176.2],
|
||||
WS: [-13.6, -172.4],
|
||||
YE: [15.9, 47.5],
|
||||
YT: [-12.8, 45.2],
|
||||
ZA: [-29, 25.2],
|
||||
ZM: [-13.5, 27.8],
|
||||
ZW: [-19, 29.9],
|
||||
};
|
||||
|
||||
/** Time zone (tzdata, ICU and older names) → ISO 3166 country. */
|
||||
export const ZONE_COUNTRIES = {
|
||||
'Africa/Abidjan': 'CI',
|
||||
'Africa/Accra': 'GH',
|
||||
'Africa/Addis_Ababa': 'ET',
|
||||
'Africa/Algiers': 'DZ',
|
||||
'Africa/Asmara': 'ER',
|
||||
'Africa/Asmera': 'ER',
|
||||
'Africa/Bamako': 'ML',
|
||||
'Africa/Bangui': 'CF',
|
||||
'Africa/Banjul': 'GM',
|
||||
'Africa/Bissau': 'GW',
|
||||
'Africa/Blantyre': 'MW',
|
||||
'Africa/Brazzaville': 'CG',
|
||||
'Africa/Bujumbura': 'BI',
|
||||
'Africa/Cairo': 'EG',
|
||||
'Africa/Casablanca': 'MA',
|
||||
'Africa/Ceuta': 'ES',
|
||||
'Africa/Conakry': 'GN',
|
||||
'Africa/Dakar': 'SN',
|
||||
'Africa/Dar_es_Salaam': 'TZ',
|
||||
'Africa/Djibouti': 'DJ',
|
||||
'Africa/Douala': 'CM',
|
||||
'Africa/El_Aaiun': 'EH',
|
||||
'Africa/Freetown': 'SL',
|
||||
'Africa/Gaborone': 'BW',
|
||||
'Africa/Harare': 'ZW',
|
||||
'Africa/Johannesburg': 'ZA',
|
||||
'Africa/Juba': 'SS',
|
||||
'Africa/Kampala': 'UG',
|
||||
'Africa/Khartoum': 'SD',
|
||||
'Africa/Kigali': 'RW',
|
||||
'Africa/Kinshasa': 'CD',
|
||||
'Africa/Lagos': 'NG',
|
||||
'Africa/Libreville': 'GA',
|
||||
'Africa/Lome': 'TG',
|
||||
'Africa/Luanda': 'AO',
|
||||
'Africa/Lubumbashi': 'CD',
|
||||
'Africa/Lusaka': 'ZM',
|
||||
'Africa/Malabo': 'GQ',
|
||||
'Africa/Maputo': 'MZ',
|
||||
'Africa/Maseru': 'LS',
|
||||
'Africa/Mbabane': 'SZ',
|
||||
'Africa/Mogadishu': 'SO',
|
||||
'Africa/Monrovia': 'LR',
|
||||
'Africa/Nairobi': 'KE',
|
||||
'Africa/Ndjamena': 'TD',
|
||||
'Africa/Niamey': 'NE',
|
||||
'Africa/Nouakchott': 'MR',
|
||||
'Africa/Ouagadougou': 'BF',
|
||||
'Africa/Porto-Novo': 'BJ',
|
||||
'Africa/Sao_Tome': 'ST',
|
||||
'Africa/Timbuktu': 'ML',
|
||||
'Africa/Tripoli': 'LY',
|
||||
'Africa/Tunis': 'TN',
|
||||
'Africa/Windhoek': 'NA',
|
||||
'America/Adak': 'US',
|
||||
'America/Anchorage': 'US',
|
||||
'America/Anguilla': 'AI',
|
||||
'America/Antigua': 'AG',
|
||||
'America/Araguaina': 'BR',
|
||||
'America/Argentina/Buenos_Aires': 'AR',
|
||||
'America/Argentina/Catamarca': 'AR',
|
||||
'America/Argentina/ComodRivadavia': 'AR',
|
||||
'America/Argentina/Cordoba': 'AR',
|
||||
'America/Argentina/Jujuy': 'AR',
|
||||
'America/Argentina/La_Rioja': 'AR',
|
||||
'America/Argentina/Mendoza': 'AR',
|
||||
'America/Argentina/Rio_Gallegos': 'AR',
|
||||
'America/Argentina/Salta': 'AR',
|
||||
'America/Argentina/San_Juan': 'AR',
|
||||
'America/Argentina/San_Luis': 'AR',
|
||||
'America/Argentina/Tucuman': 'AR',
|
||||
'America/Argentina/Ushuaia': 'AR',
|
||||
'America/Aruba': 'AW',
|
||||
'America/Asuncion': 'PY',
|
||||
'America/Atikokan': 'CA',
|
||||
'America/Atka': 'US',
|
||||
'America/Bahia': 'BR',
|
||||
'America/Bahia_Banderas': 'MX',
|
||||
'America/Barbados': 'BB',
|
||||
'America/Belem': 'BR',
|
||||
'America/Belize': 'BZ',
|
||||
'America/Blanc-Sablon': 'CA',
|
||||
'America/Boa_Vista': 'BR',
|
||||
'America/Bogota': 'CO',
|
||||
'America/Boise': 'US',
|
||||
'America/Buenos_Aires': 'AR',
|
||||
'America/Cambridge_Bay': 'CA',
|
||||
'America/Campo_Grande': 'BR',
|
||||
'America/Cancun': 'MX',
|
||||
'America/Caracas': 'VE',
|
||||
'America/Catamarca': 'AR',
|
||||
'America/Cayenne': 'GF',
|
||||
'America/Cayman': 'KY',
|
||||
'America/Chicago': 'US',
|
||||
'America/Chihuahua': 'MX',
|
||||
'America/Ciudad_Juarez': 'MX',
|
||||
'America/Coral_Harbour': 'CA',
|
||||
'America/Cordoba': 'AR',
|
||||
'America/Costa_Rica': 'CR',
|
||||
'America/Coyhaique': 'CL',
|
||||
'America/Creston': 'CA',
|
||||
'America/Cuiaba': 'BR',
|
||||
'America/Curacao': 'CW',
|
||||
'America/Danmarkshavn': 'GL',
|
||||
'America/Dawson': 'CA',
|
||||
'America/Dawson_Creek': 'CA',
|
||||
'America/Denver': 'US',
|
||||
'America/Detroit': 'US',
|
||||
'America/Dominica': 'DM',
|
||||
'America/Edmonton': 'CA',
|
||||
'America/Eirunepe': 'BR',
|
||||
'America/El_Salvador': 'SV',
|
||||
'America/Ensenada': 'MX',
|
||||
'America/Fort_Nelson': 'CA',
|
||||
'America/Fort_Wayne': 'US',
|
||||
'America/Fortaleza': 'BR',
|
||||
'America/Glace_Bay': 'CA',
|
||||
'America/Godthab': 'GL',
|
||||
'America/Goose_Bay': 'CA',
|
||||
'America/Grand_Turk': 'TC',
|
||||
'America/Grenada': 'GD',
|
||||
'America/Guadeloupe': 'GP',
|
||||
'America/Guatemala': 'GT',
|
||||
'America/Guayaquil': 'EC',
|
||||
'America/Guyana': 'GY',
|
||||
'America/Halifax': 'CA',
|
||||
'America/Havana': 'CU',
|
||||
'America/Hermosillo': 'MX',
|
||||
'America/Indiana/Indianapolis': 'US',
|
||||
'America/Indiana/Knox': 'US',
|
||||
'America/Indiana/Marengo': 'US',
|
||||
'America/Indiana/Petersburg': 'US',
|
||||
'America/Indiana/Tell_City': 'US',
|
||||
'America/Indiana/Vevay': 'US',
|
||||
'America/Indiana/Vincennes': 'US',
|
||||
'America/Indiana/Winamac': 'US',
|
||||
'America/Indianapolis': 'US',
|
||||
'America/Inuvik': 'CA',
|
||||
'America/Iqaluit': 'CA',
|
||||
'America/Jamaica': 'JM',
|
||||
'America/Jujuy': 'AR',
|
||||
'America/Juneau': 'US',
|
||||
'America/Kentucky/Louisville': 'US',
|
||||
'America/Kentucky/Monticello': 'US',
|
||||
'America/Knox_IN': 'US',
|
||||
'America/Kralendijk': 'BQ',
|
||||
'America/La_Paz': 'BO',
|
||||
'America/Lima': 'PE',
|
||||
'America/Los_Angeles': 'US',
|
||||
'America/Louisville': 'US',
|
||||
'America/Lower_Princes': 'SX',
|
||||
'America/Maceio': 'BR',
|
||||
'America/Managua': 'NI',
|
||||
'America/Manaus': 'BR',
|
||||
'America/Marigot': 'MF',
|
||||
'America/Martinique': 'MQ',
|
||||
'America/Matamoros': 'MX',
|
||||
'America/Mazatlan': 'MX',
|
||||
'America/Mendoza': 'AR',
|
||||
'America/Menominee': 'US',
|
||||
'America/Merida': 'MX',
|
||||
'America/Metlakatla': 'US',
|
||||
'America/Mexico_City': 'MX',
|
||||
'America/Miquelon': 'PM',
|
||||
'America/Moncton': 'CA',
|
||||
'America/Monterrey': 'MX',
|
||||
'America/Montevideo': 'UY',
|
||||
'America/Montreal': 'CA',
|
||||
'America/Montserrat': 'MS',
|
||||
'America/Nassau': 'BS',
|
||||
'America/New_York': 'US',
|
||||
'America/Nipigon': 'CA',
|
||||
'America/Nome': 'US',
|
||||
'America/Noronha': 'BR',
|
||||
'America/North_Dakota/Beulah': 'US',
|
||||
'America/North_Dakota/Center': 'US',
|
||||
'America/North_Dakota/New_Salem': 'US',
|
||||
'America/Nuuk': 'GL',
|
||||
'America/Ojinaga': 'MX',
|
||||
'America/Panama': 'PA',
|
||||
'America/Pangnirtung': 'CA',
|
||||
'America/Paramaribo': 'SR',
|
||||
'America/Phoenix': 'US',
|
||||
'America/Port-au-Prince': 'HT',
|
||||
'America/Port_of_Spain': 'TT',
|
||||
'America/Porto_Acre': 'BR',
|
||||
'America/Porto_Velho': 'BR',
|
||||
'America/Puerto_Rico': 'PR',
|
||||
'America/Punta_Arenas': 'CL',
|
||||
'America/Rainy_River': 'CA',
|
||||
'America/Rankin_Inlet': 'CA',
|
||||
'America/Recife': 'BR',
|
||||
'America/Regina': 'CA',
|
||||
'America/Resolute': 'CA',
|
||||
'America/Rio_Branco': 'BR',
|
||||
'America/Rosario': 'AR',
|
||||
'America/Santa_Isabel': 'MX',
|
||||
'America/Santarem': 'BR',
|
||||
'America/Santiago': 'CL',
|
||||
'America/Santo_Domingo': 'DO',
|
||||
'America/Sao_Paulo': 'BR',
|
||||
'America/Scoresbysund': 'GL',
|
||||
'America/Shiprock': 'US',
|
||||
'America/Sitka': 'US',
|
||||
'America/St_Barthelemy': 'BL',
|
||||
'America/St_Johns': 'CA',
|
||||
'America/St_Kitts': 'KN',
|
||||
'America/St_Lucia': 'LC',
|
||||
'America/St_Thomas': 'VI',
|
||||
'America/St_Vincent': 'VC',
|
||||
'America/Swift_Current': 'CA',
|
||||
'America/Tegucigalpa': 'HN',
|
||||
'America/Thule': 'GL',
|
||||
'America/Thunder_Bay': 'CA',
|
||||
'America/Tijuana': 'MX',
|
||||
'America/Toronto': 'CA',
|
||||
'America/Tortola': 'VG',
|
||||
'America/Vancouver': 'CA',
|
||||
'America/Virgin': 'VI',
|
||||
'America/Whitehorse': 'CA',
|
||||
'America/Winnipeg': 'CA',
|
||||
'America/Yakutat': 'US',
|
||||
'America/Yellowknife': 'CA',
|
||||
'Antarctica/Casey': 'AQ',
|
||||
'Antarctica/Davis': 'AQ',
|
||||
'Antarctica/DumontDUrville': 'AQ',
|
||||
'Antarctica/Macquarie': 'AU',
|
||||
'Antarctica/Mawson': 'AQ',
|
||||
'Antarctica/McMurdo': 'AQ',
|
||||
'Antarctica/Palmer': 'AQ',
|
||||
'Antarctica/Rothera': 'AQ',
|
||||
'Antarctica/South_Pole': 'AQ',
|
||||
'Antarctica/Syowa': 'AQ',
|
||||
'Antarctica/Troll': 'AQ',
|
||||
'Antarctica/Vostok': 'AQ',
|
||||
'Arctic/Longyearbyen': 'SJ',
|
||||
'Asia/Aden': 'YE',
|
||||
'Asia/Almaty': 'KZ',
|
||||
'Asia/Amman': 'JO',
|
||||
'Asia/Anadyr': 'RU',
|
||||
'Asia/Aqtau': 'KZ',
|
||||
'Asia/Aqtobe': 'KZ',
|
||||
'Asia/Ashgabat': 'TM',
|
||||
'Asia/Ashkhabad': 'TM',
|
||||
'Asia/Atyrau': 'KZ',
|
||||
'Asia/Baghdad': 'IQ',
|
||||
'Asia/Bahrain': 'BH',
|
||||
'Asia/Baku': 'AZ',
|
||||
'Asia/Bangkok': 'TH',
|
||||
'Asia/Barnaul': 'RU',
|
||||
'Asia/Beirut': 'LB',
|
||||
'Asia/Bishkek': 'KG',
|
||||
'Asia/Brunei': 'BN',
|
||||
'Asia/Calcutta': 'IN',
|
||||
'Asia/Chita': 'RU',
|
||||
'Asia/Choibalsan': 'MN',
|
||||
'Asia/Chongqing': 'CN',
|
||||
'Asia/Chungking': 'CN',
|
||||
'Asia/Colombo': 'LK',
|
||||
'Asia/Dacca': 'BD',
|
||||
'Asia/Damascus': 'SY',
|
||||
'Asia/Dhaka': 'BD',
|
||||
'Asia/Dili': 'TL',
|
||||
'Asia/Dubai': 'AE',
|
||||
'Asia/Dushanbe': 'TJ',
|
||||
'Asia/Famagusta': 'CY',
|
||||
'Asia/Gaza': 'PS',
|
||||
'Asia/Harbin': 'CN',
|
||||
'Asia/Hebron': 'PS',
|
||||
'Asia/Ho_Chi_Minh': 'VN',
|
||||
'Asia/Hong_Kong': 'HK',
|
||||
'Asia/Hovd': 'MN',
|
||||
'Asia/Irkutsk': 'RU',
|
||||
'Asia/Istanbul': 'TR',
|
||||
'Asia/Jakarta': 'ID',
|
||||
'Asia/Jayapura': 'ID',
|
||||
'Asia/Jerusalem': 'IL',
|
||||
'Asia/Kabul': 'AF',
|
||||
'Asia/Kamchatka': 'RU',
|
||||
'Asia/Karachi': 'PK',
|
||||
'Asia/Kashgar': 'CN',
|
||||
'Asia/Kathmandu': 'NP',
|
||||
'Asia/Katmandu': 'NP',
|
||||
'Asia/Khandyga': 'RU',
|
||||
'Asia/Kolkata': 'IN',
|
||||
'Asia/Krasnoyarsk': 'RU',
|
||||
'Asia/Kuala_Lumpur': 'MY',
|
||||
'Asia/Kuching': 'MY',
|
||||
'Asia/Kuwait': 'KW',
|
||||
'Asia/Macao': 'MO',
|
||||
'Asia/Macau': 'MO',
|
||||
'Asia/Magadan': 'RU',
|
||||
'Asia/Makassar': 'ID',
|
||||
'Asia/Manila': 'PH',
|
||||
'Asia/Muscat': 'OM',
|
||||
'Asia/Nicosia': 'CY',
|
||||
'Asia/Novokuznetsk': 'RU',
|
||||
'Asia/Novosibirsk': 'RU',
|
||||
'Asia/Omsk': 'RU',
|
||||
'Asia/Oral': 'KZ',
|
||||
'Asia/Phnom_Penh': 'KH',
|
||||
'Asia/Pontianak': 'ID',
|
||||
'Asia/Pyongyang': 'KP',
|
||||
'Asia/Qatar': 'QA',
|
||||
'Asia/Qostanay': 'KZ',
|
||||
'Asia/Qyzylorda': 'KZ',
|
||||
'Asia/Rangoon': 'MM',
|
||||
'Asia/Riyadh': 'SA',
|
||||
'Asia/Saigon': 'VN',
|
||||
'Asia/Sakhalin': 'RU',
|
||||
'Asia/Samarkand': 'UZ',
|
||||
'Asia/Seoul': 'KR',
|
||||
'Asia/Shanghai': 'CN',
|
||||
'Asia/Singapore': 'SG',
|
||||
'Asia/Srednekolymsk': 'RU',
|
||||
'Asia/Taipei': 'TW',
|
||||
'Asia/Tashkent': 'UZ',
|
||||
'Asia/Tbilisi': 'GE',
|
||||
'Asia/Tehran': 'IR',
|
||||
'Asia/Tel_Aviv': 'IL',
|
||||
'Asia/Thimbu': 'BT',
|
||||
'Asia/Thimphu': 'BT',
|
||||
'Asia/Tokyo': 'JP',
|
||||
'Asia/Tomsk': 'RU',
|
||||
'Asia/Ujung_Pandang': 'ID',
|
||||
'Asia/Ulaanbaatar': 'MN',
|
||||
'Asia/Ulan_Bator': 'MN',
|
||||
'Asia/Urumqi': 'CN',
|
||||
'Asia/Ust-Nera': 'RU',
|
||||
'Asia/Vientiane': 'LA',
|
||||
'Asia/Vladivostok': 'RU',
|
||||
'Asia/Yakutsk': 'RU',
|
||||
'Asia/Yangon': 'MM',
|
||||
'Asia/Yekaterinburg': 'RU',
|
||||
'Asia/Yerevan': 'AM',
|
||||
'Atlantic/Azores': 'PT',
|
||||
'Atlantic/Bermuda': 'BM',
|
||||
'Atlantic/Canary': 'ES',
|
||||
'Atlantic/Cape_Verde': 'CV',
|
||||
'Atlantic/Faeroe': 'FO',
|
||||
'Atlantic/Faroe': 'FO',
|
||||
'Atlantic/Jan_Mayen': 'SJ',
|
||||
'Atlantic/Madeira': 'PT',
|
||||
'Atlantic/Reykjavik': 'IS',
|
||||
'Atlantic/South_Georgia': 'GS',
|
||||
'Atlantic/St_Helena': 'SH',
|
||||
'Atlantic/Stanley': 'FK',
|
||||
'Australia/ACT': 'AU',
|
||||
'Australia/Adelaide': 'AU',
|
||||
'Australia/Brisbane': 'AU',
|
||||
'Australia/Broken_Hill': 'AU',
|
||||
'Australia/Canberra': 'AU',
|
||||
'Australia/Currie': 'AU',
|
||||
'Australia/Darwin': 'AU',
|
||||
'Australia/Eucla': 'AU',
|
||||
'Australia/Hobart': 'AU',
|
||||
'Australia/LHI': 'AU',
|
||||
'Australia/Lindeman': 'AU',
|
||||
'Australia/Lord_Howe': 'AU',
|
||||
'Australia/Melbourne': 'AU',
|
||||
'Australia/NSW': 'AU',
|
||||
'Australia/North': 'AU',
|
||||
'Australia/Perth': 'AU',
|
||||
'Australia/Queensland': 'AU',
|
||||
'Australia/South': 'AU',
|
||||
'Australia/Sydney': 'AU',
|
||||
'Australia/Tasmania': 'AU',
|
||||
'Australia/Victoria': 'AU',
|
||||
'Australia/West': 'AU',
|
||||
'Australia/Yancowinna': 'AU',
|
||||
'Brazil/Acre': 'BR',
|
||||
'Brazil/DeNoronha': 'BR',
|
||||
'Brazil/East': 'BR',
|
||||
'Brazil/West': 'BR',
|
||||
'Canada/Atlantic': 'CA',
|
||||
'Canada/Central': 'CA',
|
||||
'Canada/Eastern': 'CA',
|
||||
'Canada/Mountain': 'CA',
|
||||
'Canada/Newfoundland': 'CA',
|
||||
'Canada/Pacific': 'CA',
|
||||
'Canada/Saskatchewan': 'CA',
|
||||
'Canada/Yukon': 'CA',
|
||||
'Chile/Continental': 'CL',
|
||||
'Chile/EasterIsland': 'CL',
|
||||
'Europe/Amsterdam': 'NL',
|
||||
'Europe/Andorra': 'AD',
|
||||
'Europe/Astrakhan': 'RU',
|
||||
'Europe/Athens': 'GR',
|
||||
'Europe/Belfast': 'GB',
|
||||
'Europe/Belgrade': 'RS',
|
||||
'Europe/Berlin': 'DE',
|
||||
'Europe/Bratislava': 'SK',
|
||||
'Europe/Brussels': 'BE',
|
||||
'Europe/Bucharest': 'RO',
|
||||
'Europe/Budapest': 'HU',
|
||||
'Europe/Busingen': 'DE',
|
||||
'Europe/Chisinau': 'MD',
|
||||
'Europe/Copenhagen': 'DK',
|
||||
'Europe/Dublin': 'IE',
|
||||
'Europe/Gibraltar': 'GI',
|
||||
'Europe/Guernsey': 'GG',
|
||||
'Europe/Helsinki': 'FI',
|
||||
'Europe/Isle_of_Man': 'IM',
|
||||
'Europe/Istanbul': 'TR',
|
||||
'Europe/Jersey': 'JE',
|
||||
'Europe/Kaliningrad': 'RU',
|
||||
'Europe/Kiev': 'UA',
|
||||
'Europe/Kirov': 'RU',
|
||||
'Europe/Kyiv': 'UA',
|
||||
'Europe/Lisbon': 'PT',
|
||||
'Europe/Ljubljana': 'SI',
|
||||
'Europe/London': 'GB',
|
||||
'Europe/Luxembourg': 'LU',
|
||||
'Europe/Madrid': 'ES',
|
||||
'Europe/Malta': 'MT',
|
||||
'Europe/Mariehamn': 'AX',
|
||||
'Europe/Minsk': 'BY',
|
||||
'Europe/Monaco': 'MC',
|
||||
'Europe/Moscow': 'RU',
|
||||
'Europe/Nicosia': 'CY',
|
||||
'Europe/Oslo': 'NO',
|
||||
'Europe/Paris': 'FR',
|
||||
'Europe/Podgorica': 'ME',
|
||||
'Europe/Prague': 'CZ',
|
||||
'Europe/Riga': 'LV',
|
||||
'Europe/Rome': 'IT',
|
||||
'Europe/Samara': 'RU',
|
||||
'Europe/San_Marino': 'SM',
|
||||
'Europe/Sarajevo': 'BA',
|
||||
'Europe/Saratov': 'RU',
|
||||
'Europe/Simferopol': 'UA',
|
||||
'Europe/Skopje': 'MK',
|
||||
'Europe/Sofia': 'BG',
|
||||
'Europe/Stockholm': 'SE',
|
||||
'Europe/Tallinn': 'EE',
|
||||
'Europe/Tirane': 'AL',
|
||||
'Europe/Tiraspol': 'MD',
|
||||
'Europe/Ulyanovsk': 'RU',
|
||||
'Europe/Uzhgorod': 'UA',
|
||||
'Europe/Vaduz': 'LI',
|
||||
'Europe/Vatican': 'VA',
|
||||
'Europe/Vienna': 'AT',
|
||||
'Europe/Vilnius': 'LT',
|
||||
'Europe/Volgograd': 'RU',
|
||||
'Europe/Warsaw': 'PL',
|
||||
'Europe/Zagreb': 'HR',
|
||||
'Europe/Zaporozhye': 'UA',
|
||||
'Europe/Zurich': 'CH',
|
||||
'Indian/Antananarivo': 'MG',
|
||||
'Indian/Chagos': 'IO',
|
||||
'Indian/Christmas': 'CX',
|
||||
'Indian/Cocos': 'CC',
|
||||
'Indian/Comoro': 'KM',
|
||||
'Indian/Kerguelen': 'TF',
|
||||
'Indian/Mahe': 'SC',
|
||||
'Indian/Maldives': 'MV',
|
||||
'Indian/Mauritius': 'MU',
|
||||
'Indian/Mayotte': 'YT',
|
||||
'Indian/Reunion': 'RE',
|
||||
'Mexico/BajaNorte': 'MX',
|
||||
'Mexico/BajaSur': 'MX',
|
||||
'Mexico/General': 'MX',
|
||||
'Pacific/Apia': 'WS',
|
||||
'Pacific/Auckland': 'NZ',
|
||||
'Pacific/Bougainville': 'PG',
|
||||
'Pacific/Chatham': 'NZ',
|
||||
'Pacific/Chuuk': 'FM',
|
||||
'Pacific/Easter': 'CL',
|
||||
'Pacific/Efate': 'VU',
|
||||
'Pacific/Enderbury': 'KI',
|
||||
'Pacific/Fakaofo': 'TK',
|
||||
'Pacific/Fiji': 'FJ',
|
||||
'Pacific/Funafuti': 'TV',
|
||||
'Pacific/Galapagos': 'EC',
|
||||
'Pacific/Gambier': 'PF',
|
||||
'Pacific/Guadalcanal': 'SB',
|
||||
'Pacific/Guam': 'GU',
|
||||
'Pacific/Honolulu': 'US',
|
||||
'Pacific/Johnston': 'US',
|
||||
'Pacific/Kanton': 'KI',
|
||||
'Pacific/Kiritimati': 'KI',
|
||||
'Pacific/Kosrae': 'FM',
|
||||
'Pacific/Kwajalein': 'MH',
|
||||
'Pacific/Majuro': 'MH',
|
||||
'Pacific/Marquesas': 'PF',
|
||||
'Pacific/Midway': 'UM',
|
||||
'Pacific/Nauru': 'NR',
|
||||
'Pacific/Niue': 'NU',
|
||||
'Pacific/Norfolk': 'NF',
|
||||
'Pacific/Noumea': 'NC',
|
||||
'Pacific/Pago_Pago': 'AS',
|
||||
'Pacific/Palau': 'PW',
|
||||
'Pacific/Pitcairn': 'PN',
|
||||
'Pacific/Pohnpei': 'FM',
|
||||
'Pacific/Ponape': 'FM',
|
||||
'Pacific/Port_Moresby': 'PG',
|
||||
'Pacific/Rarotonga': 'CK',
|
||||
'Pacific/Saipan': 'MP',
|
||||
'Pacific/Samoa': 'AS',
|
||||
'Pacific/Tahiti': 'PF',
|
||||
'Pacific/Tarawa': 'KI',
|
||||
'Pacific/Tongatapu': 'TO',
|
||||
'Pacific/Truk': 'FM',
|
||||
'Pacific/Wake': 'UM',
|
||||
'Pacific/Wallis': 'WF',
|
||||
'Pacific/Yap': 'FM',
|
||||
'US/Alaska': 'US',
|
||||
'US/Aleutian': 'US',
|
||||
'US/Arizona': 'US',
|
||||
'US/Central': 'US',
|
||||
'US/East-Indiana': 'US',
|
||||
'US/Eastern': 'US',
|
||||
'US/Hawaii': 'US',
|
||||
'US/Indiana-Starke': 'US',
|
||||
'US/Michigan': 'US',
|
||||
'US/Mountain': 'US',
|
||||
'US/Pacific': 'US',
|
||||
'US/Samoa': 'AS',
|
||||
};
|
||||
@@ -65,7 +65,10 @@ const START_SIZE_PX = 1024;
|
||||
const MAX_SIZE_PX = 4096;
|
||||
|
||||
function createAtlas() {
|
||||
const slotOfKey = new Map();
|
||||
// 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 entries = [];
|
||||
const listeners = new Set();
|
||||
const atlas = {
|
||||
@@ -90,8 +93,8 @@ function createAtlas() {
|
||||
* @returns {number}
|
||||
*/
|
||||
slot(url, sizePx, source) {
|
||||
const key = `${sizePx}|${url}`;
|
||||
const known = slotOfKey.get(key);
|
||||
let bySize = slotsOfUrl.get(url);
|
||||
const known = bySize?.get(sizePx);
|
||||
if (known !== undefined) return known;
|
||||
if (entries.length >= MAX_ICON_SLOTS)
|
||||
throw new RangeError(
|
||||
@@ -100,7 +103,8 @@ function createAtlas() {
|
||||
const slot = entries.length;
|
||||
const entry = { url, sizePx, image: null, x: 0, y: 0 };
|
||||
entries.push(entry);
|
||||
slotOfKey.set(key, slot);
|
||||
if (!bySize) slotsOfUrl.set(url, (bySize = new Map()));
|
||||
bySize.set(sizePx, slot);
|
||||
if (source) placeLoaded(entry, source);
|
||||
else load(entry);
|
||||
return slot;
|
||||
@@ -108,7 +112,7 @@ function createAtlas() {
|
||||
|
||||
/** Whether `url` at `sizePx` already has a slot. */
|
||||
has(url, sizePx) {
|
||||
return slotOfKey.has(`${sizePx}|${url}`);
|
||||
return slotsOfUrl.get(url)?.has(sizePx) === true;
|
||||
},
|
||||
|
||||
/** Whether a slot's image is packed and drawable. */
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
});
|
||||
@@ -774,9 +774,11 @@ test('markup, startup ordering and accessibility remain pinned', async () => {
|
||||
);
|
||||
|
||||
assert.match(startup, /styleManager\.initialRestorePromise/);
|
||||
assert.match(
|
||||
startup,
|
||||
/loadingScreen\.classList\.add\('hidden'\);\s*revealAfterCover\(\);/,
|
||||
assert.ok(
|
||||
startup.indexOf("loadingScreen.classList.add('hidden')") <
|
||||
startup.indexOf(
|
||||
"loadingScreen.addEventListener('transitionend', revealFirstRun",
|
||||
),
|
||||
);
|
||||
assert.match(
|
||||
startup,
|
||||
@@ -918,7 +920,7 @@ test('the Stories announcement waits behind the welcome card', () => {
|
||||
// the card is dismissed.
|
||||
assert.match(
|
||||
css,
|
||||
/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*\}/,
|
||||
/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*\}/,
|
||||
);
|
||||
// The selector only works while Stories still renders the popup as #hPop
|
||||
// inside #gev-stories.
|
||||
@@ -1108,10 +1110,11 @@ 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).
|
||||
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
|
||||
// Fire Perimeters queries add lastGrowthTime.
|
||||
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
|
||||
assert.equal(
|
||||
crypto.createHash('sha256').update(block).digest('hex'),
|
||||
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
|
||||
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
|
||||
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
|
||||
);
|
||||
const instructions = fs.readFileSync(
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
|
||||
import { START_VIEW } from './camera.js';
|
||||
|
||||
/**
|
||||
* The visitor's country, guessed from the browser's time zone and, for a zone
|
||||
* that belongs to no country (UTC), the region of a preferred language
|
||||
* ("en-GB"). Nothing leaves the browser. Null when neither names one.
|
||||
* @param {{timeZone?: string|null, languages?: readonly string[]}} [where]
|
||||
* @returns {string|null} ISO 3166 code, e.g. 'DE'
|
||||
*/
|
||||
export function homeCountry({
|
||||
timeZone = currentTimeZone(),
|
||||
languages = globalThis.navigator?.languages ?? [],
|
||||
} = {}) {
|
||||
const byZone = ZONE_COUNTRIES[timeZone];
|
||||
if (byZone) return byZone;
|
||||
for (const language of languages) {
|
||||
const region = regionOf(language);
|
||||
if (region && COUNTRY_CENTRES[region]) return region;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look straight down over the visitor's country from the start height.
|
||||
* Use the default start view when the country is unknown.
|
||||
* @param {{timeZone?: string|null, languages?: readonly string[]}} [where]
|
||||
*/
|
||||
export function homeCountryView(where = {}) {
|
||||
const centre = COUNTRY_CENTRES[homeCountry(where)];
|
||||
if (!centre) return START_VIEW;
|
||||
const [lat, lon] = centre;
|
||||
return Object.freeze({ lon, lat, height: START_VIEW.height });
|
||||
}
|
||||
|
||||
function currentTimeZone() {
|
||||
try {
|
||||
return new Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function regionOf(language) {
|
||||
try {
|
||||
return new Intl.Locale(language).region ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { homeCountry, homeCountryView } from './homeCountry.js';
|
||||
import { START_VIEW } from './camera.js';
|
||||
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
|
||||
|
||||
test('the time zone names the country, in its tzdata, ICU or older name', () => {
|
||||
assert.equal(homeCountry({ timeZone: 'Europe/Berlin', languages: [] }), 'DE');
|
||||
assert.equal(homeCountry({ timeZone: 'Asia/Kolkata', languages: [] }), 'IN');
|
||||
assert.equal(homeCountry({ timeZone: 'Asia/Calcutta', languages: [] }), 'IN');
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'Asia/Choibalsan', languages: [] }),
|
||||
'MN',
|
||||
);
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'Europe/Uzhgorod', languages: [] }),
|
||||
'UA',
|
||||
);
|
||||
assert.equal(homeCountry({ timeZone: 'Europe/Kiev', languages: [] }), 'UA');
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'America/Chicago', languages: ['de-DE'] }),
|
||||
'US',
|
||||
'the zone outranks the language',
|
||||
);
|
||||
});
|
||||
|
||||
test("a zone of no country falls back to a language's region", () => {
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'UTC', languages: ['fr', 'en-GB'] }),
|
||||
'GB',
|
||||
);
|
||||
assert.equal(homeCountry({ timeZone: 'Etc/UTC', languages: ['ru'] }), null);
|
||||
assert.equal(homeCountry({ timeZone: null, languages: [] }), null);
|
||||
});
|
||||
|
||||
test('the start view looks down on the country from the planet height', () => {
|
||||
const view = homeCountryView({ timeZone: 'Asia/Tokyo', languages: [] });
|
||||
assert.deepEqual(
|
||||
[view.lat, view.lon, view.height],
|
||||
[...COUNTRY_CENTRES.JP, START_VIEW.height],
|
||||
);
|
||||
assert.equal(
|
||||
homeCountryView({ timeZone: 'UTC', languages: [] }),
|
||||
START_VIEW,
|
||||
'unknown: the default start',
|
||||
);
|
||||
});
|
||||
|
||||
test('every zone has a country with a centre on the globe', () => {
|
||||
for (const [zone, country] of Object.entries(ZONE_COUNTRIES)) {
|
||||
const centre = COUNTRY_CENTRES[country];
|
||||
assert.ok(centre, `${zone} → ${country}`);
|
||||
const [lat, lon] = centre;
|
||||
assert.ok(Math.abs(lat) <= 90 && Math.abs(lon) <= 180, country);
|
||||
}
|
||||
// Countries whose largest part is not where their centroid would be.
|
||||
const [usLat, usLon] = COUNTRY_CENTRES.US;
|
||||
assert.ok(usLat > 30 && usLat < 45 && usLon > -110 && usLon < -85);
|
||||
const [frLat, frLon] = COUNTRY_CENTRES.FR;
|
||||
assert.ok(frLat > 42 && frLat < 50 && frLon > -2 && frLon < 8);
|
||||
});
|
||||
+140
-29
@@ -61,7 +61,6 @@ import {
|
||||
import { isRtlLocale } from './i18n/locale.js';
|
||||
import { localizeLayerName } from './ui/layerPanel.js';
|
||||
import { isEmbeddedInline } from './app/embed.js';
|
||||
import { openingPlaying } from './app/openingIntro.js';
|
||||
import { subscribeSelectedVessel } from './hudReadouts.js';
|
||||
|
||||
/** Color palettes keyed by shader mode; applied as CSS custom properties. */
|
||||
@@ -228,6 +227,17 @@ 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.
|
||||
@@ -255,6 +265,19 @@ 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}. */
|
||||
@@ -321,26 +344,8 @@ export class IntelHUD {
|
||||
};
|
||||
this._onCameraMoveEnd = () => {
|
||||
this._markSummaryDirty();
|
||||
// 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...").
|
||||
// The opening's frames are not that view: it lands with a moveEnd.
|
||||
if (
|
||||
!this._firstSummaryKicked &&
|
||||
!openingPlaying() &&
|
||||
this._visible &&
|
||||
this._latestMetrics
|
||||
) {
|
||||
this._firstSummaryKicked = true;
|
||||
void this._updateSummary(true, true);
|
||||
}
|
||||
if (this._displayed) this._settle();
|
||||
else this._unseen.settle = true;
|
||||
};
|
||||
|
||||
// Session-consistent pseudorandom identifiers (generated once at construction)
|
||||
@@ -365,6 +370,27 @@ 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();
|
||||
@@ -381,7 +407,8 @@ export class IntelHUD {
|
||||
? {}
|
||||
: { vessel: { active: false, text: t('AIS: --') } }),
|
||||
});
|
||||
if (this._visible && this._latestMetrics) this._updateCameraData();
|
||||
if (this._visible && this._displayed && this._latestMetrics)
|
||||
this._updateCameraData();
|
||||
this._setSummaryText(this._composeSummary(), false);
|
||||
}
|
||||
|
||||
@@ -424,10 +451,17 @@ export class IntelHUD {
|
||||
*/
|
||||
_present(patch) {
|
||||
Object.assign(this._view, patch);
|
||||
const signature = JSON.stringify(this._view);
|
||||
// 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);
|
||||
if (signature === this._viewSignature) return;
|
||||
this._viewSignature = signature;
|
||||
this._publish(Object.freeze({ ...this._view }));
|
||||
this._shown = Object.freeze({ ...view });
|
||||
this._publish(this._shown);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -436,6 +470,7 @@ 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() });
|
||||
@@ -462,6 +497,18 @@ 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.
|
||||
@@ -851,6 +898,7 @@ export class IntelHUD {
|
||||
_stopSummaryTyping() {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
this._summaryTypingText = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -860,6 +908,7 @@ export class IntelHUD {
|
||||
*/
|
||||
_typeSummary(text) {
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingText = text;
|
||||
let index = 0;
|
||||
this._present({ summary: '' });
|
||||
this._summaryTypingInterval = setInterval(() => {
|
||||
@@ -868,6 +917,7 @@ export class IntelHUD {
|
||||
this._present({ summary: text });
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
this._summaryTypingInterval = null;
|
||||
this._summaryTypingText = null;
|
||||
return;
|
||||
}
|
||||
this._present({ summary: text.slice(0, index) });
|
||||
@@ -880,6 +930,16 @@ 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);
|
||||
@@ -1009,7 +1069,8 @@ export class IntelHUD {
|
||||
}
|
||||
|
||||
_setSummaryText(text, animate) {
|
||||
if (animate) {
|
||||
// Nothing types out off screen: the text is there when the view is back.
|
||||
if (animate && this._displayed) {
|
||||
this._typeSummary(text);
|
||||
return;
|
||||
}
|
||||
@@ -1130,11 +1191,63 @@ 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;
|
||||
@@ -1221,10 +1334,8 @@ export class IntelHUD {
|
||||
|
||||
/** Tear down all running intervals. Call when discarding the HUD instance. */
|
||||
destroy() {
|
||||
clearInterval(this._updateInterval);
|
||||
clearInterval(this._recBlinkInterval);
|
||||
clearInterval(this._timestampInterval);
|
||||
clearInterval(this._summaryInterval);
|
||||
this._destroyed = true;
|
||||
this._stopTimers();
|
||||
clearInterval(this._summaryTypingInterval);
|
||||
for (const off of this._offCamera.splice(0)) off();
|
||||
this._dataManagerUnsubscribe?.();
|
||||
|
||||
@@ -6,8 +6,6 @@
|
||||
// setup as hudPageVisibility.test.mjs).
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import { playOpeningIntro } from './app/openingIntro.js';
|
||||
import { hudReadouts } from './testSupport/hudReadouts.mjs';
|
||||
import { registerHooks } from 'node:module';
|
||||
import { fakeCameraPort } from './testSupport/fakeCameraPort.mjs';
|
||||
@@ -177,45 +175,3 @@ test('an unchanged context restores its accepted reply over the fallback line',
|
||||
assert.equal(service.calls, 1);
|
||||
assert.equal(shown(), 'Austin capitol district live');
|
||||
});
|
||||
|
||||
test('the first summary waits for the opening to land', (t) => {
|
||||
const { hud } = createHud(t, {
|
||||
summarize: async () => ({ ok: true, status: 200, data: { summary: 'x' } }),
|
||||
});
|
||||
hud._visible = true;
|
||||
let asked = 0;
|
||||
hud._updateSummary = async () => {
|
||||
asked += 1;
|
||||
};
|
||||
|
||||
const win = new Window();
|
||||
win.document.body.innerHTML = `
|
||||
<div id="loading-screen"><span class="loader-logo"><svg>
|
||||
<path id="outer_eye"/><path id="inner_eye"/>
|
||||
</svg></span></div>`;
|
||||
win.requestAnimationFrame = () => 1;
|
||||
win.matchMedia = () => ({ matches: false });
|
||||
const opening = playOpeningIntro({
|
||||
win,
|
||||
loadingScreen: win.document.getElementById('loading-screen'),
|
||||
camera: {
|
||||
pose: () => ({
|
||||
lon: 10,
|
||||
lat: 50,
|
||||
height: 23e6,
|
||||
heading: 0,
|
||||
pitch: -Math.PI / 2,
|
||||
roll: 0,
|
||||
fovy: 1,
|
||||
}),
|
||||
setView() {},
|
||||
onCommand: () => () => {},
|
||||
},
|
||||
});
|
||||
t.after(() => opening.cancel());
|
||||
hud._onCameraMoveEnd();
|
||||
assert.equal(asked, 0);
|
||||
opening.cancel();
|
||||
hud._onCameraMoveEnd();
|
||||
assert.equal(asked, 1);
|
||||
});
|
||||
@@ -1845,11 +1845,6 @@
|
||||
"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.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
|
||||
@@ -4856,5 +4851,12 @@
|
||||
"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}"
|
||||
"{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 م."
|
||||
}
|
||||
@@ -1727,11 +1727,6 @@
|
||||
"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.",
|
||||
@@ -4432,5 +4427,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1411,11 +1411,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1070,11 +1070,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -919,11 +919,6 @@
|
||||
"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": "חדשות",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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 מ׳."
|
||||
}
|
||||
@@ -1070,11 +1070,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1024,11 +1024,6 @@
|
||||
"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": "ニュース",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"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} 発表"
|
||||
"{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 に簡略化されています。"
|
||||
}
|
||||
@@ -1068,11 +1068,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1439,11 +1439,6 @@
|
||||
"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 м",
|
||||
@@ -4644,5 +4639,12 @@
|
||||
"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}"
|
||||
"{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 м."
|
||||
}
|
||||
@@ -1643,11 +1643,6 @@
|
||||
"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.",
|
||||
@@ -4432,5 +4427,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1092,11 +1092,6 @@
|
||||
"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": "Новини",
|
||||
@@ -4644,5 +4639,12 @@
|
||||
"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}"
|
||||
"{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 м."
|
||||
}
|
||||
@@ -1004,11 +1004,6 @@
|
||||
"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": "新闻",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"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}"
|
||||
"{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 米。"
|
||||
}
|
||||
@@ -1004,11 +1004,6 @@
|
||||
"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": "新聞",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"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}"
|
||||
"{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 米。"
|
||||
}
|
||||
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createIcons } from './icons.js';
|
||||
import { createContactIcons } from '../../data/aircraftIconLayer.js';
|
||||
import {
|
||||
createContactIcons,
|
||||
placedPlanSpread,
|
||||
} from '../../data/aircraftIconLayer.js';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import {
|
||||
aircraftMotionRegime,
|
||||
@@ -269,8 +272,10 @@ 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 + 1000 + leadMs]);
|
||||
assert.deepEqual(asked, [now + leadMs, now + planMs + leadMs]);
|
||||
assert.equal(regimes.length, 0, 'its own motion is not planned');
|
||||
const item = set.item('p');
|
||||
assert.equal(item.motion.kind, 'lerp');
|
||||
@@ -284,16 +289,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 + 1000 + leadMs - t0) / 10_000,
|
||||
(now + planMs + leadMs - t0) / 10_000,
|
||||
30,
|
||||
2000,
|
||||
),
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.equal(item.motion.t0, now);
|
||||
assert.equal(item.motion.t1, now + 1000);
|
||||
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
|
||||
assert.equal(set.expires('p'), now + 1000);
|
||||
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);
|
||||
|
||||
// No answer: the layer's own motion plans it.
|
||||
places = false;
|
||||
|
||||
@@ -11,7 +11,6 @@ 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;
|
||||
|
||||
@@ -112,7 +111,8 @@ export function createLifecycle({
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
holdContinuousRender('flights'); // per-frame animator (perf wave 2)
|
||||
// Drawn as often as the fleet moves on screen (renderPace.js).
|
||||
parts.rendering._startPace();
|
||||
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;
|
||||
releaseContinuousRender('flights');
|
||||
parts.rendering._stopPace();
|
||||
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();
|
||||
releaseContinuousRender('flights'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -10,7 +10,6 @@ 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;
|
||||
@@ -93,7 +92,8 @@ export function createLifecycle({
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
holdContinuousRender('military'); // per-frame animator (perf wave 2)
|
||||
// Drawn as often as the fleet moves on screen (renderPace.js).
|
||||
parts.rendering._startPace();
|
||||
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;
|
||||
releaseContinuousRender('military');
|
||||
parts.rendering._stopPace();
|
||||
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();
|
||||
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -8,13 +8,14 @@ import { buildIncidentCard } from './cards.js';
|
||||
|
||||
const now = Date.UTC(2026, 9, 14);
|
||||
const row = {
|
||||
stableId: 'x',
|
||||
id: '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',
|
||||
@@ -33,6 +34,7 @@ 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',
|
||||
]);
|
||||
@@ -44,8 +46,8 @@ for (const locale of ['es', 'ru']) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
assert.notEqual(
|
||||
t('Fully contained'),
|
||||
'Fully contained',
|
||||
t('Older or unknown'),
|
||||
'Older or unknown',
|
||||
'legend is translated',
|
||||
);
|
||||
const card = buildIncidentCard(row, now, {
|
||||
@@ -60,6 +62,7 @@ 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 (mirrors the fill). */
|
||||
/** CSS accent for a perimeter card by containment progress. */
|
||||
export function containmentAccent(containedPct) {
|
||||
if (!Number.isFinite(containedPct) || containedPct <= 0) return '#ff3b30';
|
||||
if (containedPct < 50) return '#ff7a00';
|
||||
@@ -11,55 +11,6 @@ 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.
|
||||
@@ -149,8 +100,9 @@ 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 - Normalized perimeter row (see records.js).
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {Object} row - A snapshot fire (see records.js).
|
||||
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
|
||||
* `at`, or now.
|
||||
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
|
||||
* @returns {Object} World-overlay entry without `position`.
|
||||
*/
|
||||
@@ -194,13 +146,17 @@ 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 = 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 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 details = [facts.join(' · ')];
|
||||
if (row.complexName)
|
||||
@@ -209,6 +165,7 @@ 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'));
|
||||
|
||||
@@ -216,7 +173,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
name: row.name || t('Unnamed incident'),
|
||||
});
|
||||
return {
|
||||
id: `fire-perimeter-card:${row.stableId}`,
|
||||
id: `fire-perimeter-card:${row.id}`,
|
||||
// `selected` picks the paint lane and collision protection; an explicit
|
||||
// paintLane would override it in the host's lane resolver.
|
||||
selected: true,
|
||||
|
||||
@@ -1,99 +1,12 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
import { buildIncidentCard } from './cards.js';
|
||||
|
||||
test('a full incident row renders name, size, containment, and ages', () => {
|
||||
const now = 1758000000000;
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: '2026-NMGNF-000123',
|
||||
id: '2026-NMGNF-000123',
|
||||
name: 'Frijoles',
|
||||
acres: 15956.4,
|
||||
containedPct: 74,
|
||||
@@ -101,6 +14,7 @@ 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,
|
||||
@@ -116,6 +30,7 @@ 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);
|
||||
@@ -125,7 +40,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: null,
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -149,7 +64,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Timber',
|
||||
acres: 25426,
|
||||
containedPct: 44,
|
||||
@@ -177,7 +92,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Any',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -204,7 +119,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 = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Any',
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -232,7 +147,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 342923,
|
||||
containedPct: 99,
|
||||
@@ -256,7 +171,7 @@ test('a complex member names its complex on the card', () => {
|
||||
test('a card without a link is not interactive', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -279,7 +194,7 @@ test('a card without a link is not interactive', () => {
|
||||
test('partial incident details render only the facts that exist', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Whiskey',
|
||||
acres: 542,
|
||||
containedPct: 48,
|
||||
@@ -305,7 +220,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 = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Grey',
|
||||
acres: 0.25,
|
||||
containedPct: null,
|
||||
@@ -333,3 +248,22 @@ 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,19 +17,8 @@ function normalizeName(name) {
|
||||
.replace(/ fire$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
function nodeCandidates(publications, { name, state }) {
|
||||
if (!Array.isArray(publications) || !name) return [];
|
||||
const wanted = normalizeName(name);
|
||||
let candidates = publications.filter(
|
||||
(row) =>
|
||||
@@ -51,20 +40,26 @@ export function resolveInciwebNodeLink(publications, { name, state }) {
|
||||
row.tau.slice(0, 2).toLowerCase() === statePrefix,
|
||||
);
|
||||
} else if (candidates.length > 1) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
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;
|
||||
// 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;
|
||||
}
|
||||
|
||||
/** The publication id inside a node link produced above, or null. */
|
||||
@@ -79,7 +74,8 @@ 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 recent editorial activity on the page.
|
||||
// Without a discovery date, require editorial activity on the page in the
|
||||
// 180 days up to the moment shown.
|
||||
const CHANGED_WITHIN_MS = 180 * 24 * 3600000;
|
||||
|
||||
/**
|
||||
@@ -97,7 +93,8 @@ export function isCurrentPublication(
|
||||
return createdMs >= discoveredTime - CREATED_BEFORE_DISCOVERY_MS;
|
||||
}
|
||||
if (Number.isFinite(changedMs)) {
|
||||
return nowMs - changedMs <= CHANGED_WITHIN_MS;
|
||||
const age = nowMs - changedMs;
|
||||
return age >= 0 && age <= CHANGED_WITHIN_MS;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -132,6 +129,14 @@ 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
|
||||
@@ -143,11 +148,8 @@ export function createInciwebPublicationSource({
|
||||
* - WFIGS row facts.
|
||||
* @returns {?string} InciWeb URL.
|
||||
*/
|
||||
export function findInciwebLink(publications, { name, state, complexName }) {
|
||||
return (
|
||||
resolveInciwebNodeLink(publications, { name, state }) ??
|
||||
resolveInciwebNodeLink(publications, { name: complexName, state })
|
||||
);
|
||||
export function findInciwebLink(publications, incident) {
|
||||
return findInciwebLinks(publications, incident)[0] ?? null;
|
||||
}
|
||||
|
||||
/** Fetch the full InciWeb incident catalog. */
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
resolveInciwebNodeLink,
|
||||
createInciwebIndexSource,
|
||||
createInciwebPublicationSource,
|
||||
@@ -142,6 +143,34 @@ 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, {
|
||||
@@ -214,6 +243,14 @@ 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(
|
||||
|
||||
+277
-143
@@ -1,34 +1,64 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
|
||||
import {
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
perimeterAnchorDegrees,
|
||||
buildIncidentCard,
|
||||
containmentAccent,
|
||||
} from './cards.js';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
inciwebNodeId,
|
||||
isCurrentPublication,
|
||||
} from './inciweb.js';
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
|
||||
export { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
export {
|
||||
normalizeFirePerimeterSnapshot,
|
||||
perimeterAnchorDegrees,
|
||||
} from './records.js';
|
||||
export { createWfigsPerimeterSource } from './source.js';
|
||||
export * from './cards.js';
|
||||
export * from './inciweb.js';
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
|
||||
/**
|
||||
* Fill/line colour for a perimeter by containment progress (same ramp as the
|
||||
* card accent), as a renderer colour `[r, g, b, a]`.
|
||||
* 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.
|
||||
*/
|
||||
export function containmentColor(containedPct) {
|
||||
return hexColor(containmentAccent(containedPct));
|
||||
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);
|
||||
}
|
||||
|
||||
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
|
||||
const FILL_ALPHA = 0.35;
|
||||
const LINE_ALPHA = 0.9;
|
||||
const LINE_WIDTH_PX = 2;
|
||||
|
||||
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
|
||||
@@ -52,10 +82,29 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
|
||||
/**
|
||||
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
|
||||
*
|
||||
* 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.
|
||||
* `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.
|
||||
*/
|
||||
export function createFirePerimetersLayer({
|
||||
source,
|
||||
@@ -71,12 +120,17 @@ export function createFirePerimetersLayer({
|
||||
let _viewer = null;
|
||||
let _request = null;
|
||||
let _linkRequest = null;
|
||||
let _snapshotSignature = null;
|
||||
// What the sets show: the snapshot revision and each piece's age band.
|
||||
let _drawnKey = 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;
|
||||
@@ -88,16 +142,26 @@ export function createFirePerimetersLayer({
|
||||
let _inciwebIndex = [];
|
||||
let _indexFetchedAt = 0;
|
||||
let _indexFetchInFlight = false;
|
||||
/** @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();
|
||||
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();
|
||||
function abortLinkVerification() {
|
||||
_linkRequest?.controller.abort();
|
||||
_linkRequest = null;
|
||||
}
|
||||
|
||||
function resetSelection() {
|
||||
abortLinkVerification();
|
||||
_linkFailures.clear();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
}
|
||||
|
||||
const canSelect = () => overlayHost && inputFor && picking;
|
||||
|
||||
/**
|
||||
@@ -141,29 +205,57 @@ export function createFirePerimetersLayer({
|
||||
.getPublication(id, { signal })
|
||||
.then((publication) => {
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkVerdicts.set(
|
||||
link,
|
||||
isCurrentPublication(publication, {
|
||||
discoveredTime: row.discoveredTime,
|
||||
}),
|
||||
);
|
||||
if (_selectedId === row.stableId) publishSelectedCard();
|
||||
_linkPublications.set(link, publication ?? {});
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
})
|
||||
.catch(() => {
|
||||
// Fail closed without caching: no link now, retry on reselection.
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkFailures.add(link);
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
})
|
||||
.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 ? _rowById.get(_selectedId) : null;
|
||||
const row = _selectedId ? _fireById.get(_selectedId) : null;
|
||||
if (!row) {
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
resetSelection();
|
||||
overlayHost.setEntries(
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
@@ -171,12 +263,36 @@ export function createFirePerimetersLayer({
|
||||
);
|
||||
return;
|
||||
}
|
||||
const candidate = findInciwebLink(_inciwebIndex, row);
|
||||
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
|
||||
_selectedLink =
|
||||
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
|
||||
// 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 card = {
|
||||
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
|
||||
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
|
||||
position: fromDegrees(row.anchor.lon, row.anchor.lat),
|
||||
};
|
||||
if (!openExternal) card.interactive = false;
|
||||
@@ -201,11 +317,9 @@ export function createFirePerimetersLayer({
|
||||
* of this layer's own sets, for an incident drawn now; else null.
|
||||
*/
|
||||
function pickedIncidentId(hit) {
|
||||
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;
|
||||
if (!hit || hit.surface) return null;
|
||||
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
|
||||
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
@@ -236,6 +350,7 @@ export function createFirePerimetersLayer({
|
||||
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
|
||||
if (incidentId) {
|
||||
abortLinkVerification();
|
||||
_linkFailures.clear();
|
||||
_selectedId = incidentId;
|
||||
publishSelectedCard();
|
||||
return;
|
||||
@@ -247,23 +362,67 @@ 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() {
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
resetSelection();
|
||||
if (overlayHost) {
|
||||
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
|
||||
@@ -292,9 +451,7 @@ export function createFirePerimetersLayer({
|
||||
clampTo: 'both',
|
||||
show: false,
|
||||
});
|
||||
_setIds = new Set([_fills.id, _lines.id]);
|
||||
_viewer = viewer;
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -318,87 +475,58 @@ export function createFirePerimetersLayer({
|
||||
clearSelection();
|
||||
},
|
||||
|
||||
async update() {
|
||||
async update(_viewerArg, { signal } = {}) {
|
||||
if (!_enabled || !_fills) return false;
|
||||
_request?.abort();
|
||||
const request = new AbortController();
|
||||
_request = request;
|
||||
refreshInciwebIndex(request.signal);
|
||||
const abort = () => request.abort(signal.reason);
|
||||
if (signal?.aborted) abort();
|
||||
else signal?.addEventListener('abort', abort, { once: true });
|
||||
try {
|
||||
// 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 }) };
|
||||
refreshInciwebIndex(request.signal);
|
||||
const snapshot = await source.getSnapshot({ signal: request.signal });
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
const { rows } = snapshot;
|
||||
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
|
||||
throw new Error(msg('Malformed perimeter 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();
|
||||
|
||||
// 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)),
|
||||
_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),
|
||||
);
|
||||
if (signature === _snapshotSignature) {
|
||||
if (_selectedId) publishSelectedCard();
|
||||
_lastUpdate = updatedAt;
|
||||
_lastError = null;
|
||||
return true;
|
||||
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;
|
||||
}
|
||||
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),
|
||||
});
|
||||
// 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();
|
||||
}
|
||||
|
||||
_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)
|
||||
@@ -409,6 +537,7 @@ export function createFirePerimetersLayer({
|
||||
_stale = false;
|
||||
return false;
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
if (_request === request) _request = null;
|
||||
}
|
||||
},
|
||||
@@ -418,18 +547,20 @@ export function createFirePerimetersLayer({
|
||||
_request = null;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
_rowById.clear();
|
||||
_snapshotSignature = null;
|
||||
_fireById = new Map();
|
||||
_fireByItem.clear();
|
||||
_drawnKey = null;
|
||||
_at = null;
|
||||
_bandsAt = null;
|
||||
_note = null;
|
||||
_inciwebIndex = [];
|
||||
_indexFetchedAt = 0;
|
||||
_linkVerdicts.clear();
|
||||
_linkPublications.clear();
|
||||
_viewer = null;
|
||||
_enabled = false;
|
||||
_fills?.dispose();
|
||||
_lines?.dispose();
|
||||
_fills = _lines = null;
|
||||
_setIds = new Set();
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -442,11 +573,15 @@ export function createFirePerimetersLayer({
|
||||
? Math.max(1, Math.floor(maxCount))
|
||||
: 2000;
|
||||
const result = [];
|
||||
for (const row of _rowById.values()) {
|
||||
for (const fire of _fireById.values()) {
|
||||
if (result.length >= limit) break;
|
||||
const { anchor, stableId, ...facts } = row;
|
||||
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;
|
||||
result.push({
|
||||
id: stableId,
|
||||
id,
|
||||
...facts,
|
||||
lat: anchor.lat,
|
||||
lon: anchor.lon,
|
||||
@@ -455,34 +590,33 @@ export function createFirePerimetersLayer({
|
||||
return result;
|
||||
},
|
||||
|
||||
/** The moment the analyst records show: the snapshot's `at`, or null for now. */
|
||||
getAnalystRecordsAt() {
|
||||
return _at;
|
||||
},
|
||||
|
||||
getRowControls() {
|
||||
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) },
|
||||
];
|
||||
const atMs = _bandsAt;
|
||||
const counts = PERIMETER_AGE_BANDS.map(() => 0);
|
||||
for (const fire of _fireById.values())
|
||||
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
|
||||
return {
|
||||
chips: [],
|
||||
legend: bands.map((band, index) => ({
|
||||
...band,
|
||||
count: [..._rowById.values()].filter(
|
||||
(row) => containmentAccent(row.containedPct) === band.color,
|
||||
).length,
|
||||
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
|
||||
label: t(band.label),
|
||||
color: band.color,
|
||||
count: counts[index],
|
||||
...(index === 0
|
||||
? {
|
||||
blurb: t(
|
||||
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
|
||||
),
|
||||
}
|
||||
? { blurb: t('Colour shows the age of each area.') }
|
||||
: {}),
|
||||
})),
|
||||
...(_note ? { info: t(_note) } : {}),
|
||||
};
|
||||
},
|
||||
|
||||
getStats() {
|
||||
return {
|
||||
count: _count,
|
||||
count: _fireById.size,
|
||||
lastUpdate: _lastUpdate,
|
||||
error: _lastError,
|
||||
stale: _stale,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,14 @@
|
||||
/**
|
||||
* 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
|
||||
@@ -80,6 +91,7 @@ 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),
|
||||
@@ -92,3 +104,114 @@ 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,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
import {
|
||||
perimeterAnchorDegrees,
|
||||
normalizeFirePerimeterSnapshot,
|
||||
firePerimeterSnapshot,
|
||||
} from './records.js';
|
||||
|
||||
const ring = [
|
||||
[-108.1, 35.2],
|
||||
@@ -22,6 +26,7 @@ function feature(overrides = {}) {
|
||||
attr_IncidentTypeCategory: 'WF',
|
||||
attr_FireDiscoveryDateTime: 1757900000000,
|
||||
poly_DateCurrent: 1757950000000,
|
||||
poly_PolygonDateTime: 1757940000000,
|
||||
attr_FireCause: 'Natural',
|
||||
attr_FireBehaviorGeneral: 'Active',
|
||||
attr_TotalIncidentPersonnel: 380,
|
||||
@@ -59,6 +64,7 @@ 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,
|
||||
@@ -90,6 +96,7 @@ 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,
|
||||
@@ -110,6 +117,7 @@ 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,
|
||||
@@ -126,6 +134,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
category: null,
|
||||
discoveredTime: null,
|
||||
updatedTime: null,
|
||||
polygonTime: null,
|
||||
cause: null,
|
||||
behavior: null,
|
||||
personnel: null,
|
||||
@@ -199,3 +208,223 @@ 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,42 +1,35 @@
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { firePerimeterSnapshot } from './records.js';
|
||||
|
||||
// A portable export (package.json): no i18n here. Failures stay English data;
|
||||
// the Layers panel shows them translated.
|
||||
const msg = (text) => text;
|
||||
// Failures stay English data. The Layers panel shows them translated.
|
||||
|
||||
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
|
||||
/** Request a 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 {
|
||||
/** The perimeter rows (see getSnapshotDetail for staleness). */
|
||||
async getSnapshot(options = {}) {
|
||||
return (await getSnapshotDetail(options)).rows;
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
},
|
||||
getSnapshotDetail,
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,7 @@ const validPayload = {
|
||||
],
|
||||
};
|
||||
|
||||
test('a successful response yields normalized perimeter rows', async () => {
|
||||
test('a successful response yields the snapshot of fires and pieces', async () => {
|
||||
let requested;
|
||||
const source = createWfigsPerimeterSource({
|
||||
fetchImpl: async (url) => {
|
||||
@@ -30,9 +30,13 @@ test('a successful response yields normalized perimeter rows', async () => {
|
||||
});
|
||||
},
|
||||
});
|
||||
const rows = await source.getSnapshot();
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
|
||||
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);
|
||||
assert.equal(requested, '/api/fire-perimeters');
|
||||
});
|
||||
|
||||
@@ -160,22 +164,20 @@ 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 detail carries the proxy staleness and fetch time', async () => {
|
||||
test('the snapshot 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 }),
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshotDetail(), {
|
||||
rows: [],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshot(), []);
|
||||
const snapshot = await source.getSnapshot();
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.fetchedAt, fetchedAt);
|
||||
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
|
||||
});
|
||||
|
||||
test('getSnapshot works when taken off its source object', async () => {
|
||||
const { getSnapshot } = createWfigsPerimeterSource({
|
||||
fetchImpl: async () => Response.json({ rows: [] }),
|
||||
});
|
||||
assert.deepEqual(await getSnapshot(), []);
|
||||
assert.deepEqual((await getSnapshot()).fires, []);
|
||||
});
|
||||
@@ -292,6 +292,8 @@ function recordingRendering(state) {
|
||||
if (point) point.show = show;
|
||||
},
|
||||
_setPointsShown() {},
|
||||
_startPace() {},
|
||||
_stopPace() {},
|
||||
_setOrbitPathShown(noradId, show) {
|
||||
if (state._orbitPaths.has(noradId)) rings.set(noradId, show);
|
||||
},
|
||||
|
||||
@@ -30,7 +30,6 @@ 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. */
|
||||
@@ -98,7 +97,8 @@ export function createLifecycle({
|
||||
|
||||
enable(viewer) {
|
||||
layerState._enabled = true;
|
||||
holdContinuousRender('satellites'); // per-frame animator (perf wave 2)
|
||||
// Drawn as often as the dots move on screen (rendering.js, the pace).
|
||||
parts.rendering._startPace();
|
||||
parts.rendering._setPointsShown(
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
@@ -137,7 +137,7 @@ export function createLifecycle({
|
||||
parts.catalog._abortActiveUpdates();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
layerState._enabled = false;
|
||||
releaseContinuousRender('satellites');
|
||||
parts.rendering._stopPace();
|
||||
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;
|
||||
releaseContinuousRender('satellites'); // direct-destroy path (perf wave 2 fix)
|
||||
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
|
||||
layerState._enabled = false;
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
|
||||
@@ -2,6 +2,11 @@ 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,
|
||||
@@ -104,6 +109,49 @@ 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-
|
||||
@@ -654,6 +702,26 @@ 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);
|
||||
@@ -669,7 +737,24 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -691,6 +776,7 @@ 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. */
|
||||
@@ -733,9 +819,17 @@ export function createRendering({
|
||||
|
||||
if (layerState._params.showPoints) {
|
||||
const worldMs = layerState.now();
|
||||
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
|
||||
layerState._lastReckonMs = worldMs;
|
||||
_reckonPoints(worldMs);
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
|
||||
@@ -781,8 +875,10 @@ 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);
|
||||
@@ -837,6 +933,7 @@ export function createRendering({
|
||||
).color,
|
||||
});
|
||||
layerState._activeFocusCount = result.activeCount;
|
||||
paceFading = Boolean(result.transitioning);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -939,6 +1036,9 @@ export function createRendering({
|
||||
_propagateAll,
|
||||
_reckonPoints,
|
||||
_preRenderTick,
|
||||
_startPace,
|
||||
_stopPace,
|
||||
_paceForTest: () => ({ ...pace.state(), pxPerSec: pacePxPerSec }),
|
||||
_updatePointFocus,
|
||||
applySatellitePointFocusDeemphasis,
|
||||
_flushPoints,
|
||||
|
||||
@@ -5,6 +5,8 @@ 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
|
||||
@@ -270,7 +272,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; a slow one once a second', (t) => {
|
||||
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) => {
|
||||
let mono = 0;
|
||||
t.mock.method(performance, 'now', () => mono);
|
||||
const originalDocument = globalThis.document;
|
||||
@@ -295,23 +297,24 @@ 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 16 ms since the pass before.
|
||||
// `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).
|
||||
const waitAfterStep = (dLat) => {
|
||||
layer.testing._runPlacementPassForTest();
|
||||
advance(1_000); // whatever frame that asked for comes and goes
|
||||
assert.equal(timers.size, 0);
|
||||
mono += 16;
|
||||
mono += 40;
|
||||
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 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);
|
||||
// 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);
|
||||
// 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({
|
||||
@@ -324,7 +327,20 @@ 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) <= 32);
|
||||
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);
|
||||
});
|
||||
|
||||
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (t) => {
|
||||
@@ -722,3 +738,49 @@ 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']]);
|
||||
});
|
||||
+108
-19
@@ -48,13 +48,19 @@ 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 = 0.5;
|
||||
/** A frame is asked for at least this often while any drawn vessel moves. */
|
||||
const PLACEMENT_FRAME_MS = 1000;
|
||||
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;
|
||||
/** 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;
|
||||
@@ -482,6 +488,12 @@ 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;
|
||||
}
|
||||
@@ -989,26 +1001,88 @@ 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 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.
|
||||
// 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;
|
||||
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();
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
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
|
||||
@@ -1126,6 +1200,12 @@ 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) {
|
||||
@@ -1143,6 +1223,7 @@ export function createRendering({
|
||||
function cancelPlacementFrame() {
|
||||
motionPassWallMs = null;
|
||||
forgetClockStep();
|
||||
placementDue = true;
|
||||
drawnBehind = false;
|
||||
hiddenFollowedAtWallMs = null;
|
||||
if (placementFrameTimer === null) return;
|
||||
@@ -1171,6 +1252,8 @@ 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 =
|
||||
@@ -1230,9 +1313,13 @@ 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.
|
||||
@@ -1246,6 +1333,7 @@ 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) {
|
||||
@@ -1258,8 +1346,9 @@ 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');
|
||||
holdContinuousRender('ais-vessels', { maxFps: VESSEL_FOCUS_FPS });
|
||||
else releaseContinuousRender('ais-vessels');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,16 +796,20 @@ 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;
|
||||
requestRender();
|
||||
if (!ownerFrames()) 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;
|
||||
requestRender();
|
||||
if (!ownerFrames()) requestRender();
|
||||
};
|
||||
// A shape's pulse the renderer cannot run is refused before anything
|
||||
// changes.
|
||||
@@ -925,7 +929,9 @@ export function createCesiumDraw({
|
||||
spec.motionClock?.kind === 'live'
|
||||
) {
|
||||
spec.motionClock = options.motionClock;
|
||||
requestRender();
|
||||
// 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();
|
||||
return;
|
||||
}
|
||||
// Refused, changing nothing, where icons on the GPU cannot take it
|
||||
|
||||
@@ -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 fire lines on a viewer of its own', async () => {
|
||||
test('the fire perimeters layer draws holed ground fills and draped outlines on a viewer of its own', async () => {
|
||||
const { createFirePerimetersLayer } =
|
||||
await import('../../layers/perimeters/index.js');
|
||||
const scene = fakeScene();
|
||||
@@ -2313,9 +2313,19 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
|
||||
];
|
||||
const layer = createFirePerimetersLayer({
|
||||
source: {
|
||||
getSnapshot: async () => [
|
||||
{ stableId: 'a', containedPct: 0, polygons: [[outer, hole]] },
|
||||
],
|
||||
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],
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
});
|
||||
layer.init(viewer);
|
||||
@@ -2336,9 +2346,9 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
|
||||
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, 1, 'the exterior ring only');
|
||||
assert.equal(line.geometryInstances.length, 2, 'the hole is outlined too');
|
||||
assert.equal(line.geometryInstances[0].geometry.width, 2);
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:0');
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:line:0');
|
||||
layer.destroy();
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
|
||||
@@ -163,6 +163,8 @@ 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) =>
|
||||
@@ -250,6 +252,7 @@ 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;
|
||||
@@ -260,9 +263,11 @@ 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(),
|
||||
@@ -331,6 +336,7 @@ 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();
|
||||
|
||||
@@ -870,7 +870,13 @@ export function createGpuIcons({
|
||||
},
|
||||
/** Whether a live-clock row is still moving: frames should keep coming. */
|
||||
animating() {
|
||||
if (spec.motionClock?.kind === 'scene' || spec.show === false)
|
||||
// A set whose owner asks for its frames (`frames: 'owner'`) is not
|
||||
// kept drawing by its moving rows.
|
||||
if (
|
||||
spec.motionClock?.kind === 'scene' ||
|
||||
spec.motionClock?.frames === 'owner' ||
|
||||
spec.show === false
|
||||
)
|
||||
return false;
|
||||
return set.count > 0 && clockMs() < movingUntil;
|
||||
},
|
||||
|
||||
@@ -221,6 +221,40 @@ test('rows moving on a live clock keep frames coming until their segments end',
|
||||
assert.equal(scene.renders, onScene);
|
||||
});
|
||||
|
||||
test('a live set whose owner asks for its frames asks for none itself', () => {
|
||||
const { scene, part, draw } = drawOver();
|
||||
const set = draw.icons({
|
||||
id: 'gpu:owned',
|
||||
motionClock: { kind: 'live', delayMs: 2000, frames: 'owner' },
|
||||
});
|
||||
const now = Date.now();
|
||||
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
|
||||
set.set([
|
||||
icon('a', {
|
||||
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
|
||||
}),
|
||||
]);
|
||||
const moving = scene.renders;
|
||||
part.afterRender();
|
||||
assert.equal(scene.renders, moving, 'moving rows ask for no frame');
|
||||
set.setOptions({
|
||||
motionClock: { kind: 'live', delayMs: 3000, frames: 'owner' },
|
||||
});
|
||||
assert.equal(scene.renders, moving, 'a new delay asks for no frame');
|
||||
// A row restyled in place, as the owner does when a frame begins (a
|
||||
// helicopter's rotor), asks for none either: that frame draws it.
|
||||
set.upsert([
|
||||
icon('a', {
|
||||
scale: 2,
|
||||
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
|
||||
}),
|
||||
]);
|
||||
assert.equal(scene.renders, moving, 'a write in place asks for no frame');
|
||||
set.setOptions({ motionClock: { kind: 'live', delayMs: 4000 } });
|
||||
part.afterRender();
|
||||
assert.ok(scene.renders > moving, 'back to the set: frames again');
|
||||
});
|
||||
|
||||
test('a set that recedes draws on the GPU, every row receding by the set’s parameters, and changes live', () => {
|
||||
const { scene, part, draw } = drawOver();
|
||||
// An item's own `recede` is not the contract's: it changes nothing.
|
||||
|
||||
@@ -158,6 +158,7 @@ export const CESIUM_CHECKS = new Set([
|
||||
'renderer.whenSettled',
|
||||
'renderer.resize',
|
||||
'frame.onHeldChange',
|
||||
'frame.onHoldsChange',
|
||||
'frame.setTargetFps',
|
||||
'globe.setTerrain',
|
||||
'globe.setPhotoreal',
|
||||
|
||||
@@ -96,6 +96,8 @@ export function cesiumCapabilities(scene, only) {
|
||||
// Cesium's AUTODETECT tracking frame (`follow.js`).
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
// Every hold and release is told (`onHoldsChange`).
|
||||
'holdChanges',
|
||||
// The zoom-out guard reads the scene's own controller and frame events.
|
||||
...(scene?.screenSpaceCameraController && scene?.preRender
|
||||
? ['keepEarthFramed']
|
||||
@@ -302,7 +304,10 @@ export function createCesiumPorts(
|
||||
const holds = new Map();
|
||||
// Told when the first hold is taken and the last released.
|
||||
const heldListeners = listenerList(report);
|
||||
// Told every hold taken or released.
|
||||
const holdsListeners = listenerList(report);
|
||||
function applyHolds() {
|
||||
holdsListeners.fire();
|
||||
const continuous = holds.size > 0;
|
||||
if (scene.requestRenderMode === !continuous) return;
|
||||
scene.requestRenderMode = !continuous;
|
||||
@@ -383,6 +388,9 @@ export function createCesiumPorts(
|
||||
};
|
||||
},
|
||||
onHeldChange: (cb) => heldListeners.on(cb),
|
||||
...(capabilities.has('holdChanges')
|
||||
? { onHoldsChange: (cb) => holdsListeners.on(cb) }
|
||||
: {}),
|
||||
/** Cesium can idle, so it draws on demand. */
|
||||
mode: () => 'demand',
|
||||
diagnostics: () => ({
|
||||
@@ -862,6 +870,7 @@ export function createCesiumPorts(
|
||||
for (const list of Object.values(rendererListeners)) list.clear();
|
||||
for (const list of Object.values(frameListeners)) list.clear();
|
||||
heldListeners.clear();
|
||||
holdsListeners.clear();
|
||||
drawPart.dispose();
|
||||
cameraPart.dispose();
|
||||
creditsPart.dispose();
|
||||
|
||||
@@ -15,6 +15,7 @@ test('capabilities follow what the scene supports', () => {
|
||||
'pointVisibility',
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
'holdChanges',
|
||||
'columns',
|
||||
'motionSegments',
|
||||
'courseGlide',
|
||||
|
||||
@@ -6618,6 +6618,26 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
|
||||
deepEqual(heard, [true, false], 'nothing once off');
|
||||
},
|
||||
),
|
||||
check(
|
||||
'frame.onHoldsChange',
|
||||
'onHoldsChange is told every hold and release, whoever holds, and nothing once off',
|
||||
(h, r) => {
|
||||
let heard = 0;
|
||||
const off = r.frame.onHoldsChange(() => (heard += 1));
|
||||
try {
|
||||
const one = r.frame.holdContinuous('conformance:one');
|
||||
const two = r.frame.holdContinuous('conformance:two');
|
||||
one();
|
||||
two();
|
||||
equal(heard, 4, 'two holds and two releases');
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
r.frame.holdContinuous('conformance:after')();
|
||||
equal(heard, 4, 'nothing once off');
|
||||
},
|
||||
{ capability: 'holdChanges' },
|
||||
),
|
||||
check(
|
||||
'frame.setTargetFps',
|
||||
'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate',
|
||||
|
||||
Vendored
+3
-1
@@ -228,4 +228,6 @@ export type Capability =
|
||||
/** Reading the frame the eye is placed in (`camera.followFrame`). */
|
||||
| 'followFrame'
|
||||
/** A `threshold` per `changed` listener (`camera.on`). */
|
||||
| 'cameraChangeThreshold';
|
||||
| 'cameraChangeThreshold'
|
||||
/** Hearing every hold taken or released (`frame.onHoldsChange`). */
|
||||
| 'holdChanges';
|
||||
Vendored
+14
-1
@@ -133,7 +133,20 @@ export interface SetSpec {
|
||||
* `live` (the default) is wall time minus `delayMs`, as a live feed is
|
||||
* drawn a little behind real time; `scene` is the frame port's scene time.
|
||||
*/
|
||||
motionClock?: { kind: 'live'; delayMs?: number } | { kind: 'scene' };
|
||||
motionClock?:
|
||||
| {
|
||||
kind: 'live';
|
||||
delayMs?: number;
|
||||
/**
|
||||
* Who asks for the frames moving rows need: the set itself, one after
|
||||
* another while a row moves (the default), or its `owner`, at the
|
||||
* rate the rows move on screen. An owner's set may also draw a
|
||||
* change written in place on the owner's next frame without asking
|
||||
* for one (the owner writes as a frame begins).
|
||||
*/
|
||||
frames?: 'set' | 'owner';
|
||||
}
|
||||
| { kind: 'scene' };
|
||||
show?: boolean;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+6
@@ -78,6 +78,12 @@ export interface FramePort {
|
||||
* it) and stop (its last released): `true` held, `false` not.
|
||||
*/
|
||||
onHeldChange(cb: (held: boolean) => void): Off;
|
||||
/**
|
||||
* `holdChanges`: hear every hold taken or released, whoever holds
|
||||
* (diagnostics' `holds` has changed), where `onHeldChange` hears only the
|
||||
* first hold and the last release.
|
||||
*/
|
||||
onHoldsChange?(cb: () => void): Off;
|
||||
mode(): 'demand' | 'continuous';
|
||||
diagnostics(): FrameDiagnostics;
|
||||
/** Stop ticking while the page is hidden; resume on `false`. */
|
||||
|
||||
@@ -55,6 +55,7 @@ export const CAPABILITIES = Object.freeze([
|
||||
'occlusionTest',
|
||||
'pointVisibility',
|
||||
'keepEarthFramed',
|
||||
'holdChanges',
|
||||
]);
|
||||
|
||||
/** @type {readonly import('./frame').FrameStep[]} */
|
||||
@@ -120,8 +121,8 @@ export const PORTS = deepFreeze({
|
||||
'destroy',
|
||||
),
|
||||
),
|
||||
frame: Object.fromEntries(
|
||||
required(
|
||||
frame: Object.fromEntries([
|
||||
...required(
|
||||
'on',
|
||||
'requestRender',
|
||||
'holdContinuous',
|
||||
@@ -135,7 +136,8 @@ export const PORTS = deepFreeze({
|
||||
'setTime',
|
||||
'time',
|
||||
),
|
||||
),
|
||||
['onHoldsChange', 'holdChanges'],
|
||||
]),
|
||||
globe: Object.fromEntries([
|
||||
...required(
|
||||
'setBase',
|
||||
|
||||
@@ -190,6 +190,16 @@ export function createStubRenderer(options = {}) {
|
||||
let holdSeq = 0;
|
||||
// Told when the first hold is taken and the last released.
|
||||
const heldListeners = new Set();
|
||||
const holdsListeners = new Set();
|
||||
function tellHolds() {
|
||||
for (const entry of [...holdsListeners])
|
||||
if (holdsListeners.has(entry))
|
||||
try {
|
||||
entry.cb();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
}
|
||||
function tellHeld(held) {
|
||||
for (const entry of [...heldListeners])
|
||||
try {
|
||||
@@ -359,9 +369,11 @@ export function createStubRenderer(options = {}) {
|
||||
const key = ++holdSeq;
|
||||
continuous.set(key, String(reason));
|
||||
if (continuous.size === 1) tellHeld(true);
|
||||
tellHolds();
|
||||
return () => {
|
||||
if (!continuous.delete(key)) return;
|
||||
if (continuous.size === 0) tellHeld(false);
|
||||
tellHolds();
|
||||
};
|
||||
},
|
||||
onHeldChange(cb) {
|
||||
@@ -369,6 +381,15 @@ export function createStubRenderer(options = {}) {
|
||||
heldListeners.add(entry);
|
||||
return () => heldListeners.delete(entry);
|
||||
},
|
||||
...(capabilities.has('holdChanges')
|
||||
? {
|
||||
onHoldsChange(cb) {
|
||||
const entry = { cb };
|
||||
holdsListeners.add(entry);
|
||||
return () => holdsListeners.delete(entry);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
mode: () => 'demand',
|
||||
diagnostics: () => ({
|
||||
mode: 'demand',
|
||||
|
||||
+140
-7
@@ -29,8 +29,13 @@
|
||||
* short stable strings ('flights', 'traffic', 'style-anim', …) so the
|
||||
* diagnostics read like a story.
|
||||
*
|
||||
* Frame rate: while the loop is held it draws at the display's own refresh
|
||||
* rate; while nothing holds it, the governor caps it at IDLE_FRAME_RATE,
|
||||
* Frame rate: a hold may say the most frames a second it needs
|
||||
* (`holdContinuousRender(owner, { maxFps })`); while held the loop draws at
|
||||
* the highest rate its holders asked for, and at the display's own refresh
|
||||
* rate as soon as one holder asked for none. Moving layers hold through
|
||||
* their pace (renderPace.js) at 15 to 30; a followed target counts as
|
||||
* FOLLOW_FRAME_RATE unless a pointer or the wheel is steering the camera.
|
||||
* While nothing holds it, the governor caps it at IDLE_FRAME_RATE,
|
||||
* because Cesium still ticks the clock, data sources and every
|
||||
* pre/post-update listener once per animation frame even when it skips the
|
||||
* draw. The frame port says when its first hold is taken and its last
|
||||
@@ -42,11 +47,19 @@
|
||||
* The governor is O(1) passive: no per-frame work of its own, ever.
|
||||
*/
|
||||
|
||||
import { PACE_MAX_HZ } from './renderPace.js';
|
||||
|
||||
/** @typedef {import('./render/contract/frame').FramePort} FramePort */
|
||||
/** @typedef {import('./render/contract/camera').CameraPort} CameraPort */
|
||||
|
||||
/** Frames a second the loop ticks while nothing moves. */
|
||||
export const IDLE_FRAME_RATE = 60;
|
||||
/**
|
||||
* Frames a second for a camera that only rides along with what it follows:
|
||||
* the most a moving layer draws (renderPace.js), leaving room in the frame
|
||||
* for everything else. The person steering it still gets the display's rate.
|
||||
*/
|
||||
export const FOLLOW_FRAME_RATE = PACE_MAX_HZ;
|
||||
|
||||
let _frame = null;
|
||||
/** Owners holding, each with the frame port's release once installed. */
|
||||
@@ -56,11 +69,108 @@ let _removeCameraListeners = null;
|
||||
/** Stops hearing the installed port's holds. */
|
||||
let _offHeldChange = null;
|
||||
|
||||
/** The loop's rate: the display's while held, IDLE_FRAME_RATE while not. */
|
||||
function applyRate(held) {
|
||||
_frame?.setTargetFps(held ? 0 : IDLE_FRAME_RATE);
|
||||
/** The most frames a second each owner said its hold needs; none: the display's. */
|
||||
const _rateOf = new Map();
|
||||
/**
|
||||
* Whether a pointer is down, or the wheel turned in the last moment: the
|
||||
* person is steering the camera. Kept apart, so the wheel's moment ending
|
||||
* never ends a drag.
|
||||
*/
|
||||
const _pointersDown = new Set();
|
||||
let _wheeling = false;
|
||||
let _steeringTimer = null;
|
||||
const steering = () => _pointersDown.size > 0 || _wheeling;
|
||||
|
||||
/**
|
||||
* The camera's own moves (a drag, a zoom, a flight) draw at the display's
|
||||
* rate. A camera carried by what it follows needs only the follow rate,
|
||||
* unless the person is steering it at the same time.
|
||||
*/
|
||||
function cameraRate() {
|
||||
return !steering() && _holds.has('tracked-entity') ? FOLLOW_FRAME_RATE : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rate while held: the highest any holder asked for, and the display's
|
||||
* (0) as soon as one holder asked for none. The renderer's own holds
|
||||
* (animated styles) ask for none; a frame port with `onHoldsChange` says
|
||||
* when one is taken or let go, and one without it is heard at the loop's
|
||||
* first hold and last release only.
|
||||
*/
|
||||
function heldRate() {
|
||||
let rate = 0;
|
||||
for (const owner of _frame.diagnostics().holds) {
|
||||
const asked = owner === 'camera' ? cameraRate() : _rateOf.get(owner);
|
||||
if (!asked) return 0;
|
||||
if (asked > rate) rate = asked;
|
||||
}
|
||||
return rate;
|
||||
}
|
||||
|
||||
/** The loop's rate: the holders' while held, IDLE_FRAME_RATE while not. */
|
||||
function applyRate(held = (_frame?.diagnostics().holds.length ?? 0) > 0) {
|
||||
_frame?.setTargetFps(held ? heldRate() : IDLE_FRAME_RATE);
|
||||
}
|
||||
|
||||
/** Change the steering inputs, and the rate if steering changed. */
|
||||
function changeSteering(change) {
|
||||
const was = steering();
|
||||
change();
|
||||
if (steering() !== was) applyRate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pointer and wheel input on the page: the person is steering the camera.
|
||||
* A release the page never hears (the pointer let go over another window)
|
||||
* ends when the page loses focus or is hidden.
|
||||
*/
|
||||
function watchSteering(target, { schedule, unschedule }) {
|
||||
if (typeof target?.addEventListener !== 'function') return null;
|
||||
// Every pointer down counts (a pinch is two), until it is let go.
|
||||
const down = (event) =>
|
||||
changeSteering(() => _pointersDown.add(event?.pointerId ?? 0));
|
||||
const up = (event) =>
|
||||
changeSteering(() => _pointersDown.delete(event?.pointerId ?? 0));
|
||||
const allUp = () => changeSteering(() => _pointersDown.clear());
|
||||
// The window's own blur, not an element's inside the page.
|
||||
const blur = (event) => {
|
||||
if (!event || event.target === target) allUp();
|
||||
};
|
||||
const wheel = () => {
|
||||
changeSteering(() => (_wheeling = true));
|
||||
if (_steeringTimer !== null) unschedule(_steeringTimer);
|
||||
_steeringTimer = schedule(() => {
|
||||
_steeringTimer = null;
|
||||
changeSteering(() => (_wheeling = false));
|
||||
}, 300);
|
||||
};
|
||||
const hidden = () => {
|
||||
if (globalThis.document?.visibilityState === 'hidden') allUp();
|
||||
};
|
||||
const options = { passive: true, capture: true };
|
||||
target.addEventListener('pointerdown', down, options);
|
||||
target.addEventListener('pointerup', up, options);
|
||||
target.addEventListener('pointercancel', up, options);
|
||||
target.addEventListener('blur', blur, options);
|
||||
target.addEventListener('wheel', wheel, options);
|
||||
const doc = globalThis.document;
|
||||
doc?.addEventListener?.('visibilitychange', hidden);
|
||||
return () => {
|
||||
target.removeEventListener('pointerdown', down, options);
|
||||
target.removeEventListener('pointerup', up, options);
|
||||
target.removeEventListener('pointercancel', up, options);
|
||||
target.removeEventListener('blur', blur, options);
|
||||
target.removeEventListener('wheel', wheel, options);
|
||||
doc?.removeEventListener?.('visibilitychange', hidden);
|
||||
if (_steeringTimer !== null) unschedule(_steeringTimer);
|
||||
_steeringTimer = null;
|
||||
_pointersDown.clear();
|
||||
_wheeling = false;
|
||||
};
|
||||
}
|
||||
/** Stops hearing the pointer and the wheel. */
|
||||
let _removeSteeringListeners = null;
|
||||
|
||||
/** Debug trail of the most recent one-shot render requests (idle mode only). */
|
||||
const _recentRequests = [];
|
||||
const RECENT_REQUEST_CAP = 16;
|
||||
@@ -185,11 +295,21 @@ export function installRenderGovernor(
|
||||
if (_frame) releaseFrameHolds();
|
||||
_offHeldChange?.();
|
||||
_frame = frame;
|
||||
_offHeldChange = frame.onHeldChange(applyRate);
|
||||
const offHeld = frame.onHeldChange(applyRate);
|
||||
const offHolds = frame.onHoldsChange?.(() => applyRate()) ?? null;
|
||||
_offHeldChange = () => {
|
||||
offHeld();
|
||||
offHolds?.();
|
||||
};
|
||||
applyRate(frame.diagnostics().holds.length > 0);
|
||||
for (const ownerId of _holds.keys()) holdOnFrame(ownerId);
|
||||
}
|
||||
_removeCameraListeners = watchCameraMotion(camera, { schedule, unschedule });
|
||||
_removeSteeringListeners?.();
|
||||
_removeSteeringListeners = watchSteering(globalThis.window, {
|
||||
schedule,
|
||||
unschedule,
|
||||
});
|
||||
}
|
||||
|
||||
function releaseFrameHolds() {
|
||||
@@ -206,10 +326,15 @@ function releaseFrameHolds() {
|
||||
* @param {string} ownerId Short stable id, e.g. 'flights', 'traffic'.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function holdContinuousRender(ownerId) {
|
||||
export function holdContinuousRender(ownerId, { maxFps = 0 } = {}) {
|
||||
if (!ownerId) return;
|
||||
if (maxFps > 0) _rateOf.set(ownerId, maxFps);
|
||||
else _rateOf.delete(ownerId);
|
||||
if (!_holds.has(ownerId)) _holds.set(ownerId, null);
|
||||
holdOnFrame(ownerId);
|
||||
// A second holder, or a new rate, changes the rate without changing
|
||||
// whether the loop is held.
|
||||
applyRate();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,7 +348,9 @@ export function releaseContinuousRender(ownerId) {
|
||||
if (!ownerId || !_holds.has(ownerId)) return;
|
||||
const release = _holds.get(ownerId);
|
||||
_holds.delete(ownerId);
|
||||
_rateOf.delete(ownerId);
|
||||
release?.();
|
||||
applyRate();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -262,11 +389,14 @@ export function uninstallRenderGovernor(frame) {
|
||||
if (!_frame || _frame !== frame) return;
|
||||
_removeCameraListeners?.();
|
||||
_removeCameraListeners = null;
|
||||
_removeSteeringListeners?.();
|
||||
_removeSteeringListeners = null;
|
||||
releaseFrameHolds();
|
||||
_offHeldChange?.();
|
||||
_offHeldChange = null;
|
||||
_frame = null;
|
||||
_holds.clear();
|
||||
_rateOf.clear();
|
||||
_recentRequests.length = 0;
|
||||
}
|
||||
|
||||
@@ -274,9 +404,12 @@ export function uninstallRenderGovernor(frame) {
|
||||
export function _resetRenderGovernorForTest() {
|
||||
_removeCameraListeners?.();
|
||||
_removeCameraListeners = null;
|
||||
_removeSteeringListeners?.();
|
||||
_removeSteeringListeners = null;
|
||||
_offHeldChange?.();
|
||||
_offHeldChange = null;
|
||||
_frame = null;
|
||||
_holds.clear();
|
||||
_rateOf.clear();
|
||||
_recentRequests.length = 0;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
_resetRenderGovernorForTest,
|
||||
uninstallRenderGovernor,
|
||||
IDLE_FRAME_RATE,
|
||||
FOLLOW_FRAME_RATE,
|
||||
} from './renderGovernor.js';
|
||||
import { framePortFor } from './testSupport/fakeFramePort.mjs';
|
||||
|
||||
@@ -293,3 +294,126 @@ test('installing again drops a camera hold the old listeners can no longer relea
|
||||
assert.equal(scene.requestRenderMode, true);
|
||||
assert.equal(timers.pending, 0);
|
||||
});
|
||||
|
||||
test('a hold may cap the rate: the highest asked wins, an uncapped hold is the display rate', () => {
|
||||
const { viewer, scene } = makeViewer();
|
||||
const frame = framePortFor(viewer.scene);
|
||||
installRenderGovernor(frame);
|
||||
holdContinuousRender('satellites', { maxFps: 15 });
|
||||
assert.equal(scene.targetFps, 15);
|
||||
holdContinuousRender('flights', { maxFps: 30 });
|
||||
assert.equal(scene.targetFps, 30, 'the highest asked');
|
||||
holdContinuousRender('flights', { maxFps: 20 });
|
||||
assert.equal(scene.targetFps, 20, 'a holder lowering its rate');
|
||||
holdContinuousRender('traffic');
|
||||
assert.equal(scene.targetFps, 0, 'a hold without a rate: the display rate');
|
||||
releaseContinuousRender('traffic');
|
||||
assert.equal(scene.targetFps, 20);
|
||||
releaseContinuousRender('flights');
|
||||
assert.equal(scene.targetFps, 15);
|
||||
releaseContinuousRender('satellites');
|
||||
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
|
||||
});
|
||||
|
||||
test('the renderer holding the loop itself asks for no rate: the display rate', () => {
|
||||
const { viewer, scene } = makeViewer();
|
||||
const frame = framePortFor(viewer.scene);
|
||||
installRenderGovernor(frame);
|
||||
const release = frame.holdContinuous('effects:animated');
|
||||
holdContinuousRender('satellites', { maxFps: 15 });
|
||||
assert.equal(scene.targetFps, 0);
|
||||
release();
|
||||
assert.equal(scene.targetFps, 15, 'heard as soon as the renderer lets go');
|
||||
const again = frame.holdContinuous('effects:animated');
|
||||
assert.equal(scene.targetFps, 0, 'and as soon as it holds again');
|
||||
again();
|
||||
releaseContinuousRender('satellites');
|
||||
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
|
||||
});
|
||||
|
||||
test('a camera carried by a followed target draws at the follow rate unless a pointer steers it', () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const page = new EventTarget();
|
||||
globalThis.window = page;
|
||||
try {
|
||||
const { viewer, scene } = makeViewer();
|
||||
const camera = makeCamera();
|
||||
installRenderGovernor(framePortFor(viewer.scene), { camera });
|
||||
camera.raise('moveStart');
|
||||
assert.equal(scene.targetFps, 0, 'a camera move: the display rate');
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE, 'following');
|
||||
assert.equal(FOLLOW_FRAME_RATE, 30);
|
||||
page.dispatchEvent(new Event('pointerdown'));
|
||||
assert.equal(scene.targetFps, 0, 'steering: the display rate');
|
||||
page.dispatchEvent(new Event('pointerup'));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
|
||||
releaseContinuousRender('tracked-entity');
|
||||
assert.equal(scene.targetFps, 0, 'the camera moving on its own');
|
||||
camera.raise('moveEnd');
|
||||
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
|
||||
} finally {
|
||||
_resetRenderGovernorForTest();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
}
|
||||
});
|
||||
|
||||
test('steering ends when the page loses focus, and a wheel moment ending never ends a drag', () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const page = new EventTarget();
|
||||
globalThis.window = page;
|
||||
try {
|
||||
const timers = fakeTimers();
|
||||
const { viewer, scene } = makeViewer();
|
||||
installRenderGovernor(framePortFor(viewer.scene), timers);
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
holdContinuousRender('camera');
|
||||
page.dispatchEvent(new Event('pointerdown'));
|
||||
assert.equal(scene.targetFps, 0, 'dragging: the display rate');
|
||||
// Let go over another window: the page never hears the release.
|
||||
page.dispatchEvent(new Event('blur'));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE, 'focus lost: steering ends');
|
||||
// A wheel turn, then a drag begun before its moment ends.
|
||||
page.dispatchEvent(new Event('wheel'));
|
||||
page.dispatchEvent(new Event('pointerdown'));
|
||||
timers.run();
|
||||
assert.equal(scene.targetFps, 0, 'the drag goes on at the display rate');
|
||||
page.dispatchEvent(new Event('pointerup'));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
|
||||
} finally {
|
||||
_resetRenderGovernorForTest();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
}
|
||||
});
|
||||
|
||||
test('a pinch steers until its last finger lifts; an element losing focus is not the page losing it', () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const page = new EventTarget();
|
||||
globalThis.window = page;
|
||||
try {
|
||||
const { viewer, scene } = makeViewer();
|
||||
installRenderGovernor(framePortFor(viewer.scene), fakeTimers());
|
||||
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
|
||||
holdContinuousRender('camera');
|
||||
const pointer = (type, pointerId) => Object.assign(new Event(type), { pointerId });
|
||||
page.dispatchEvent(pointer('pointerdown', 1));
|
||||
page.dispatchEvent(pointer('pointerdown', 2));
|
||||
page.dispatchEvent(pointer('pointerup', 1));
|
||||
assert.equal(scene.targetFps, 0, 'one finger still down');
|
||||
// The search box's blur reaches the window's capturing listener.
|
||||
const field = new EventTarget();
|
||||
field.addEventListener('blur', () => {});
|
||||
const blur = new Event('blur');
|
||||
Object.defineProperty(blur, 'target', { value: field });
|
||||
page.dispatchEvent(blur);
|
||||
assert.equal(scene.targetFps, 0, 'still steering');
|
||||
page.dispatchEvent(pointer('pointerup', 2));
|
||||
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
|
||||
} finally {
|
||||
_resetRenderGovernorForTest();
|
||||
if (previousWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = previousWindow;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Draws a moving layer as often as its marks move on screen, in place of a
|
||||
* hold on the render loop for as long as the layer is on.
|
||||
*
|
||||
* A mark should move at most PACE_STEP_PX between two draws, so a layer
|
||||
* needs `fastest on-screen speed / PACE_STEP_PX` draws a second. The pace
|
||||
* keeps that between PACE_MIN_HZ (animated marks never stall) and
|
||||
* PACE_MAX_HZ (room in the frame for everything else the scene draws).
|
||||
* Below PACE_HOLD_HZ it asks for one frame at a time on a timer, so the
|
||||
* loop stays on demand; from there it holds the loop at a rate the display
|
||||
* divides evenly (the render governor's rate per hold).
|
||||
*
|
||||
* The person steering the camera still draws at the display's rate: that is
|
||||
* the camera's hold, not a layer's (see renderGovernor.js).
|
||||
*/
|
||||
|
||||
/** The most a mark may move on screen between two draws, in pixels. */
|
||||
export const PACE_STEP_PX = 0.5;
|
||||
/** Draws a second however slowly the marks move. */
|
||||
export const PACE_MIN_HZ = 3;
|
||||
/** Draws a second however fast the marks move. */
|
||||
export const PACE_MAX_HZ = 30;
|
||||
/** From this many draws a second the pace holds the loop instead. */
|
||||
export const PACE_HOLD_HZ = 12;
|
||||
/** Below this the hold is let go again (a gap, so it does not flap; above
|
||||
* ROTOR_FPS, so a turning rotor alone draws on the timer at its own rate). */
|
||||
export const PACE_RELEASE_HZ = 11;
|
||||
/** Held rates, each dividing 60 and 120 evenly so draws come at even gaps. */
|
||||
const HELD_RATES = [15, 20, 30];
|
||||
|
||||
/** Draws a second for marks crossing the screen at `pxPerSec`. */
|
||||
export function paceHzForSpeed(pxPerSec) {
|
||||
return pxPerSec / PACE_STEP_PX;
|
||||
}
|
||||
|
||||
/** The held rate for a need of `hz` draws a second. */
|
||||
function heldRateFor(hz) {
|
||||
for (const rate of HELD_RATES) if (hz <= rate) return rate;
|
||||
return PACE_MAX_HZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {string} options.owner The hold's owner id ('flights', 'satellites').
|
||||
* @param {object} [options.render] The render governor's calls
|
||||
* (holdContinuousRender, releaseContinuousRender, governorRequestRender).
|
||||
* @param {Function} [options.setTimeout] Injectable timers for tests.
|
||||
* @param {Function} [options.clearTimeout]
|
||||
* @param {() => number} [options.now] Injectable wall clock (ms) for tests.
|
||||
*/
|
||||
export function createRenderPace({
|
||||
owner,
|
||||
render,
|
||||
setTimeout: schedule = globalThis.setTimeout,
|
||||
clearTimeout: unschedule = globalThis.clearTimeout,
|
||||
now = () => globalThis.performance?.now() ?? Date.now(),
|
||||
}) {
|
||||
const hold = render?.holdContinuousRender ?? (() => {});
|
||||
const release = render?.releaseContinuousRender ?? (() => {});
|
||||
const request = render?.governorRequestRender ?? (() => {});
|
||||
let running = false;
|
||||
let hz = PACE_MIN_HZ;
|
||||
let held = false;
|
||||
/** The rate the hold asked for, or -1 while not held. */
|
||||
let heldFps = -1;
|
||||
let timer = null;
|
||||
let timerHz = 0;
|
||||
/** Whether the timer's wait ended: the marks move on the next frame. */
|
||||
let due = false;
|
||||
/** Wall ms the marks last moved. */
|
||||
let movedMs = -Infinity;
|
||||
|
||||
function arm() {
|
||||
if (!running || held) return;
|
||||
if (timer !== null) {
|
||||
// A pending wait at a much slower rate is cut short.
|
||||
if (hz <= timerHz * 1.5) return;
|
||||
unschedule(timer);
|
||||
}
|
||||
timerHz = hz;
|
||||
timer = schedule(() => {
|
||||
timer = null;
|
||||
due = true;
|
||||
request(owner);
|
||||
arm();
|
||||
}, 1000 / hz);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the draws a second needed now (any number: it is clamped to the
|
||||
* pace's range; Infinity asks for the most). Called once a drawn frame.
|
||||
*/
|
||||
function set(needHz) {
|
||||
if (!running) return;
|
||||
const clamped = Math.min(
|
||||
PACE_MAX_HZ,
|
||||
needHz >= PACE_MIN_HZ ? needHz : PACE_MIN_HZ,
|
||||
);
|
||||
// Up at once, down gently: the fastest mark leaving the view is no
|
||||
// reason to step the next one.
|
||||
hz = clamped >= hz ? clamped : Math.max(clamped, hz * 0.9);
|
||||
const wantHold = held ? hz >= PACE_RELEASE_HZ : hz >= PACE_HOLD_HZ;
|
||||
if (wantHold) {
|
||||
const maxFps = heldRateFor(hz);
|
||||
if (!held || maxFps !== heldFps) hold(owner, { maxFps });
|
||||
heldFps = maxFps;
|
||||
if (timer !== null) unschedule(timer);
|
||||
timer = null;
|
||||
} else if (held) {
|
||||
release(owner);
|
||||
heldFps = -1;
|
||||
}
|
||||
held = wantHold;
|
||||
arm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the layer's marks should move in this frame, for a layer that
|
||||
* moves them itself (moving them asks for a frame, so a layer moving them
|
||||
* on every drawn frame keeps the loop drawing). Marks the move when true.
|
||||
*/
|
||||
function take() {
|
||||
const at = now();
|
||||
if (!running || held || due || at - movedMs >= 1000 / hz) {
|
||||
due = false;
|
||||
movedMs = at;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (running) return;
|
||||
running = true;
|
||||
// Until the first frame says what is needed.
|
||||
hz = PACE_RELEASE_HZ;
|
||||
due = true;
|
||||
movedMs = -Infinity;
|
||||
request(owner);
|
||||
arm();
|
||||
}
|
||||
|
||||
function stop() {
|
||||
running = false;
|
||||
if (timer !== null) unschedule(timer);
|
||||
timer = null;
|
||||
held = false;
|
||||
heldFps = -1;
|
||||
due = false;
|
||||
release(owner);
|
||||
}
|
||||
|
||||
return {
|
||||
set,
|
||||
take,
|
||||
start,
|
||||
stop,
|
||||
state: () => ({ running, hz, held, heldFps }),
|
||||
};
|
||||
}
|
||||
|
||||
/** cos 60°: marks further than this from the view's axis are not read. */
|
||||
const VIEW_COS = 0.5;
|
||||
|
||||
/**
|
||||
* Reads how fast the fastest mark crosses the screen, from each mark's move
|
||||
* as an angle at the eye. Use: `begin` with the camera, `add` each mark's
|
||||
* two positions (ECEF), then `pxPerSec` with the time between them.
|
||||
* The flat screen stretches an angle away from its centre by 1 / cos², so
|
||||
* that is applied too.
|
||||
*/
|
||||
export function createScreenSpeed() {
|
||||
let eye = null;
|
||||
let dir = null;
|
||||
let ex = 0;
|
||||
let ey = 0;
|
||||
let ez = 0;
|
||||
let focal = 0;
|
||||
let fastest2 = 0;
|
||||
|
||||
return {
|
||||
/**
|
||||
* @param {{position: {x,y,z}, direction: {x,y,z}, fovy: number}|null} pose
|
||||
* @param {number} heightPx The canvas's height in CSS pixels.
|
||||
* @param {{x,y,z}} [eyeMove] How far the eye itself moved between the
|
||||
* two positions: a camera riding one mark sees its neighbours nearly
|
||||
* still.
|
||||
* @returns {boolean} Whether there is a camera to read with.
|
||||
*/
|
||||
begin(pose, heightPx, eyeMove = null) {
|
||||
fastest2 = 0;
|
||||
eye = pose?.position ?? null;
|
||||
dir = pose?.direction ?? null;
|
||||
if (!eye || !dir || !(pose.fovy > 0)) {
|
||||
eye = null;
|
||||
return false;
|
||||
}
|
||||
ex = eyeMove?.x ?? 0;
|
||||
ey = eyeMove?.y ?? 0;
|
||||
ez = eyeMove?.z ?? 0;
|
||||
focal = (heightPx || 900) / 2 / Math.tan(pose.fovy / 2);
|
||||
return true;
|
||||
},
|
||||
/** One mark's move from `from` to `to` (ECEF metres). */
|
||||
add(from, to) {
|
||||
if (!eye || !from || !to) return;
|
||||
const dx = to.x - eye.x;
|
||||
const dy = to.y - eye.y;
|
||||
const dz = to.z - eye.z;
|
||||
const range2 = dx * dx + dy * dy + dz * dz;
|
||||
const along = dx * dir.x + dy * dir.y + dz * dir.z;
|
||||
if (!(along > 0) || along * along < VIEW_COS * VIEW_COS * range2) return;
|
||||
const mx = to.x - from.x - ex;
|
||||
const my = to.y - from.y - ey;
|
||||
const mz = to.z - from.z - ez;
|
||||
// The angle the move subtends, stretched by 1 / cos² off the centre.
|
||||
const turn2 =
|
||||
((mx * mx + my * my + mz * mz) * range2) /
|
||||
(along * along * along * along);
|
||||
if (turn2 > fastest2) fastest2 = turn2;
|
||||
},
|
||||
/** The fastest mark's on-screen speed, for moves `seconds` apart. */
|
||||
pxPerSec(seconds) {
|
||||
if (!eye || !(seconds > 0)) return 0;
|
||||
return (Math.sqrt(fastest2) * focal) / seconds;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createRenderPace,
|
||||
createScreenSpeed,
|
||||
paceHzForSpeed,
|
||||
PACE_MAX_HZ,
|
||||
PACE_MIN_HZ,
|
||||
PACE_STEP_PX,
|
||||
} from './renderPace.js';
|
||||
|
||||
/** A pace with fake timers, clock and render calls. */
|
||||
function makePace() {
|
||||
const calls = [];
|
||||
const timers = new Map();
|
||||
let nextId = 1;
|
||||
let nowMs = 0;
|
||||
const pace = createRenderPace({
|
||||
owner: 'dots',
|
||||
render: {
|
||||
holdContinuousRender: (owner, options) =>
|
||||
calls.push(['hold', owner, options.maxFps]),
|
||||
releaseContinuousRender: (owner) => calls.push(['release', owner]),
|
||||
governorRequestRender: (owner) => calls.push(['request', owner]),
|
||||
},
|
||||
setTimeout(fn, ms) {
|
||||
const id = nextId++;
|
||||
timers.set(id, { fn, ms });
|
||||
return id;
|
||||
},
|
||||
clearTimeout: (id) => timers.delete(id),
|
||||
now: () => nowMs,
|
||||
});
|
||||
return {
|
||||
pace,
|
||||
calls,
|
||||
timers,
|
||||
advance(ms) {
|
||||
nowMs += ms;
|
||||
},
|
||||
fire() {
|
||||
const [id, timer] = [...timers][0];
|
||||
timers.delete(id);
|
||||
timer.fn();
|
||||
return timer.ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('a mark may move half a pixel between draws', () => {
|
||||
assert.equal(PACE_STEP_PX, 0.5);
|
||||
assert.equal(paceHzForSpeed(1), 2);
|
||||
assert.equal(paceHzForSpeed(10), 20);
|
||||
});
|
||||
|
||||
test('slow marks are drawn three times a second, one frame at a time', () => {
|
||||
const { pace, calls, timers, fire } = makePace();
|
||||
pace.start();
|
||||
pace.set(0.2);
|
||||
pace.set(0.2);
|
||||
// From the starting rate it eases down, never below the floor.
|
||||
for (let i = 0; i < 40; i++) pace.set(0.2);
|
||||
assert.equal(pace.state().hz, PACE_MIN_HZ);
|
||||
assert.equal(pace.state().held, false);
|
||||
assert.ok(timers.size === 1, 'one wait out');
|
||||
// The wait out from the start runs out, then the next is at the floor.
|
||||
fire();
|
||||
assert.equal(fire(), 1000 / PACE_MIN_HZ);
|
||||
assert.deepEqual(calls.at(-1), ['request', 'dots']);
|
||||
assert.ok(!calls.some(([kind]) => kind === 'hold'));
|
||||
});
|
||||
|
||||
test('fast marks hold the loop at a rate the display divides, never above 30', () => {
|
||||
const { pace, calls, timers } = makePace();
|
||||
pace.start();
|
||||
pace.set(13);
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'dots', 15]);
|
||||
assert.equal(timers.size, 0, 'held: no waits');
|
||||
pace.set(18);
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'dots', 20]);
|
||||
pace.set(500);
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'dots', PACE_MAX_HZ]);
|
||||
assert.equal(pace.state().hz, PACE_MAX_HZ);
|
||||
pace.set(Infinity);
|
||||
assert.equal(pace.state().heldFps, PACE_MAX_HZ);
|
||||
// The same rate again asks the governor for nothing.
|
||||
const before = calls.length;
|
||||
pace.set(40);
|
||||
assert.equal(calls.length, before);
|
||||
});
|
||||
|
||||
test('the hold is let go below the release rate, not at the hold rate', () => {
|
||||
const { pace, calls } = makePace();
|
||||
pace.start();
|
||||
pace.set(14);
|
||||
assert.equal(pace.state().held, true);
|
||||
// Down gently: a tenth a frame at most.
|
||||
for (let i = 0; i < 2; i++) pace.set(10);
|
||||
assert.equal(pace.state().held, true, 'still above the release rate');
|
||||
for (let i = 0; i < 20; i++) pace.set(1);
|
||||
assert.equal(pace.state().held, false);
|
||||
assert.ok(calls.some(([kind]) => kind === 'release'));
|
||||
});
|
||||
|
||||
test('marks a layer moves itself move at the pace, and on every frame while held', () => {
|
||||
const { pace, advance, fire } = makePace();
|
||||
pace.start();
|
||||
assert.equal(pace.take(), true, 'first frame moves');
|
||||
assert.equal(pace.take(), false, 'same instant: no move');
|
||||
for (let i = 0; i < 40; i++) pace.set(0);
|
||||
advance(100);
|
||||
assert.equal(pace.take(), false, 'too soon at three a second');
|
||||
fire();
|
||||
assert.equal(pace.take(), true, 'the wait ended');
|
||||
advance(1000 / PACE_MIN_HZ);
|
||||
assert.equal(pace.take(), true, 'a third of a second on');
|
||||
pace.set(30);
|
||||
assert.equal(pace.take(), true);
|
||||
assert.equal(pace.take(), true, 'held: every drawn frame');
|
||||
});
|
||||
|
||||
test('stopping lets the hold go and ends the waits; a stopped pace moves every frame', () => {
|
||||
const { pace, calls, timers } = makePace();
|
||||
pace.start();
|
||||
pace.set(25);
|
||||
pace.stop();
|
||||
assert.deepEqual(calls.at(-1), ['release', 'dots']);
|
||||
assert.equal(timers.size, 0);
|
||||
pace.set(25);
|
||||
assert.equal(pace.state().held, false, 'set does nothing once stopped');
|
||||
assert.equal(pace.take(), true);
|
||||
assert.equal(pace.take(), true);
|
||||
});
|
||||
|
||||
/** A camera at `z` metres up the z axis looking down it, 60° field. */
|
||||
function poseAt(z) {
|
||||
return {
|
||||
position: { x: 0, y: 0, z },
|
||||
direction: { x: 0, y: 0, z: -1 },
|
||||
fovy: Math.PI / 3,
|
||||
};
|
||||
}
|
||||
|
||||
test('screen speed: a move across the view axis, from its angle at the eye', () => {
|
||||
const speed = createScreenSpeed();
|
||||
assert.equal(speed.begin(poseAt(1000), 1000), true);
|
||||
// 10 m sideways at 1 km ahead, over one second.
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 10, y: 0, z: 0 });
|
||||
const focal = 500 / Math.tan(Math.PI / 6);
|
||||
// Measured at the move's end: 10 m off-axis, a hair off-centre.
|
||||
const px = speed.pxPerSec(1);
|
||||
assert.ok(Math.abs(px - (10 / 1000) * focal) / px < 0.001, `${px}`);
|
||||
assert.ok(Math.abs(speed.pxPerSec(2) - px / 2) < 1e-9);
|
||||
});
|
||||
|
||||
test('screen speed: the fastest mark counts, marks behind or far off-axis do not', () => {
|
||||
const speed = createScreenSpeed();
|
||||
speed.begin(poseAt(1000), 1000);
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 5, y: 0, z: 0 });
|
||||
// Behind the eye.
|
||||
speed.add({ x: 0, y: 0, z: 2000 }, { x: 500, y: 0, z: 2000 });
|
||||
// 80° off the axis.
|
||||
speed.add({ x: 5000, y: 0, z: 900 }, { x: 5500, y: 0, z: 900 });
|
||||
const focal = 500 / Math.tan(Math.PI / 6);
|
||||
assert.ok(Math.abs(speed.pxPerSec(1) - (5 / 1000) * focal) < 0.01);
|
||||
});
|
||||
|
||||
test('screen speed: a mark moving with the eye stands still on screen', () => {
|
||||
const speed = createScreenSpeed();
|
||||
speed.begin(poseAt(1000), 1000, { x: 7, y: 0, z: 0 });
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 7, y: 0, z: 0 });
|
||||
assert.equal(speed.pxPerSec(1), 0);
|
||||
});
|
||||
|
||||
test('screen speed: no camera, no reading', () => {
|
||||
const speed = createScreenSpeed();
|
||||
assert.equal(speed.begin(null, 900), false);
|
||||
speed.add({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });
|
||||
assert.equal(speed.pxPerSec(1), 0);
|
||||
});
|
||||
|
||||
test('a need of ten a second, once held, falls back to single frames at ten', () => {
|
||||
const { pace, timers } = makePace();
|
||||
pace.start();
|
||||
pace.set(30);
|
||||
for (let i = 0; i < 40; i++) pace.set(10);
|
||||
assert.equal(pace.state().held, false);
|
||||
assert.equal(Math.round(pace.state().hz), 10);
|
||||
assert.equal(timers.size, 1);
|
||||
});
|
||||
+4
-13
@@ -126,8 +126,6 @@ export class ShareLinkManager {
|
||||
this._panelStateProvider = null;
|
||||
this._styleParamStateProvider = null;
|
||||
this._initialRestorePending = false;
|
||||
// Who holds the hash writes (holdWrites).
|
||||
this._writeHolds = new Set();
|
||||
// Each incoming share (start-up or a later hash navigation) gets a token;
|
||||
// only the newest one may release URL-write suppression.
|
||||
this._restoreToken = 0;
|
||||
@@ -728,12 +726,10 @@ export class ShareLinkManager {
|
||||
/**
|
||||
* Hold the address's hash writes, for an owner that covers the view and
|
||||
* keeps the person's camera and layers out of the address while it does
|
||||
* (Stories, the opening's flight). Each `owner` holds and releases its own
|
||||
* hold; once none holds, the current view is written again.
|
||||
* (Stories). Releasing writes the current view again.
|
||||
* @param {boolean} held
|
||||
* @param {string} [owner]
|
||||
*/
|
||||
holdWrites(held, owner = 'stories') {
|
||||
holdWrites(held) {
|
||||
if (held && !this._writesHeld && this._debounceTimer) {
|
||||
// A view change still waiting for its debounce is written first, so
|
||||
// the address the owner saves is the live view.
|
||||
@@ -741,16 +737,11 @@ export class ShareLinkManager {
|
||||
this._debounceTimer = null;
|
||||
this._updateHash();
|
||||
}
|
||||
if (held) this._writeHolds.add(owner);
|
||||
else this._writeHolds.delete(owner);
|
||||
if (!this._writesHeld) this._scheduleUpdate();
|
||||
this._writesHeld = !!held;
|
||||
if (!held) this._scheduleUpdate();
|
||||
else clearTimeout(this._debounceTimer);
|
||||
}
|
||||
|
||||
get _writesHeld() {
|
||||
return this._writeHolds.size > 0;
|
||||
}
|
||||
|
||||
_scheduleUpdate() {
|
||||
if (this._destroyed || this._initialRestorePending || this._writesHeld)
|
||||
return;
|
||||
|
||||
@@ -193,21 +193,6 @@ test('holding writes first writes a view change still waiting for its debounce',
|
||||
manager.destroy();
|
||||
});
|
||||
|
||||
test('each owner releases only its own hold on writes', (t) => {
|
||||
installTab(t, SHARE_A);
|
||||
const timers = installManualTimers(t);
|
||||
const manager = new ShareLinkManager(bindFakeCesiumCamera(fakeViewer()));
|
||||
manager.completeInitialRestore(manager.parseInitialHash().restoreToken);
|
||||
manager.holdWrites(true, 'opening');
|
||||
manager.holdWrites(true);
|
||||
manager.holdWrites(false, 'opening');
|
||||
manager._scheduleUpdate();
|
||||
assert.equal(timers.size, 0, 'Stories still holds them');
|
||||
manager.holdWrites(false);
|
||||
assert.equal(timers.size, 1, 'written again once none holds');
|
||||
manager.destroy();
|
||||
});
|
||||
|
||||
test('a hash write keeps the state another owner stored on the entry', (t) => {
|
||||
installTab(t, SHARE_A);
|
||||
const written = [];
|
||||
|
||||
Vendored
-3
@@ -1,11 +1,8 @@
|
||||
import { createApplicationControls } from '../app/controls.js';
|
||||
import { getStandaloneCatalog } from './catalog.js';
|
||||
import { homeCountryView } from '../homeCountry.js';
|
||||
export function createStandaloneControls(options) {
|
||||
return createApplicationControls({
|
||||
catalog: options?.catalog ?? getStandaloneCatalog(),
|
||||
// The planet over the visitor's country; the title's logo goes back here.
|
||||
startView: homeCountryView(),
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,16 +1,8 @@
|
||||
import { startApplicationChrome } from '../app/startupChrome.js';
|
||||
import { playOpeningIntro } from '../app/openingIntro.js';
|
||||
import { initKeySetup } from '../keySetup.js';
|
||||
import { streetLevelFromParams } from '../view/index.js';
|
||||
export function startStandaloneChrome(options) {
|
||||
// A Street Level link opens its photos at its view, so it plays no
|
||||
// opening. Read now: the address is rewritten once the link restores.
|
||||
const streetLevel = streetLevelFromParams(
|
||||
new URLSearchParams(globalThis.location?.hash.slice(1) ?? ''),
|
||||
);
|
||||
return startApplicationChrome({
|
||||
initializeSettings: initKeySetup,
|
||||
playOpening: streetLevel ? null : playOpeningIntro,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -10,12 +10,7 @@ const source = readFileSync(
|
||||
.replace(/^import .*;\n/gm, '')
|
||||
.replace('export function', 'function');
|
||||
|
||||
function fixture({
|
||||
playOpening,
|
||||
hasShareState = false,
|
||||
shareLink,
|
||||
navigationGeneration,
|
||||
} = {}) {
|
||||
function fixture() {
|
||||
const timers = new Map();
|
||||
const listeners = new Map();
|
||||
const events = [];
|
||||
@@ -42,15 +37,6 @@ function fixture({
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(source, context);
|
||||
const styleManager = {
|
||||
_navigationGeneration: navigationGeneration,
|
||||
hasShareState,
|
||||
viewer: 'viewer',
|
||||
shareLinkManager: shareLink,
|
||||
initialRestorePromise: new Promise((resolve) => {
|
||||
restored = resolve;
|
||||
}),
|
||||
};
|
||||
const stop = context.startApplicationChrome({
|
||||
initializeSettings: context.initKeySetup,
|
||||
loadingScreen: {
|
||||
@@ -58,14 +44,16 @@ function fixture({
|
||||
addEventListener: (type, listener) => listeners.set(type, listener),
|
||||
removeEventListener: (type) => listeners.delete(type),
|
||||
},
|
||||
playOpening,
|
||||
styleManager,
|
||||
styleManager: {
|
||||
initialRestorePromise: new Promise((resolve) => {
|
||||
restored = resolve;
|
||||
}),
|
||||
},
|
||||
dataManager: {},
|
||||
signal: controller.signal,
|
||||
});
|
||||
return {
|
||||
events,
|
||||
styleManager,
|
||||
listeners,
|
||||
stop,
|
||||
restored,
|
||||
@@ -136,180 +124,3 @@ test('shutdown during the cover transition cancels the listener and fallback', a
|
||||
f.fire(900);
|
||||
assert.deepEqual(f.events, ['hidden', 'settings:destroy']);
|
||||
});
|
||||
|
||||
function openingStub(events) {
|
||||
let land;
|
||||
const calls = [];
|
||||
const play = (options) => {
|
||||
calls.push(options);
|
||||
events.push('opening');
|
||||
return {
|
||||
done: new Promise((resolve) => {
|
||||
land = resolve;
|
||||
}),
|
||||
cancel: () => events.push('opening:cancel'),
|
||||
};
|
||||
};
|
||||
return { play, calls, land: () => land() };
|
||||
}
|
||||
|
||||
test('a bare address plays the opening, and welcome waits for its end', async () => {
|
||||
const events = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({ playOpening: opening.play });
|
||||
f.events.push = (value) => events.push(value);
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(events, ['opening']);
|
||||
assert.equal(opening.calls[0].viewer, 'viewer');
|
||||
f.fire(900);
|
||||
assert.deepEqual(events, ['opening'], 'no fallback timer while it plays');
|
||||
f.listeners.get('transitionend')(); // the cover has faded
|
||||
opening.land();
|
||||
await flush();
|
||||
assert.deepEqual(events, ['opening', 'welcome']);
|
||||
await f.stop();
|
||||
assert.ok(events.includes('opening:cancel'));
|
||||
});
|
||||
|
||||
test("the opening's frames stay out of the address until it ends", async () => {
|
||||
const events = [];
|
||||
const holds = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({
|
||||
playOpening: opening.play,
|
||||
shareLink: { holdWrites: (held, owner) => holds.push([held, owner]) },
|
||||
});
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(holds, [[true, 'opening']]);
|
||||
opening.land();
|
||||
await flush();
|
||||
assert.deepEqual(holds, [
|
||||
[true, 'opening'],
|
||||
[false, 'opening'],
|
||||
]);
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
test('an opening that does not play releases the address at once', async () => {
|
||||
const holds = [];
|
||||
const f = fixture({
|
||||
playOpening: () => null,
|
||||
shareLink: { holdWrites: (held, owner) => holds.push([held, owner]) },
|
||||
});
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(holds, [
|
||||
[true, 'opening'],
|
||||
[false, 'opening'],
|
||||
]);
|
||||
assert.ok(f.events.includes('hidden'));
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
const VIEW_ONLY = Object.freeze({
|
||||
status: 'settled',
|
||||
share: { camera: 'applied' },
|
||||
tracking: { status: 'skipped', reason: 'no-shared-target' },
|
||||
thing: false,
|
||||
});
|
||||
|
||||
test('a link to only a view opens with the opening, ending at that view', async () => {
|
||||
const events = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({ playOpening: opening.play, hasShareState: true });
|
||||
f.restored(VIEW_ONLY);
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, 1);
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
for (const [name, restored] of [
|
||||
['a followed target', { ...VIEW_ONLY, tracking: { status: 'restored' } }],
|
||||
['a shared thing', { ...VIEW_ONLY, thing: true }],
|
||||
[
|
||||
'a camera the person moved first',
|
||||
{ ...VIEW_ONLY, share: { camera: 'superseded' } },
|
||||
],
|
||||
['a failed restore', { status: 'failed' }],
|
||||
]) {
|
||||
test(`a link to ${name} opens without the opening`, async () => {
|
||||
for (const [result, plays] of [
|
||||
[restored, 0],
|
||||
[VIEW_ONLY, 1],
|
||||
]) {
|
||||
const opening = openingStub([]);
|
||||
const f = fixture({ playOpening: opening.play, hasShareState: true });
|
||||
f.restored(result);
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, plays);
|
||||
if (!plays) assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('a share restore whose navigation was superseded does not start the opening', async () => {
|
||||
const opening = openingStub([]);
|
||||
const f = fixture({
|
||||
playOpening: opening.play,
|
||||
hasShareState: true,
|
||||
navigationGeneration: 5,
|
||||
});
|
||||
f.restored({ ...VIEW_ONLY, navigationToken: 3 });
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, 0);
|
||||
assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
test('a navigation before the opening starts keeps the camera from it', async () => {
|
||||
const opening = openingStub([]);
|
||||
const f = fixture({ playOpening: opening.play, navigationGeneration: 0 });
|
||||
f.styleManager._navigationGeneration = 1;
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, 0);
|
||||
assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
for (const [name, rejectedShareCode, plays] of [
|
||||
['a rejected share code opens without the opening', 'checksum', 0],
|
||||
['control: a bare address still plays it', null, 1],
|
||||
]) {
|
||||
test(name, async () => {
|
||||
const opening = openingStub([]);
|
||||
const f = fixture({
|
||||
playOpening: opening.play,
|
||||
shareLink: { rejectedShareCode },
|
||||
});
|
||||
f.restored({ status: 'not-requested', share: null, layers: [] });
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, plays);
|
||||
if (!plays) assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
}
|
||||
|
||||
test('a skipped opening reveals welcome only once the cover has faded', async () => {
|
||||
const f = fixture({
|
||||
playOpening: () => ({ done: Promise.resolve(), cancel() {} }),
|
||||
});
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.ok(!f.events.includes('welcome'));
|
||||
f.fire(900);
|
||||
assert.ok(f.events.includes('welcome'));
|
||||
await f.stop();
|
||||
});
|
||||
@@ -4,7 +4,8 @@
|
||||
* Cesium port does (`src/render/cesium/ports.js`): holds, counted per
|
||||
* reason, keep `requestRenderMode` false; releasing the last asks for one
|
||||
* frame; a request is the scene's `requestRender`; the first hold and the
|
||||
* last release are told to `onHeldChange`; a rate set is kept as the
|
||||
* last release are told to `onHeldChange`, every hold and release to
|
||||
* `onHoldsChange`; a rate set is kept as the
|
||||
* scene's `targetFps`. Only the members the governor uses. One port per
|
||||
* scene, so a test can uninstall what it installed.
|
||||
* @param {{requestRenderMode?: boolean, requestRender?: () => void}} scene
|
||||
@@ -20,10 +21,12 @@ const ports = new WeakMap();
|
||||
function makePort(scene) {
|
||||
const holds = new Map();
|
||||
const heldListeners = new Set();
|
||||
const holdsListeners = new Set();
|
||||
let wasHeld = false;
|
||||
const apply = () => {
|
||||
const held = holds.size > 0;
|
||||
scene.requestRenderMode = !held;
|
||||
for (const cb of [...holdsListeners]) cb();
|
||||
if (held === wasHeld) return;
|
||||
wasHeld = held;
|
||||
for (const cb of [...heldListeners]) cb(held);
|
||||
@@ -34,6 +37,10 @@ function makePort(scene) {
|
||||
heldListeners.add(cb);
|
||||
return () => heldListeners.delete(cb);
|
||||
},
|
||||
onHoldsChange(cb) {
|
||||
holdsListeners.add(cb);
|
||||
return () => holdsListeners.delete(cb);
|
||||
},
|
||||
diagnostics: () => ({ holds: [...holds.keys()] }),
|
||||
setTargetFps(fps) {
|
||||
scene.targetFps = fps;
|
||||
|
||||
@@ -250,7 +250,8 @@ export const getFirePerimeters = defineTool({
|
||||
title: 'Wildfire perimeters',
|
||||
description:
|
||||
'Mapped wildfire perimeters from the US WFIGS service in an area, ' +
|
||||
'largest first, with size, containment, cause and personnel.',
|
||||
'largest first, with size, containment, cause, personnel, and ' +
|
||||
"`last_growth`: when each was last mapped (WFIGS mapping time, else the record's last edit).",
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { area: AREA_SCHEMA, limit: LIMIT_SCHEMA },
|
||||
@@ -260,19 +261,33 @@ export const getFirePerimeters = defineTool({
|
||||
requires: ['perimeters'],
|
||||
async run(args, { services, signal }) {
|
||||
const area = await resolveArea(args.area, { services, signal });
|
||||
const snapshot =
|
||||
typeof services.perimeters.getSnapshotDetail === 'function'
|
||||
? await services.perimeters.getSnapshotDetail({ signal })
|
||||
: { rows: await services.perimeters.getSnapshot({ signal }) };
|
||||
const snapshot = await services.perimeters.getSnapshot({ signal });
|
||||
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
|
||||
throw new ToolError('malformed', 'The perimeter snapshot is malformed');
|
||||
const at = isoTime(snapshot.at);
|
||||
// A time after the moment shown is not known at it.
|
||||
const timeAt = (ms) =>
|
||||
at !== null && ms > snapshot.at ? null : isoTime(ms);
|
||||
// The proxy answers from its last snapshot, marked stale, while WFIGS is
|
||||
// unreachable.
|
||||
const stale = snapshot.stale === true;
|
||||
const rows = snapshot.rows
|
||||
.filter((fire) => polygonsTouchArea(fire.polygons, area))
|
||||
.map((fire) => ({ fire, point: polygonCenter(fire.polygons) }))
|
||||
.filter(({ point }) => point)
|
||||
.map(({ fire, point }) => ({
|
||||
id: fire.stableId,
|
||||
// A fire is in the area when a piece of its burned area is.
|
||||
const touching = new Set();
|
||||
for (const piece of snapshot.pieces)
|
||||
if (
|
||||
!touching.has(piece.fireId) &&
|
||||
polygonsTouchArea(piece.polygons, area)
|
||||
)
|
||||
touching.add(piece.fireId);
|
||||
const rows = snapshot.fires
|
||||
.filter(
|
||||
(fire) =>
|
||||
touching.has(fire.id) &&
|
||||
Number.isFinite(fire.anchor?.lat) &&
|
||||
Number.isFinite(fire.anchor?.lon),
|
||||
)
|
||||
.map((fire) => ({
|
||||
id: fire.id,
|
||||
name: fire.name,
|
||||
acres: round(fire.acres, 0),
|
||||
contained_pct: fire.containedPct,
|
||||
@@ -282,47 +297,29 @@ export const getFirePerimeters = defineTool({
|
||||
cause: fire.cause,
|
||||
behavior: fire.behavior,
|
||||
personnel: fire.personnel,
|
||||
discovered: isoTime(fire.discoveredTime),
|
||||
updated: isoTime(fire.updatedTime),
|
||||
lat: round(point.lat, 5),
|
||||
lon: round(point.lon, 5),
|
||||
discovered: timeAt(fire.discoveredTime),
|
||||
updated: timeAt(fire.updatedTime),
|
||||
last_growth: timeAt(fire.lastGrowthTime),
|
||||
lat: round(fire.anchor.lat, 5),
|
||||
lon: round(fire.anchor.lon, 5),
|
||||
}))
|
||||
.sort((a, b) => (b.acres ?? 0) - (a.acres ?? 0));
|
||||
return {
|
||||
summary:
|
||||
`${countNoun(rows.length, 'mapped wildfire perimeter')} in ${area.label}` +
|
||||
(at ? ` as of ${at}` : '') +
|
||||
(stale ? ' (data may be stale).' : '.'),
|
||||
data: {
|
||||
view: suggestView(services, { area, layers: ['fire-perimeters'] }),
|
||||
stale,
|
||||
retrieved_at: isoTime(snapshot.fetchedAt),
|
||||
...(at && { snapshot_at: at }),
|
||||
...capRows(rows, args.limit),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
/** Average outer-ring vertices, using a circular longitude mean at the dateline. */
|
||||
function polygonCenter(polygons) {
|
||||
let lat = 0;
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let count = 0;
|
||||
const toRad = Math.PI / 180;
|
||||
for (const polygon of polygons || []) {
|
||||
for (const [x, y] of polygon?.[0] || []) {
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
||||
sinLon += Math.sin(x * toRad);
|
||||
cosLon += Math.cos(x * toRad);
|
||||
lat += y;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count
|
||||
? { lat: lat / count, lon: Math.atan2(sinLon, cosLon) / toRad }
|
||||
: null;
|
||||
}
|
||||
|
||||
export const getTerrainHeight = defineTool({
|
||||
name: 'get_terrain_height',
|
||||
title: 'Terrain height',
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
defineTool,
|
||||
ToolError,
|
||||
} from '../index.js';
|
||||
import { firePerimeterSnapshot } from '../../layers/perimeters/records.js';
|
||||
|
||||
const conditions = {
|
||||
observedAt: '2026-10-01T19:15:00.000Z',
|
||||
@@ -154,6 +155,57 @@ test('cyclones are listed strongest first and can be limited to an area', async
|
||||
);
|
||||
});
|
||||
|
||||
test('get_fire_perimeters rejects a snapshot that breaks the contract', async () => {
|
||||
const square = [
|
||||
[-118.5, 35.2],
|
||||
[-118.4, 35.2],
|
||||
[-118.4, 35.3],
|
||||
[-118.5, 35.3],
|
||||
[-118.5, 35.2],
|
||||
];
|
||||
const area = { bbox: [-119, 35, -118, 36] };
|
||||
const legacyRow = {
|
||||
stableId: 'legacy',
|
||||
name: 'Legacy',
|
||||
acres: 100,
|
||||
polygons: [[square]],
|
||||
};
|
||||
const fire = {
|
||||
id: 'f1',
|
||||
name: 'Fire One',
|
||||
acres: 10,
|
||||
anchor: { lon: -118.45, lat: 35.25 },
|
||||
};
|
||||
const piece = {
|
||||
fireId: 'f1',
|
||||
born: null,
|
||||
polygons: [[square]],
|
||||
outline: [square],
|
||||
};
|
||||
const query = (snapshot) =>
|
||||
composeCatalog({
|
||||
tools: coreTools,
|
||||
services: { perimeters: { getSnapshot: async () => snapshot } },
|
||||
}).call('get_fire_perimeters', { area });
|
||||
for (const malformed of [
|
||||
[legacyRow],
|
||||
{ rows: [legacyRow], stale: false, fetchedAt: 1 },
|
||||
{ fires: [fire] },
|
||||
{ pieces: [piece] },
|
||||
])
|
||||
await assert.rejects(
|
||||
query(malformed),
|
||||
(error) => error.code === 'malformed',
|
||||
);
|
||||
const live = await query({ fires: [], pieces: [] });
|
||||
assert.equal(live.data.rows.length, 0);
|
||||
assert.equal('snapshot_at' in live.data, false);
|
||||
assert.equal(
|
||||
(await query({ fires: [fire], pieces: [piece] })).data.rows.length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('fire perimeters are placed by their outline and sorted by size', async () => {
|
||||
const ring = (lon, lat) => [
|
||||
[
|
||||
@@ -161,11 +213,12 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
[lon + 0.1, lat],
|
||||
[lon + 0.1, lat + 0.1],
|
||||
[lon, lat + 0.1],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
const perimeters = {
|
||||
async getSnapshot() {
|
||||
return [
|
||||
return firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'small',
|
||||
name: 'Small Fire',
|
||||
@@ -179,6 +232,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
personnel: 20,
|
||||
discoveredTime: Date.UTC(2026, 8, 1),
|
||||
updatedTime: null,
|
||||
polygonTime: Date.UTC(2026, 8, 2, 6),
|
||||
polygons: [ring(-118.5, 35.2)],
|
||||
},
|
||||
{
|
||||
@@ -194,8 +248,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
acres: 9000,
|
||||
polygons: [ring(-80, 30)],
|
||||
},
|
||||
{ stableId: 'empty', name: 'No Outline', acres: 1, polygons: [] },
|
||||
];
|
||||
]);
|
||||
},
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
@@ -222,6 +275,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
personnel: 20,
|
||||
discovered: '2026-09-01T00:00:00.000Z',
|
||||
updated: null,
|
||||
last_growth: '2026-09-02T06:00:00.000Z',
|
||||
lat: 35.25,
|
||||
lon: -118.45,
|
||||
});
|
||||
@@ -229,24 +283,25 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
|
||||
test('fire perimeter queries include dateline interiors and exclude the opposite meridian', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
};
|
||||
const catalog = catalogWith({ perimeters });
|
||||
for (const area of [
|
||||
@@ -268,45 +323,46 @@ test('fire perimeter queries include dateline interiors and exclude the opposite
|
||||
|
||||
test('fire perimeter coordinates stay at the dateline for closed and multipart outlines', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
[
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
[
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
[
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [178, -3, -178, 3] },
|
||||
@@ -759,23 +815,24 @@ test('brief sections use a named place at its own point', async () => {
|
||||
|
||||
test('a fire perimeter enclosing the whole area is found', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'big',
|
||||
name: 'Big Fire',
|
||||
acres: 250000,
|
||||
polygons: [
|
||||
[
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'big',
|
||||
name: 'Big Fire',
|
||||
acres: 250000,
|
||||
polygons: [
|
||||
[
|
||||
[-122, 38],
|
||||
[-120, 38],
|
||||
[-120, 40],
|
||||
[-122, 40],
|
||||
[
|
||||
[-122, 38],
|
||||
[-120, 38],
|
||||
[-120, 40],
|
||||
[-122, 40],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-121.2, 38.9, -120.8, 39.1] },
|
||||
@@ -883,19 +940,11 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
|
||||
],
|
||||
];
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [],
|
||||
getSnapshotDetail: async () => ({
|
||||
rows: [
|
||||
{
|
||||
stableId: 'held',
|
||||
name: 'Held Fire',
|
||||
acres: 300,
|
||||
polygons: [ring],
|
||||
},
|
||||
],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
}),
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot(
|
||||
[{ stableId: 'held', name: 'Held Fire', acres: 300, polygons: [ring] }],
|
||||
{ stale: true, fetchedAt },
|
||||
),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-120, 34, -117, 36] },
|
||||
@@ -907,3 +956,62 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
|
||||
assert.equal(result.data.stale, true);
|
||||
assert.equal(result.data.retrieved_at, new Date(fetchedAt).toISOString());
|
||||
});
|
||||
|
||||
test('a fire is in the area when one of its pieces is', async () => {
|
||||
const square = (lon, lat) => [
|
||||
[
|
||||
[lon, lat],
|
||||
[lon + 0.1, lat],
|
||||
[lon + 0.1, lat + 0.1],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
const fire = (id, lon, lat) => ({
|
||||
id,
|
||||
name: id,
|
||||
acres: 10,
|
||||
lastGrowthTime: null,
|
||||
anchor: { lon, lat },
|
||||
});
|
||||
const perimeters = {
|
||||
getSnapshot: async () => ({
|
||||
at: Date.UTC(2024, 6, 3),
|
||||
stale: false,
|
||||
fetchedAt: null,
|
||||
revision: '',
|
||||
note: null,
|
||||
fires: [
|
||||
{
|
||||
...fire('split', -80, 30),
|
||||
discoveredTime: Date.UTC(2024, 6, 1),
|
||||
updatedTime: Date.UTC(2024, 6, 4),
|
||||
lastGrowthTime: Date.UTC(2024, 6, 4),
|
||||
},
|
||||
fire('unmapped', -118.5, 35.2),
|
||||
],
|
||||
pieces: [
|
||||
{ fireId: 'split', born: null, polygons: [square(-80, 30)] },
|
||||
{ fireId: 'split', born: null, polygons: [square(-118.5, 35.2)] },
|
||||
],
|
||||
}),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-120, 34, -117, 36] },
|
||||
});
|
||||
const [row] = result.data.rows;
|
||||
assert.deepEqual(
|
||||
[row.discovered, row.updated, row.last_growth],
|
||||
['2024-07-01T00:00:00.000Z', null, null],
|
||||
'times after the snapshot are unknown at it',
|
||||
);
|
||||
assert.equal(result.data.snapshot_at, '2024-07-03T00:00:00.000Z');
|
||||
assert.equal(
|
||||
result.summary,
|
||||
'1 mapped wildfire perimeter in the requested box as of 2024-07-03T00:00:00.000Z.',
|
||||
);
|
||||
assert.deepEqual(
|
||||
result.data.rows.map(({ id, lat, lon }) => [id, lat, lon]),
|
||||
[['split', 30, -80]],
|
||||
'placed at its card anchor; a fire with no pieces is not mapped',
|
||||
);
|
||||
});
|
||||
@@ -426,6 +426,9 @@ export class StyleManager extends ShellFacade {
|
||||
summaryService: requestServices?.summary,
|
||||
publish: (view) => hudStore.publish(view),
|
||||
});
|
||||
// The view says whether it is on screen; off screen the HUD does no
|
||||
// readout work.
|
||||
hudStore.connect(this.hud);
|
||||
this._recording.hud = this.hud;
|
||||
this._cockpitCoordinator = new CockpitCoordinator({
|
||||
viewer,
|
||||
|
||||
@@ -502,7 +502,7 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted,
|
||||
const timeline = read('./styles/world-timeline.css');
|
||||
const timelineLift = value(
|
||||
timeline,
|
||||
/body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/,
|
||||
/body:is\(\.has-world-timeline \*, #world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/,
|
||||
);
|
||||
|
||||
// From 1200px the dock and the World Timeline leave the bottom 74px; below
|
||||
@@ -549,7 +549,7 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted,
|
||||
);
|
||||
assert.match(
|
||||
trays,
|
||||
/:has\(#command-dock > #gev-voice-control\)\s*\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - 26rem\);/,
|
||||
/:where\(\.has-omnibar\.dock-has-voice \*\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - 26rem\);/,
|
||||
);
|
||||
return anchor && box && [null, anchor[1], box[1]];
|
||||
})(),
|
||||
@@ -578,7 +578,7 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted,
|
||||
// right, with the Minimal HUD too (its placement names #intel-hud).
|
||||
assert.match(
|
||||
trayWide,
|
||||
/html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*:is\(#cesium-credits, #gev-credits\),\s*html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\):has\(\s*#intel-hud\[data-variant='minimal'\]\.active\s*\)\s*:is\(#cesium-credits, #gev-credits\) \{\s*right: 1\.5rem;\s*left: auto;/,
|
||||
/html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*:is\(#cesium-credits, #gev-credits\),\s*html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\):is\(\s*\.hud-minimal-active \*,\s*#intel-hud\[data-variant='minimal'\]\.active\s*\)\s*:is\(#cesium-credits, #gev-credits\) \{\s*right: 1\.5rem;\s*left: auto;/,
|
||||
);
|
||||
// Its box hangs from the anchor's right edge there, and in the Omnibar
|
||||
// layout at every width; never in clean view or recording, where the
|
||||
@@ -791,7 +791,7 @@ test('the Omnibar dock sits above the World Timeline, and narrow corners clear t
|
||||
);
|
||||
assert.doesNotMatch(css, /--world-timeline-lift\s*:/);
|
||||
const lift = read('./styles/world-timeline.css').match(
|
||||
/body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/,
|
||||
/body:is\(\.has-world-timeline \*, #world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/,
|
||||
);
|
||||
const height = read('./styles/world-timeline.css').match(
|
||||
/#world-timeline \{[^}]*\n {2}height: (\d+)px;/,
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user