diff --git a/.env.example b/.env.example index 2caf21d298..a9819f100b 100644 --- a/.env.example +++ b/.env.example @@ -176,7 +176,7 @@ VITE_AIS_LIVE_LABEL_MAX_ROWS=900 AISSTREAM_API_KEY= # Optional AISStream subscription filters. # AISSTREAM_BOUNDING_BOXES=[[[-90,-180],[90,180]]] -# AISSTREAM_MESSAGE_TYPES=PositionReport,StandardClassBPositionReport,ExtendedClassBPositionReport,ShipStaticData,StaticDataReport +# AISSTREAM_MESSAGE_TYPES=PositionReport,StandardClassBPositionReport,ExtendedClassBPositionReport,ShipStaticData,StaticDataReport,AidsToNavigationReport # Feed watchdog: silence (ms) after which the feed is REPORTED stale; the socket # is recycled at 2.5x that. Default 120000. The watchdog self-arms only for the # default worldwide subscription — a narrow filter above can be legitimately diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 541af11364..412bf5da86 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,6 +106,16 @@ jobs: - name: Street Level gate with Mapillary fixtures run: npm run qa:street-level:fixtures -- --strict --url http://localhost:4173 + - name: The whole application on the stub renderer, with no Cesium loaded + run: | + mkdir -p qa-artifacts + npm run qa:stub-boot -- --json qa-artifacts/stub-boot.json + + - name: The renderer contract's logic checks on Cesium, headless + run: | + mkdir -p qa-artifacts + npm run qa:conformance -- --json qa-artifacts/conformance.json + - name: Preview server log if: failure() run: cat preview.log diff --git a/.prettierignore b/.prettierignore index 2b2cc755a1..9e1a01ef80 100644 --- a/.prettierignore +++ b/.prettierignore @@ -9,6 +9,8 @@ coverage pinokio/ENVIRONMENT pinokio/.installed src/data/local_data/ +# Written by scripts/record-camera-goldens.mjs and compared byte for byte. +src/render/conformance/goldens/ *.geojson *.geojsonl diff --git a/CHANGELOG.md b/CHANGELOG.md index f49dad02be..995beef5e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,120 @@ ## [Unreleased] +- A double-click on the map no longer follows or zooms to what is under + it. The globe's own double-click did that for some layers' markers and + shapes (earthquakes, cyclones, air quality, news, cables, places and + others); following something is a click, as for aircraft and ships. The + Cockpit's double-click and a drawing's finishing double-click are + unchanged (samehkhamis). +- Aircraft no longer jump ahead or back, and their trails no longer kink, + when the feed is late. The civil and military layers draw as far behind + real time as their feed is late (the 90th percentile of recent report + lags plus 5 s, at least 30 s civil and 15 s military, at most five + minutes), so an aircraft is placed between two real reports rather than + dead reckoned past them; the delay changes slowly, and the icons, the + renderer's live clock, labels, the HUD, detection, the tracked camera and + the trail all read the same one. Between two reports an aircraft flies + one smooth curve that leaves each report along its track, sent to the + renderer as `arc` segments; its trail is its reports joined along that + same curve, so the icon always sits on it. A late report a coasting + aircraft missed is eased onto, at most 30% faster than it flies; past + its newest report an aircraft coasts straight on (samehkhamis). +- The Display panel has a Sky group on a renderer with a sky to set: the + atmosphere, day and night (sun lighting by scene time), the sun, the + moon, the stars and the Milky Way's brightness. The choice is kept for the + next visit; what is not set stays as the renderer draws it (samehkhamis). +- The renderer contract no longer ties a renderer's look to the default + renderer's: `globe.sky` switches parts of the sky on and off, while how + the sky, atmosphere, haze, lighting, tone mapping and exposure look is + the renderer's own. `globe.weather`'s `clouds` is the fraction of the sky + covered, as observed; clouds are placed by scene time and the wind and + shade the ground under them where the sun lights it. New conformance + check `globe.weather.sceneTime` (samehkhamis). +- Selecting an aircraft, a vessel, a train or a transit vehicle no longer + makes it bigger: it keeps the size and form it had and changes colour (a + transit vehicle only widens its dark ring). A click on an aircraft, a + vessel or a train no longer moves the camera to a new framing either: the + camera keeps its distance and viewing angle, the contact slides to the + centre over one second, and the camera then follows it from there (a + vessel, which is never followed, is left centred). A + follow target asks for this glide with `transitionS` (renderer contract, + conformance check `camera.follow.transition`); without it a follow frames + at once, as before. An aircraft chosen by voice, search or a shared link + is still framed as before (samehkhamis). +- The renderer contract's `models` capability draws the procedural fleet + models: a model item can carry its glTF bytes (`gltf`, drawn without a + fetch), a per-axis stretch (`axisScale`), a colour for its tinted parts + (`maskColor`) and a cut below its origin (`clip: 'belowOrigin'`, a hull at + the waterline). Aircraft, military, local ADS-B, vessel, transit and rail + models are drawn through it (samehkhamis). +- A tracked aircraft's trail no longer draws a straight line from its track + history across a landing or take-off that was not seen: a parked or + taxiing aircraft whose history ends in the air (often its previous flight) + starts its trail on the ground (samehkhamis). +- Aircraft from adsb.lol that report no ground track (parked or taxiing + slowly) now face their reported true heading instead of north, so parked + models line up with their gates (samehkhamis). +- A renderer can draw weather: the `weather` capability adds `globe.weather`, + with clouds, fog, haze, rain and snow (each 0 to 1) and the wind they drift + on. `./render/weather` and `./weather/effects` export the shared rules and + the strengths of a weather observation. The Cesium renderer does not draw + weather (samehkhamis). +- Groups of toggles, sliders and notes can be added to the Display panel + under Effects, with `publishDisplayGroup` from `./ui/display/groups` + (samehkhamis). +- The globe opens at planet level, the whole Earth in view, instead of + flying in to Austin. A shared link still flies from + there to its view. The `startView` option of `createApplicationControls` + starts it somewhere else, a city for instance (longitude, latitude and + height, and heading and pitch in degrees) (samehkhamis). - An application's own tool can take the pointer as Draw does, and its click handlers can yield while a tool holds it, as the layers' do (`pointer` from `createApplicationTools`) (samehkhamis, #1641). +- `gods-eye-view/annotations` no longer reaches Cesium: the world annotation + renderer draws its areas, building columns, routes, arrows, rings and + markers through the renderer's draw port (the Cesium renderer now drapes + arrows, draws clamped rings by camera height and pulses shape alpha), and + samples a building's ground through the height service. A click on a + world mark now hits its draw set (`meta: { annotation: id }`) rather than + an entity. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- `gods-eye-view/application/layers` and `gods-eye-view/standalone/catalog` + no longer reach Cesium: the weather shells and the wind layer's colour + shell and flow draw through the renderer's `draw.field` (`rasterShell` and + `windStreamlines`, which the Cesium renderer now draws), and the wind + relief is the globe port's `hillshade` surface shading. The flow animates + as before, and still falls back to the canvas where the renderer refuses + it. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- `gods-eye-view/input` no longer reaches Cesium: the dispatcher takes its + pointer events from the renderer's input port and its picks from the query + port. A click's `hit`, `topHit`, `drawHit` and `drill()` hits, and + `pickAt`'s result, are the renderer contract's `Hit`; positions are plain + `{ x, y }`; `HANDLER_EVENT_TYPES` is gone. Cesium's own picks stay on + `event.native` (and `event.pick` and `event.pickWindow`). A viewer with no + renderer bound needs `gods-eye-view/render/cesium/unbound` + loaded once first (samehkhamis). +- `gods-eye-view/application/operations` no longer reaches Cesium: ground + snapping and mesh floor sampling ask the renderer's globe, camera and query + ports, and see through the caller's draw sets by id (the raw + `excludeObjects` option and exclusion callbacks are gone). A viewer with no + renderer bound needs `gods-eye-view/render/cesium/unbound` + loaded once first, or location framing throws and snaps answer nothing + (samehkhamis). +- `gods-eye-view/layers/traffic` (and `gods-eye-view/application/sources`, + which reaches it) no longer reaches Cesium: the layer keys cached road + heights by the globe port's `surfaceVersion()` and waits on + `isSettled('surface')`. Heat-lines are always asked for draped; a renderer + that cannot drape draws them over the surface instead of the layer + dropping them. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- Where the Cesium renderer cannot drape (a WebGL context without depth + textures), every draped line now draws over the surface, as the renderer + contract asks: along the surface's curve between its positions, in its + colour where the surface hides it, hidden past the horizon. Segment colours + are dropped (it draws in its style colour) and it runs from its first shown + segment to its last (samehkhamis). ## [0.3.0] — 2026-10-27 — Street Level, On Your Phone, in Your Language @@ -788,7 +899,7 @@ - Stop one retired bikeshare feed from reporting the whole layer as failed. City feeds are fetched independently, but failure was recorded in a single - flag that only a successful *activation* cleared — and an already-loaded city + flag that only a successful _activation_ cleared — and an already-loaded city never activates again. A dead feed re-entering camera range therefore latched LOAD FAILED permanently over a map still drawing every other city's stations. Failure is now tracked per city: a city that fails beside others still @@ -1064,7 +1175,7 @@ photo a click opens, and the cones, by each photo's projection and upload date. KartaView's SINCE is the upload date (all its server can filter by); a note under the slider says so while KartaView is lit (`sinceBasis: - 'upload'` in the provider contract). +'upload'` in the provider contract). Mapillary's line coverage and sequence cones are now shared by both (`lineCoverage.js`, `sequenceCones.js`). @@ -1642,6 +1753,7 @@ Add feed provenance to analyst/view answers and HUD context while retaining existing response fields and runner ownership (Matt Van Horn, #347). Analyst records for loaded satellites, datacenters and dams, with explicit bounded count/rank coverage (Matt Van Horn, #351). + - New Fire Perimeters layer (Events group): live NIFC WFIGS interagency wildfire incident perimeters as ground-clamped polygons with a containment-colored fire line, refreshed every 5 minutes from the public @@ -1918,7 +2030,6 @@ of current runtime behavior, see [`docs/CURRENT-STATE.md`](docs/CURRENT-STATE.md ### Other changes - - Add ECMWF IFS model selection to Wind (#464, thanks @beneduzi), with model-scoped forecast-step caches, cancellation of replaced requests, and separate issue/valid timestamps. - Add bounded Director feature actions with accessible controls, explicit camera/layer admission and cancellation; restore pack geometry on same-shot seek. Preserve existing scenes and content attribution. @@ -2727,4 +2838,3 @@ represent previously published GitHub Releases. ## [0.1.0] — 2026-02-09 - Initial project version. - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5ef1d7f8e3..438f9da14d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -139,6 +139,7 @@ The highest-leverage places to jump in: - **Vue 3 + Pinia for the interface,** [CesiumJS](https://cesium.com/platform/cesiumjs/) for the globe and [Vite](https://vitejs.dev/) to build. See [Building UI](#building-ui). - **Assembly lives in `src/app/`; standalone defaults live in `src/standalone/`.** UI controllers live in `src/ui/`, layer factories in `src/layers/`, portable sources in `src/sources/`, and application operations in `src/services/`. Existing `src/data/.js` entries retain compatibility; new code belongs with its focused owner. +- **Reach the renderer through its contract** ([docs/RENDERER-CONTRACT.md](docs/RENDERER-CONTRACT.md#moving-code-onto-the-contract)): `findDraw`, `findCamera` and the other ports in `src/render/rendererOf.js`, not Cesium or the viewer's `scene`, `camera` or `entities`. Two ratchet tests hold this: only files on `src/render/cesiumAllowList.json` may import Cesium, and `src/render/viewerAccessAllowList.json` caps the viewer accesses each other file still makes. Neither list may grow; when you port code off them, shrink them (`node scripts/viewer-access-baseline.mjs` lowers the second). - Sources acquire records; renderers own Cesium resources. Import `gods-eye-view/layers//source` when only a source factory is needed. Common voice controls consume the session interface; protocol adapters own connection details. - **Secrets stay server-side.** Anything needing a private key goes through a local proxy under `server/providers/`. The browser only ever sees the Google Maps key (which you restrict) and ephemeral tokens. - `docs/CURRENT-STATE.md` is the authoritative runtime reference — read it first. diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index b1f44764cf..4d82b771cf 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -1,13 +1,13 @@ # Data Sources & Attribution -God's Eye View's **code** is [MIT](LICENSE)-licensed. **The MIT grant covers the source code only — it does NOT extend to third-party data or visual assets.** Every third-party source keeps its own license and terms. This file documents the live and bundled data sources; bundled 3D-model provenance is recorded in [`public/models/README.md`](public/models/README.md). +God's Eye View's **code** is [MIT](LICENSE)-licensed. **The MIT grant covers the source code only — it does NOT extend to third-party data or visual assets.** Every third-party source keeps its own license and terms. This file documents the live and bundled data sources. The bundled 3D models are the project's own procedural fleet models, MIT-licensed with the code ([`public/models/README.md`](public/models/README.md)). How to read this: - **The non-permissive datasets are carved out, not omitted.** Some bundled data (e.g. TeleGeography, CC BY-NC-SA) isn't MIT-compatible. Rather than hide it, we **bundle it with a clear license carve-out** so the app works out of the box — but it stays under the provider's terms. - **If your use doesn't fit a dataset's license, remove that dataset.** Most importantly: TeleGeography is **NonCommercial** — commercial users must delete it (or license it from TeleGeography). It's one self-contained folder. - **Attribution is shown in-app** and listed here. Keep it intact. The required Google/Cesium credit renders on the on-globe credit line (bottom-left, `#cesium-credits`), and every per-layer credit below is registered into the expandable **"Data attribution"** lightbox on that line (`src/data/dataCredits.js` → `viewer.creditDisplay.addStaticCredit`). Both stay visible in clean-view and recording modes. -- **Bundled model attribution lives beside the model files.** [`public/models/README.md`](public/models/README.md) records each shipped model's creator, source, license, and modification status. +- **The bundled 3D models are the project's own.** Every model under `public/models/` is a procedural fleet model generated by the project maintainers and covered by the repository's MIT license; [`public/models/README.md`](public/models/README.md) describes the set. --- @@ -223,19 +223,23 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei The numerical minima come from US 14 CFR 91.227(c), not a published jamming classifier. Readsb's [JSON contract](https://github.com/wiedehopf/readsb/blob/dev/README-json.md) describes the quality field origins and GPS-loss flag. - 2. **GPSJAM aggregation:** score = `100 × max(0, bad − 1) / total`, with percent - bands < 2, 2–10, > 10. One bad aircraft is discounted. This is not the raw - share of bad aircraft. See the [GPSJAM FAQ](https://gpsjam.org/faq). - 3. **GEV window:** 30 minutes over visited views, at least three aircraft per - 0.5° cell. These bands were developed for daily totals; with fewer than ten - observations a cell can skip the middle band. Source timestamps date evidence - even through cache replays, and degraded evidence expires independently. + 2. **GPSJAM aggregation:** aircraft are binned into H3 resolution-4 hexagons + (about 1,770 km² each), and score = `100 × max(0, bad − 1) / total`, with + percent bands < 2, 2–10, > 10. One bad aircraft is discounted. This is not + the raw share of bad aircraft. As on GPSJAM there is no minimum aircraft + count: every hexagon with an aircraft is shown, and the discount is the only + small-sample guard. See the [GPSJAM FAQ](https://gpsjam.org/faq). + 3. **GEV window:** 30 minutes over visited views. These bands were developed + for daily totals; with fewer than ten observations a cell can skip the + middle band. Source timestamps date evidence even through cache replays, + and degraded evidence expires independently. Medium/high cells report navigation-integrity anomalies. Interference is one possible explanation, not a detected or located emitter. Avionics faults and manoeuvring military trainers can also lower reported accuracy. Blank areas - can be outside coverage or lack enough observations. Attribution: adsb.lol - contributors, ODbL 1.0; GPSJAM for aggregation only. + are outside coverage or had no qualifying aircraft in the window. + Attribution: adsb.lol contributors, ODbL 1.0; GPSJAM for the grid and + aggregation only. - **adsbdb enrichment.** `/api/adsbdb` resolves an ICAO hex to aircraft type, model name and registration, and the tracked flight's callsign to an airline and an origin/destination pair. Fan-out is deliberately small because adsbdb is a free community API that publishes no quota: at most 4 requests in flight, dispatches dripped to roughly 5/s, and each key asked for at most once per session (for the flights layer's enrichment, a lookup that failed temporarily, such as an outage, a timeout, a rate limit or an authorization refusal that may clear, may be asked again after a 60-second cool-down; an answer, found or not, and a permanent refusal such as a 404 are final; Local ADS-B lookups are asked once), with route lookups reserved for the tracked aircraft. The dev-server proxy caches each key for 24 hours in `.gev-cache/adsbdb.json`, negative answers included, so fresh entries survive server restarts. That gitignored cache remains local to the deployment and is not bundled with this repo. adsbdb publishes no general service license; its README says the route data may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh. Deployers are responsible for obtaining any permission their use requires. Enrichment is best-effort and fail-silent — a flight that gets no answer keeps what the flight feed already gave it. @@ -419,6 +423,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p | **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) | | **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) | | **US Census Bureau counties** (3,235 county polygons) | `us_census_counties/` | **Public domain** | ✅ (no restrictions) | "U.S. Census Bureau" (courtesy — not legally required) | | **US Census Bureau places** (32,629 city, town and CDP polygons) | `us_census_places/` | **Public domain** | ✅ (no restrictions) | "U.S. Census Bureau" (courtesy — not legally required) | | **Who's On First neighborhoods** (61,441 polygons) | `wof_neighborhoods/` | Per source: CC BY, ODC-By, Open Government licences, CC0, PDDL, public domain (folder `ATTRIBUTION.md`) | ✅ (attribution) | "Neighborhood boundaries: Who's On First and contributors"; per-source credits in the folder | @@ -518,6 +523,20 @@ its width ("Sichuan, China · near Chengdu"), offline, with the states and provi the division. Public domain; credited "Made with Natural Earth" with the other packs. Rebuild: `node scripts/build-admin-packs.mjs --only places`; provenance in the folder README. +### Wikidata cities (`wikidata_cities/`) + +Settlements of 15,000 people or more that Wikidata states a population and coordinates for, +read once from the Wikidata Query Service by `scripts/build-wikidata-cities.mjs`: one row per +place with its English label, latitude and longitude to 3 decimals, largest stated population, +ISO 3166-1 country code and Wikidata id (31,827 places, 1.6 MB). The pack is read the +first time a place name is looked up and gives the nearest city, the places in view and a city +found by name (`findPlace`: "Paris, France", or the nearest namesake in view). Groupings of +settlements (metropolitan areas, agglomerations) and places that no longer stand are left out +unless they are also a living city. Names match without accents ("Sao Paulo" finds São Paulo). +CC0; credited "City, town and village names from Wikidata (CC0)" as a courtesy once a name from +the pack is shown. Rebuild: `node scripts/build-wikidata-cities.mjs`; provenance in the folder +README. The app never calls Wikidata itself. + ### Sky background (`sky/`) Sources, licences, the changes CC BY asks to state, hashes and build commands diff --git a/LICENSE b/LICENSE index 4f01699a2a..86483f2d6d 100644 --- a/LICENSE +++ b/LICENSE @@ -56,7 +56,6 @@ In short: the MIT grant does not extend to any third-party data. See DATA_SOURCES.md for the full per-source license + attribution summary, and remove any dataset whose terms don't fit your use. -The 3D models under public/models/ are also third-party works and are NOT -licensed under MIT. They remain under their individual licenses. See -public/models/README.md for the author, source, license, modification notice, -and attribution covering each model file. +The 3D models under public/models/ are the project's procedural fleet +models, generated from code by the project maintainers, and are covered by +the MIT license above like the source code. See public/models/README.md. diff --git a/README.md b/README.md index 74479d0468..ea347a7399 100644 --- a/README.md +++ b/README.md @@ -2,29 +2,25 @@ # 🌐 God's Eye View -[![CI](https://github.com/bilawalsidhu/gods-eye-view/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/bilawalsidhu/gods-eye-view/actions/workflows/ci.yml) [![Reached #1 on GitHub Trending](https://img.shields.io/badge/%231_GitHub_Trending-thank_you!-F0A63C?style=flat-square&logo=github)](https://x.com/bilawalsidhu/status/2093798887815348521) +**Official site: [godseyeview.ai](https://godseyeview.ai)** · [Download](https://godseyeview.ai/download/) · [Guide](https://godseyeview.ai/guide/) · [Releases](https://godseyeview.ai/releases/) · [Hosted version waitlist](https://godseyeview.ai/online/) · [Media](https://godseyeview.ai/press/) -### A spy-satellite simulator in your browser — then you realize the sources are public and the data is real. +[![CI](https://github.com/bilawalsidhu/gods-eye-view/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/bilawalsidhu/gods-eye-view/actions/workflows/ci.yml) [![Reached #1 on GitHub Trending](https://img.shields.io/badge/%231_GitHub_Trending-thank_you!-F0A63C?style=flat-square&logo=github)](https://www.star-history.com/?type=date&repos=bilawalsidhu%2Fgods-eye-view) [![GitHub stars](https://img.shields.io/github/stars/bilawalsidhu/gods-eye-view?style=flat-square&color=4fe3ff)](https://github.com/bilawalsidhu/gods-eye-view/stargazers) [![MIT License](https://img.shields.io/badge/license-MIT-4fe3ff?style=flat-square)](LICENSE) -Photorealistic 3D globe. Live aircraft, ships, satellites, earthquakes, traffic, and public cameras. Hands-free voice control powered by a realtime AI agent. +### A spy-satellite simulator in your browser. Except the data is real. -_No place left behind._ +_The window through which we see our world._ -![Orbital HUD, a tracked live globe, FLIR terrain — then OPEN SOURCED](docs/media/hero-open-source-reveal.gif) +[![God's Eye View: a live 3D globe indexing the planet's public signals](docs/media/site/hero.webp)](https://godseyeview.ai) - - The God's Eye View video series on YouTube - +Click any satellite, plane, ship or public camera and you can track it. Turn on FLIR mode and suddenly you're wondering, holy crap, is this real? And it's free, and open source. -▶️ **From the project behind the viral God's Eye View series** _(formerly WorldView)_ — [5M+ on YouTube](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q) · [25M+ across socials](https://www.google.com/search?q=god%27s+eye+view) +**[One-click install with Pinokio](https://pinokio.co/apps/github-com-bilawalsidhu-gods-eye-view)** · **[Run it from the terminal](#-quick-start)** · **[Hosted version waitlist](https://godseyeview.ai/online/)** -🏆 **Reached #1 on GitHub Trending, daily and weekly · August 2026** +🏆 **#1 on GitHub Trending**, daily and weekly · **[#8 Product of the Day](https://www.producthunt.com/products/god-s-eye-view?launch=god-s-eye-view)**, hunted by Chris Messina · _“pretty cool”_ — [Brendan Eich](https://x.com/BrendanEich/status/2094592096401490266), creator of JavaScript · Featured on **[Pinokio](https://pinokio.co/posts/01m1m4p9xxm3qw7dnnpj2wr93g)** -**[#8 Product of the Day](https://www.producthunt.com/products/god-s-eye-view?launch=god-s-eye-view)** · Hunted by Chris Messina, creator of the hashtag +▶️ **From the project behind the God's Eye View series** _(formerly WorldView)_ — [25M+ views on YouTube](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q) -_“pretty cool”_ — [Brendan Eich](https://x.com/BrendanEich/status/2094592096401490266), creator of JavaScript and co-founder of Mozilla and Brave · Featured on **[Pinokio](https://pinokio.co/posts/01m1m4p9xxm3qw7dnnpj2wr93g)** - -⚡ **Start without API keys.** Install with [Pinokio](https://pinokio.co/apps/github-com-bilawalsidhu-gods-eye-view) or run locally from the terminal. Add optional keys inside the app. **[→ Quick Start](#-quick-start)** +**As seen on** [Matt Wolfe](https://www.youtube.com/watch?v=S2VJU5DQqlU) · [Riley Brown](https://www.youtube.com/watch?v=NR_GMq2lDCE) · [Digg](https://digg.com/tech/r7whv988) · [The Escapist](https://www.escapistmagazine.com/news-gods-eye-view-spy-satellite-simulator-setup-focus-keyphrase-gods-eye-view/) · [UNILAD Tech](https://www.uniladtech.com/social-media/youtube/viewers-concerned-youtubers-safety-built-gods-eye-monitor-889810-20260309) · [Al Jazeera](https://www.aljazeera.com/video/the-stream/2026/3/8/how-do-you-track-a-war-in-real-time) · [NDTV](https://www.ndtv.com/video/strait-of-hormuz-news-hormuz-stranglehold-no-end-in-sight-1080351) · [Mojo Story](https://www.youtube.com/watch?v=UXkJjyFfrwc) · [all media](https://godseyeview.ai/press/) @@ -32,7 +28,7 @@ _“pretty cool”_ — [Brendan Eich](https://x.com/BrendanEich/status/20945920
-**[Quick Start](#-quick-start) · [First Five Minutes](#-the-first-five-minutes) · [Talk to It](#-talk-to-it) · [What's Live](#-whats-on-the-globe) · [Under the Hood](#-under-the-hood) · [Keys & Costs](#-api-keys) · [Contributing](CONTRIBUTING.md)** +**[Quick Start](#-quick-start) · [What It Does](#️-what-this-thing-does) · [First Five Minutes](#-the-first-five-minutes) · [Talk to It](#️-talk-to-it) · [What's Live](#️-whats-on-the-globe) · [Keys & Costs](#-api-keys) · [Contributing](CONTRIBUTING.md)**
@@ -56,11 +52,41 @@ Start with the included data sources, then add your own. Each layer is a separat ## 🎛️ What This Thing Does +The world is already broadcasting. We fuse it together into a 3D globe for you and your agents. + +We've got a plurality of sensor systems watching the planet right now. Satellite imagery, flights, ships, weather, public cameras. Each captures a sliver of what's happening. God's Eye View pulls that treasure trove of public data into a single picture. + + + + + + + + + + + + + + + + + + + + + + +
Ask the planet in God's Eye View
Ask the planet
Use voice to ask the planet questions in natural language, and it annotates the 3D globe with the answer.
Flights and vessels in God's Eye View
Flights and vessels
Click on a satellite, plane, ship or public camera and you can track it.
Satellites in God's Eye View
Satellites
Toggle on different kinds of satellites, everything from GPS to Starlink.
Public cameras in God's Eye View
Public cameras
Some layers, like traffic and camera poses, are estimates, and the app says so.
Cockpit in God's Eye View
Cockpit
Visualize a flight from the third-person perspective and jump into a rendered cockpit view.
World class weather in God's Eye View
World class weather
Clouds, rain radar, lightning density and cyclone tracks with forecast cones. And since we say 4D, you can scrub the cloud imagery backwards in time.
Recent imagery in God's Eye View
Recent imagery
Draw a bounding box around a fire and it'll retrieve the Sentinel-2 images, draped on the 3D terrain. All keyless, ladies and gentlemen.
Transit in God's Eye View
Transit
Click a bus in Boston and it starts leaving a trail. This might be the most overkill way to track your bus.
RF and SDR support in God's Eye View
RF and SDR support
Now you can connect your own SDR and visualize everything you're detecting. The SDR nerds know all the other possibilities.
World radio in God's Eye View
World radio
Ask for radio near anywhere and the globe starts broadcasting. Drag the tuner across up to 750 stations.
MCP server in God's Eye View
MCP server
We've built MCP access so your agents can query the same picture and add their findings to a shared canvas.
Director Mode in God's Eye View
Director Mode
Draw outlines, sketch paths, drop your annotations on the map.
+ +
+Everything else it does + - **🛩️ Cockpit view:** Ride inside a tracked flight — the camera holds the terrain under you all the way down. - **📡 Contacts:** A 250 km roster of everything near your target — step through live aircraft and drop into any cockpit. - **🎯 Click-to-track anything:** Camera locks on, draws a fading trail, surfaces full metadata — and a tracked fire or vessel hands you off to the nearest live camera in one click. - **🖊️ Voice whiteboard:** Speak annotations onto the world — real boundary polygons, marks, and routes. -- **🛫 3D hangar:** Real per-class aircraft models — 787, ATR-72, Citation, Bell 206, MQ-9 — and a tracked contact swaps from glyph to 3D model as you close in. +- **🛫 3D fleet:** 122 procedural models drawn life size by type — airliners, business jets, helicopters, drones, ships, buses, trams and trains — and every contact swaps from glyph to 3D model as you close in. - **🎨 Reskin reality:** GLSL sensor looks over the normal globe — CRT, NVG, FLIR/thermal, Noir. - **🟩 Detection overlay:** Screen-space bounding boxes and IDs on everything in view. - **🎖️ Military HUD:** Tactical heads-up display with intelligence-style telemetry. @@ -77,6 +103,8 @@ Start with the included data sources, then add your own. Each layer is a separat - **📦 Shareable scenes:** Import, preview and share Director scenes as files or bundles, with camera anchors, authored moves and data packs. - **🌊 Nepal flood scene:** Replay the Bhote Koshi flood: flood path, witness sources and before-and-after imagery (bundled data is non-commercial; see [DATA_SOURCES.md](DATA_SOURCES.md)). +
+ ---
@@ -156,7 +184,8 @@ See [docs/PERFORMANCE.md](docs/PERFORMANCE.md). **macOS shortcut:** `./scripts/dev-fresh.sh` clears the Vite cache and pulls any configured keys straight from the Keychain. It starts keyless too. -### Path 3 — Docker +
+Path 3 — Docker No Node install needed; the container publishes the same dev server. @@ -234,7 +263,10 @@ the container.
-### Path 4 — GitHub Codespaces (cloud, no local install) + + +
+Path 4 — GitHub Codespaces (cloud, no local install) Codespaces requires a GitHub account. Overpass queries, the News layer and OpenAI voice token requests return HTTP 403 through its forwarded HTTPS URL, even with API keys @@ -272,6 +304,8 @@ wider-publish case in [Sharing an instance](#-sharing-an-instance). Provider Settings is unavailable on the forwarded URL. Never commit your workspace `.env`. [SECURITY.md](SECURITY.md) has the threat model. +
+ ### Then power it up — in the app, not in a file For a local setup, keys are upgrades, not prerequisites. When you want one, @@ -314,54 +348,30 @@ and it carries the LAN-sharing rules alongside [Keys & Costs](#-api-keys). ## 🕐 The First Five Minutes -Choose a first-run mission, or try these in order. The GIFs show Google Photorealistic 3D; your starting basemap depends on the keys you've added. +Choose a first-run mission, or try these in order. Your starting basemap depends on the keys you've added. 1. **Light up the sky.** Take the **Live Contacts** mission (or turn on **Flights** yourself) — thousands of live aircraft, gliding on real telemetry, detection mesh already reading the scene. Click one: the camera locks on, a trail draws behind it, and its live telemetry card comes up. 2. **Take the controls.** Hit **COCKPIT** on your tracked plane and ride it down, switching sensors mid-flight: NVG into Ironbow FLIR. -![Riding with a live aircraft in cockpit view while switching sensor modes](docs/media/06-cockpit-ar.gif) - 3. **Drop into a busy airport.** Search one and descend to the taxiways with **3D** aircraft on — grounded contacts, taxi trails, the whole apron working in real time. -![Moving from a full airport overhead down to close taxiway inspection with 3D flight models](docs/media/start-here/airport-ground-traffic-google-3d.gif) - 4. **Look through a public camera.** Turn on **Cameras** over Austin, London, California, Finland, or Delaware (live video). The feeds aren't webcam embeds — they project _into_ the 3D city. Cycle coverage to **VIEWSHED** and every camera draws its estimated coverage volume — where it reaches, and where it goes blind. -![Diving into an Austin intersection with a live public camera projected into the 3D scene](docs/media/03-austin-cctv.gif) - 5. **Track something in orbit.** Turn on **Satellites** and click the ISS — you ride along at orbital distance, orbit ring and all. -![Tracking the ISS along its orbital path as it crosses over Ukraine](docs/media/14-iss-over-ukraine.gif) - 6. **Switch the optics.** Tap `1`–`6` — CRT, NVG, FLIR — and the whole live planet re-renders through a different sensor. -![Cycling a dense live globe through CRT, FLIR, and NVG in one continuous view](docs/media/01-style-sweep.gif) - 7. **Talk to it** _(needs an OpenAI key)_: _"Take me to LAX and select the nearest airborne aircraft."_ 8. **Come home.** Hit **Reset Globe** — or just say _"zoom out to a globe view."_ **Keyboard:** `1`–`6` visual styles · `H` HUD · `D` detection · `C` CCTV · `` ` `` frame rate · `Esc` out. Trackpad pinch zooms the globe. --- - -## 🛩️ The Cockpit - -> Every plane should let you do this. - -Real-time cockpit mode, built from live flight data: the camera rides your contact with real terrain holding underneath, all the way down — sensor styles come along for the ride, and **Contacts** keeps the 250 km roster one click away: jump plane to plane and fall straight into the next cockpit. - -![Jumping between live aircraft and falling straight into a cockpit view](docs/media/12-switch-aircraft-cockpit.gif) - -The cockpit even carries its own briefing strip: nearby live signals, regional headlines, and real local weather — with an opt-in **WX** mode that renders volumetric clouds from actual observations around your aircraft. - -![A live military contact ridden through Normal, NVG, and Ironbow FLIR with dense detection](docs/media/start-here/military-cockpit-dense-google-3d.gif) - -_Why cockpit mode exists: you're riding a real aircraft over real terrain — and you get to pick which sensor you see the world through._ - ---- - ## 🎙️ Talk to It +
+Providers, chat, ChatGPT OAuth and the voice check + The standalone app offers **OpenAI** and **Gemini** under **AI Provider** in Settings, one choice shared by voice and chat. OpenAI is the initial default; your choice is saved in this browser. To use Gemini, add `GEMINI_API_KEY` in Provider Settings or your local `.env` file, then select Gemini. `GEMINI_LIVE_MODEL` defaults to `gemini-3.8-live`. The permanent key stays on the local server, which issues a constrained, single-use session credential. Changing provider ends the current conversation. If voice is on, the new provider starts with the same open-mic or push-to-talk mode; a held Space key is not carried over. Gemini uses the same map actions and captions, but has no OpenAI cost meter or MINI tier. When Gemini reports that its session has expired, start voice again for a new conversation. The AI Provider setting does not change the OpenAI-backed AI HUD summary. @@ -376,6 +386,8 @@ GEV reads Codex's file credentials but does not write or refresh them. It checks For a live voice check, run `node scripts/qa-voice-auth.mjs http://127.0.0.1:4189 oauth microphone.wav` against your local dev server. Use a WAV with three seconds of leading silence followed by a short spoken reply request. Replace `oauth` with `api-key` to check the API-key path. The check verifies audio input, a completed spoken reply, usage, resource cleanup, and reconnect. It saves screenshots and credential-free results under `.gev-logs/voice-auth/`. +
+ Click **GEV MIC**, grant the microphone, and just talk. This is more than a voice-controlled remote: - **🧠 It knows what it's looking at.** The agent pulls live scene context before answering — including coordinates, street names, active layers, and view scale. Ask _"what city is this?"_ mid-flight and it knows. @@ -400,10 +412,6 @@ camera input stops rotation. **✍️ Or draw it yourself** — UTILITIES ▸ **Draw**: pick Area, Line or Pin and a colour, click the vertices on the real world, double-click to finish, then name, recolour, hide or fly to each shape from its row. Same whiteboard, same persistence, no microphone needed. -![Zilker Park and Lady Bird Lake drawing onto the 3D city as persistent vector annotations, by voice](docs/media/01-voice-annotate-zilker.gif) - -![A spoken distance measurement spanning an airport, inspected from orbit](docs/media/04-airport-distance.gif) - **🔎 Interrogate it** — analyst queries against the live layers: > 🗣️ _"How many flights are over Texas right now?"_ · _"Which ships are headed to Oakland?"_ · _"What is the biggest fire near Los Angeles?"_ · _"Is anything flying above forty thousand feet?"_ · _"When does the ISS pass over next?"_ · _"How many datacenters are in view?"_ @@ -416,10 +424,6 @@ camera input stops rotation. > 🗣️ _"Show me global infrastructure."_ (stages the layers and pulls back to the globe) · _"Play Orbital Watch."_ (a full cinematic scene) · _"Set detection density to fifty percent."_ · _"Next contact — helicopters only."_ (mid-cockpit) · _"Show me space missions."_ · _"Switch to OSM."_ · _"Sharpen the image a touch."_ · _"Switch to the tactical layout."_ · _"What's turned on right now?"_ -![The globe populating with the world's radio stations as another live layer](docs/media/15-global-radio-layer.gif) - -_Ask for radio near anywhere and the globe starts broadcasting — every station is a real place you can fly to._ - --- **💬 Or ask from Claude and Codex.** God's Eye View is also an MCP server: ask Claude Desktop, Codex or ChatGPT desktop to show a place, and the live globe opens right in the conversation. Setup takes a minute — see [docs/MCP_SETUP.md](docs/MCP_SETUP.md). @@ -428,6 +432,9 @@ _Ask for radio near anywhere and the globe starts broadcasting — every station Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some offer additional capabilities with a provider key. (🟢 no key · 🟡 free key · 🔴 metered.) +
+All twenty-three layers and map sources, with sources and keys + | Layer | What you get | Source | Auth | | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- | | 🗺️ **Map Stack** | Esri satellite imagery, Google Photorealistic 3D, OSM, plus additional ion-hosted stacks | Esri / Google / Ion / OSM | 🟢 Esri satellite + OSM · 🟡 ion-hosted Google 3D + world terrain · 🔴 direct Google + place search | @@ -459,6 +466,8 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of | 🌦️ **Observed Weather** | Rain radar (contiguous US), Satellite clouds (GOES regional or global infrared, Clouds only or Full image) and Lightning density (Americas and Pacific) on one history timeline | NOAA nowCOAST | 🟢 | | 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones for the Atlantic and eastern/central North Pacific | NOAA NHC / CPHC | 🟢 | +
+ **Weather, keyless.** **Wind** animates 10 m forecast flow from NOAA GFS or ECMWF IFS, with an optional color field and a reading at map center. **Rain radar**, **Satellite clouds** and **Lightning density** are observations on one history timeline in the **WEATHER** panel (step back, **Play**, **Latest**); **Cyclone advisories** draw NHC and CPHC positions, forecast tracks and cones. On Google 3D Tiles the observed layers float above the city as translucent shells, sharpened around your view. In the app, **Data Layers** groups them as Movement, Cameras, Infrastructure, Events, Weather and Audio; Directions and OSM Places sit in the separate **Utilities** panel with Draw and Import. @@ -471,20 +480,17 @@ In the app, **Data Layers** groups them as Movement, Cameras, Infrastructure, Ev | 🟡 A free Cesium ion token | **Google Photorealistic 3D cities** and world terrain — eligible personal, non-commercial use; current ion terms and quotas apply | | 🔴 A Google Maps key | The same 3D direct from Google, plus Google place search — the billing-enabled, metered route | -![A reconstructed Falcon 9 ascent climbing and curving into its projected orbit](docs/media/08-falcon9-replay.gif) - -_The Space Missions layer replaying a Falcon 9 ascent — labeled `RECONSTRUCTED ESTIMATE`, scrubbable 0.25×–4×._ - **Also on the globe:** neighborhood overlays · an optional cockpit WX cloud effect. **Bundled static infrastructure:** Datacenters (4,352), Dams (704), and Submarine Cables (712). -![Diving into the Bahamas and revealing labeled submarine cable routes beneath the globe](docs/media/09-undersea-cables.gif) - **Missing a layer you want?** Open an issue — or add it and send the PR. --- ## 📷 Street Level +
+Street Level setup and use + > Street-level photos from any provider in one panel. This build ships **Mapillary** (a free client token), **Google Street View** (your Google Maps key), **KartaView** and **Panoramax** (no key). **Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it Street Level starts on **KartaView** instead, and the Mapillary chip says which key to add. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** and **Panoramax** need nothing: their public APIs are keyless. @@ -493,37 +499,26 @@ _The Space Missions layer replaying a Falcon 9 ascent — labeled `RECONSTRUCTED Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1*panoramax-0` KartaView on and `0.m.0_0.r.google-0*kartaview-0*panoramax-1` Panoramax on, as the app writes them (`0.m.0_0.r.kartaview-1` and `0.m.0_0.r.panoramax-1` work too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`. -## 🎖️ Field Missions +
-Once the basics click, run these: +## 🎬 Reconstructions and the Series -| Mission | How | -| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **🚁 Ask the planet** | _"Why are all these military helicopters flying in circles?"_ Select a military track — it silently backfills ~24 h of real trace history — and see what it's been doing, resolved as stacked 3D loops. | -| **✈️ Final approach** | Click-track an airliner lining up for a runway, hop into the **cockpit**, and ride it down. | -| **🌃 Night watch** | Fly to your own city, switch to **NVG**, and let the detection mesh and HUD read the scene. | -| **🚢 Port call** | Vessels on over the Port of Long Beach. Click a tanker for its tactical card and wake trail — then hit **NEAREST** in the CCTV panel and look at the same water through a public camera. | -| **📻 Tokyo FM** | Orbit Shibuya with the **Radio** layer on — then drag the analog tuner needle: every position snaps to a real station and the globe flies to whoever's broadcasting. | -| **🔥 Fire line** | FIRMS over California. Click a detection — the camera dives to it — read the intensity, then hit **NEAREST** in the CCTV panel for a ground view. | -| **🚶 Ask for a walking route** _🎙️_ | Tell the world where you want to go and watch a real street-following route trace itself through the 3D city — then _"fly it"_: banked turns, eased ends, a camera that leads the path like a drone shot. | -| **📏 Measure LAX to DFW** _🎙️_ | _"How far is LAX from DFW?"_ — an arrow spans the country, the distance lands in the caption, and the endpoints stay pinned to the real world as you orbit. | -| **🚀 Launch replay** | Open **Space Missions**, pick a launch from the last 30 days, and ride the T-minus countdown through ascent to orbit — scrub it at 0.25×–4×. Labeled `RECONSTRUCTED ESTIMATE`, because it is one. | -| **🪦 Walk the boneyard** | Fly from regional context down into dense, fully resolved rows of retired aircraft. | -| **🏗️ Orbit Three Gorges** | Sweep the dam and its terrain at a glance — then flip on the **Dams** layer and find 703 more. | +This started as a mad science experiment that suddenly blew up. Next thing you know, Iran happened. Bilawal reconstructed it in 4D. The questions we kept getting: when can I use this thing, and can I bring my own data to the party? -_🎙️ = voice missions — they need an OpenAI key._ + + + + + + + + + + + +
God's Eye View Blew Up. Here's What You Can Do With It.
God's Eye View Blew Up. Here's What You Can Do With It.
3.1M views on YouTube
I Built God's Eye View to Monitor Iran in 4D
I Built God's Eye View to Monitor Iran in 4D
1.9M views on YouTube
We Got Open Source God's Eye Before GTA 6
We Got Open Source God's Eye Before GTA 6
1.2M views on YouTube
Florida Learjet Crash - Final 78 Seconds Reconstructed in God's Eye View
Florida Learjet Crash - Final 78 Seconds Reconstructed in God's Eye View
3.5M views on YouTube
God's Eye View Reveals Iran's Chokehold on the Global Economy
God's Eye View Reveals Iran's Chokehold on the Global Economy
700K views on YouTube
God's Eye View Just Got a Massive Upgrade (Thanks To You!)
God's Eye View Just Got a Massive Upgrade (Thanks To You!)
502K views on YouTube
-![Resolving a selected aircraft's recent flight path into stacked 3D loops above the terrain](docs/media/07-helicopter-loops.gif) - -_Ask the planet: a military contact's last ~24 hours of real trace history, resolved as stacked 3D loops._ - -![Asking for a walking route and flying the generated path through the 3D city](docs/media/10-walking-route-flythrough.gif) - -_"Draw the walking route… now fly it" — banked turns, eased ends, the camera leading the path like a drone shot._ - -![Descending from regional context into dense rows of retired aircraft at the boneyard](docs/media/08-boneyard.gif) - -_Walk the boneyard: rows of retired airframes, fully resolved in 3D._ +More reconstructions, interviews and press: [godseyeview.ai/press](https://godseyeview.ai/press/) · [the full series on YouTube](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q) --- @@ -532,7 +527,7 @@ _Walk the boneyard: rows of retired airframes, fully resolved in 3D._ How the globe handles live data: - **World-stable icons.** Aircraft and ships point along their _true real-world heading_ at every camera angle — tracked or not, looking straight down or across the horizon — via per-frame screen-space course projection. No spinning, no viewport-locking. -- **Smooth motion from choppy data.** Live feeds arrive every 15–30s; the globe renders one interval behind real time and interpolates between known fixes. Dead reckoning fills the gaps. +- **Smooth motion from choppy data.** Live feeds arrive every 15–30s, often minutes late; the globe renders as far behind real time as the feed is late (at least one interval) and draws each aircraft along a smooth curve between its known fixes. Dead reckoning fills the gaps. - **Honest satellites.** SGP4 propagation with orbit rings that stay locked to their satellites via GMST realignment — no drift, no per-second flicker. - **Sits on the real ground.** Entity heights are aligned to work with Google 3D tiles, so aircraft park on aprons and cameras stand on street corners instead of floating. - **Caching and request budgets.** An OpenSky credit governor, a TomTom daily tile budget, and disk-cached TLEs reduce repeated requests. These controls do not replace provider quotas or billing controls. @@ -549,7 +544,7 @@ src/ ├── voice/ # OpenAI Realtime session + 30 voice tools ├── layers/ # Layer components — weather, wind, cyclones, transit, ALPR, … ├── data/ # One module per layer + orchestration + context store -│ ├── iconOrientation.js # Screen-projected headings + horizon cull +│ ├── iconOrientation.js # Horizon backdrop for labels (headings: screenRotation.js) │ └── local_data/ # Bundled datasets (per-folder provenance) └── scenes/ # Cinematic scene director ``` @@ -590,10 +585,6 @@ metered and Liveuamap is a paid subscription: | 🟡 | **World News API** | 📰 News layer, Local: the news of the country in view. The free plan allows 50 points a day; `WORLDNEWSAPI_DAILY_READS` (default 30) keeps Core inside it. Core keeps each country's news for up to 1 hour, and World News API's [terms](https://worldnewsapi.com/terms/) allow caching only with its prior written permission, which is yours to get. The Data attribution popover credits it with a link | [worldnewsapi.com/console](https://worldnewsapi.com/console/) — free plan | | 🔴 | **Liveuamap** | 📰 News layer, Conflicts: Liveuamap's mapped items beside GDELT's reports (🟢 Conflicts works without) | [liveuamap.com/promo/api](https://liveuamap.com/promo/api) — paid API | -![Diving from city-scale live congestion straight into an intersection's public camera](docs/media/05-traffic-to-cctv.gif) - -_What the TomTom key buys you: rush-hour density painted on the city — then dive from the jam straight into the camera watching it._ - ### Cherry on top | | Key | Why | Get it | @@ -704,7 +695,7 @@ God's Eye View runs on **public data, clear sources, and local-first execution.* **Maintainers:** [Bilawal Sidhu](https://github.com/bilawalsidhu) and [Sameh Khamis](https://github.com/samehkhamis) at [Halfpixel](https://halfpixel.ai). -Media note: the capture GIFs on this page show Google Photorealistic 3D Tiles and live data layers, used promotionally with in-frame attribution; they aren't licensed for standalone reuse. See [media provenance and permissions](docs/media/README.md); full source terms in [DATA_SOURCES.md](DATA_SOURCES.md). +Media note: the clips on this page are the ones shown on godseyeview.ai. Some show Google Photorealistic 3D Tiles and live data layers, used promotionally with in-frame attribution; they aren't licensed for standalone reuse. See [media provenance and permissions](docs/media/README.md); full source terms in [DATA_SOURCES.md](DATA_SOURCES.md). > [!IMPORTANT] > God's Eye View is an exploratory visualization of public and third-party data. @@ -725,13 +716,13 @@ So here it is. Step inside the spy-thriller cockpit — except the data is real One heads-up from the inside: build in this space for a week and you learn that **the present is the cheap part**. The moment you try to go back in time — tiling, serving, and scrubbing _what happened_ and _what changed_ at any real resolution — the data gets expensive and the compute gets brutal. That's the long game. -**Update — a hosted version is coming.** We originally planned to keep this repository as the open-source client and build a separate professional product. Then the launch happened, and the loudest request wasn't another feature — it was _"just give me a link."_ So we're building an official hosted God's Eye View at [Halfpixel](https://halfpixel.ai): no installation, just open it in your browser. The hosted version is the easiest way into this open-source project. More soon. +**Update — a hosted version is coming.** We originally planned to keep this repository as the open-source client and build a separate professional product. Then the launch happened, and the loudest request wasn't another feature — it was _"just give me a link."_ So we're building an official hosted God's Eye View at [Halfpixel](https://halfpixel.ai): no installation, just open it in your browser. The hosted version is the easiest way into this open-source project. Sign up for the [waitlist](https://godseyeview.ai/online/) and get notified. ---
-▶️ [Watch the God's Eye View series](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q) · 📬 [Map the World](https://maptheworld.ai/) — the newsletter behind the project +🌐 [godseyeview.ai](https://godseyeview.ai), the official site · ▶️ [Watch the God's Eye View series](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q) · 📬 [Map the World](https://maptheworld.ai/) — the newsletter behind the project **🌐 God's Eye View. No place left behind.** diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 4ed2ea418b..de7c4f2ea2 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -2,7 +2,8 @@ The project depends on third-party npm packages whose own licenses apply. This file records the packages added for the browser-local SDR feature, the -Street Level viewer and the Data Library's GeoParquet reader; the complete resolved dependency inventory remains in +Street Level viewer, the Data Library's GeoParquet reader and the GNSS Integrity +layer's hexagon grid; the complete resolved dependency inventory remains in `package-lock.json`. ## Web RTL-SDR @@ -60,3 +61,20 @@ Street Level viewer and the Data Library's GeoParquet reader; the complete resol - Author: Copyright (c) 2020 Arjun Barrett - Source: - License: MIT + +## kdbush + +- Package: `kdbush` 4.0.2 (the screen index that groups points drawn too + close together into clusters) +- Author: Copyright (c) 2018, Vladimir Agafonkin +- Source: +- License: ISC + +## H3 (h3-js) + +- Package: `h3-js` 4.4.0 (the GNSS Integrity layer's H3 hexagon cells) +- Author: Copyright 2017-2021 Uber Technologies, Inc. (includes the H3 C + library 4.4.1, compiled to JavaScript) +- Source: +- License: Apache License 2.0 +- License text: diff --git a/changelog.d/1579-render-failure-notice.md b/changelog.d/1579-render-failure-notice.md new file mode 100644 index 0000000000..2045ae823d --- /dev/null +++ b/changelog.d/1579-render-failure-notice.md @@ -0,0 +1,6 @@ +- When the globe stops drawing after a render error or a lost WebGL context, + an alert dialog says so instead of leaving a frozen or black globe behind + working controls. Retry restarts drawing (Reload after a lost context), and + Reset view reopens the app without the view restored from the address bar. + Cesium's "Rendering has stopped" panel no longer appears in the app + (German, @gekh, #1579). diff --git a/changelog.d/1686-cockpit-subjects.md b/changelog.d/1686-cockpit-subjects.md new file mode 100644 index 0000000000..715561e8e2 --- /dev/null +++ b/changelog.d/1686-cockpit-subjects.md @@ -0,0 +1,12 @@ +- Let an application add its own Cockpit subjects through + `services.cockpitSubjects`. A provider supplies the subject's position, + heading and HUD (in the page's language, via `getLocale` and + `onLocaleChange` from `./i18n`); the camera can follow it without the + ground clamp, anchored exactly on it, and a generic HUD adds source rows, a + banner, a veil (off under reduced motion) and a bottom progress line. The + Rail and Transit layers expose read and hold APIs so a selected train or + vehicle can be ridden, and `./layers/rail/paths` is exported; that export + and the read APIs are experimental. `docs/APPLICATION.md` shows a minimal + provider. GEV itself registers none, and entry to the built-in aircraft, + satellite and vessel views is unchanged; a provider's subject takes entry + when it was selected after them (Denis Groshev, @ZloyS, #1686). diff --git a/changelog.d/1700-i18n-plurals-context.md b/changelog.d/1700-i18n-plurals-context.md index 3cab4fa57f..6f206ba154 100644 --- a/changelog.d/1700-i18n-plurals-context.md +++ b/changelog.d/1700-i18n-plurals-context.md @@ -2,6 +2,6 @@ Data Library list, the News time window, the GhostMaps event age and the bridge radar range now read "1 Tag" and "7 Tage", «0,75 МОР. МИЛИ» and «12 МОР. МИЛЬ». Street level words "the view centre" in each language's - grammar, and Latest, FOCUS, CONFIRMED and the course readout each have - their own translation where one word served two places (German, @gekh, - #1700). + grammar, the News heading Latest agrees with the news it heads, and FOCUS, + CONFIRMED and the course readout each have their own translation where one + word served two places (German, @gekh, #1700). diff --git a/changelog.d/1714-fleet-models.md b/changelog.d/1714-fleet-models.md new file mode 100644 index 0000000000..adf11676d5 --- /dev/null +++ b/changelog.d/1714-fleet-models.md @@ -0,0 +1,8 @@ +- Draw every 3D model from the project's procedural fleet set: 121 models + (about 2 MB, MIT like the code) chosen per vehicle by type and drawn life + size, replacing the eight third-party aircraft models. Flights, Military + Flights and Local ADS-B pick a model by ICAO type, class and emitter + category; Vessels, Transit and Rail now draw models too, under the same 3D + toggle and distances, a ship at its AIS length and beam and a tram, bus or + train in its mode or category colour. The whole set loads once when a layer + starts (samehkhamis, #1714). diff --git a/changelog.d/1715-vessel-typical-length.md b/changelog.d/1715-vessel-typical-length.md new file mode 100644 index 0000000000..9cb5899746 --- /dev/null +++ b/changelog.d/1715-vessel-typical-length.md @@ -0,0 +1,3 @@ +- Draw a vessel whose feed sends no length at its ship type's typical size, so + a cruise ship or container ship no longer shows as its type's smallest model + (samehkhamis, #1715). diff --git a/changelog.d/1723-cctv-panel-collapse-on-disable.md b/changelog.d/1723-cctv-panel-collapse-on-disable.md new file mode 100644 index 0000000000..ae5a494459 --- /dev/null +++ b/changelog.d/1723-cctv-panel-collapse-on-disable.md @@ -0,0 +1,5 @@ +- Collapse the CCTV panel when the layer is switched off. It stayed open with + an empty frame and a meta line that still described the last camera; the + meta line of a disabled layer now reads the catalog count. Contacts, Space + Missions and Clear selected data layers leave the panel as it is + (asturksever, #1723). diff --git a/changelog.d/1729-fleet-ground-vehicles.md b/changelog.d/1729-fleet-ground-vehicles.md new file mode 100644 index 0000000000..ed198f27a3 --- /dev/null +++ b/changelog.d/1729-fleet-ground-vehicles.md @@ -0,0 +1,5 @@ +- Draw airport ground vehicles and ground stations as what they are instead of + the generic plane. An airport vehicle (type `ZVEH`) is a fire truck, pushback + tug, van or car by its callsign, a ground station (`GRND`) is a new 11.8 m + radio mast, and one with no altitude stands on the ground instead of at the + 10 km airborne default (samehkhamis, #1729). diff --git a/changelog.d/1730-airport-vehicle-models.md b/changelog.d/1730-airport-vehicle-models.md new file mode 100644 index 0000000000..c491effa4e --- /dev/null +++ b/changelog.d/1730-airport-vehicle-models.md @@ -0,0 +1,4 @@ +- Draw airport ground vehicles as real shapes instead of stacked boxes: the + car is an operations SUV, the van a high-roof panel van, the fire truck an + airport crash tender with turrets and the pushback a low tug with a glazed + cab, all on the ground at their built size (samehkhamis, #1730). diff --git a/changelog.d/1731-aircraft-mesh-colours.md b/changelog.d/1731-aircraft-mesh-colours.md new file mode 100644 index 0000000000..5443c3a1d1 --- /dev/null +++ b/changelog.d/1731-aircraft-mesh-colours.md @@ -0,0 +1,3 @@ +- Draw aircraft models in their own mesh colours instead of a 94% flat + white (amber for military) over the model; the tracked and emergency + colours now tint the mesh without hiding its paint (samehkhamis, #1731). diff --git a/changelog.d/1732-no-track-true-heading.md b/changelog.d/1732-no-track-true-heading.md new file mode 100644 index 0000000000..1f01a10975 --- /dev/null +++ b/changelog.d/1732-no-track-true-heading.md @@ -0,0 +1,4 @@ +- An aircraft that reports no ground track (parked or taxiing, from adsb.lol + or a local receiver) now faces its reported true heading instead of north, + so one taxiing south no longer looks like it is moving backwards + (samehkhamis, #1732). diff --git a/changelog.d/1733-buoy-models.md b/changelog.d/1733-buoy-models.md new file mode 100644 index 0000000000..a2de9e612a --- /dev/null +++ b/changelog.d/1733-buoy-models.md @@ -0,0 +1,11 @@ +- Draw aids to navigation as buoys instead of ships: a buoy, beacon, RACON, + light or mark from the vessel feed (or any AIS station numbered 99MIDxxxx) + is now the fleet set's buoy of its IALA mark (cardinal, port or starboard + hand, safe water, isolated danger or special mark), standing still with no + heading, and its icon is a disc rather than a chevron. Its card and readout + show its kind of mark with no speed or heading. AISStream now subscribes to + aid-to-navigation reports and names each by its kind of mark and its full + name; the feed lists every ship ahead of any aid, and `vessels_in_area` + counts ships only. A virtual aid (a mark broadcast where nothing physical + stands) keeps its disc, is never drawn as a buoy, and its card says it is + virtual; vessel sources may mark any record `virtual` (samehkhamis, #1733). diff --git a/changelog.d/1734-transit-route-type-models.md b/changelog.d/1734-transit-route-type-models.md new file mode 100644 index 0000000000..f451376e34 --- /dev/null +++ b/changelog.d/1734-transit-route-type-models.md @@ -0,0 +1,10 @@ +- Draw transit vehicles as their kind, not one of five: trolleybuses, cable + cars, funiculars, gondolas and monorails are modes of their own, with their + own icon, colour, card word and fleet model. A vehicle record may carry its + route's GTFS `route_type` (`routeType`), which settles its mode before the + feed's route hints and picks the finer model (a coach for 200, a high-speed + set for 101). Prague's trolleybuses and Petřín funicular, and Bucharest, + Cluj and Turin's trams, trolleybuses and metro lines, now read as such from + the route ids in each operator's routes.txt. Le Havre's funicular, which its + routes.txt types as a bus, is a named correction that outranks the route + type (samehkhamis, #1734). diff --git a/changelog.d/1735-side-rails-edge.md b/changelog.d/1735-side-rails-edge.md new file mode 100644 index 0000000000..1ecee150c7 --- /dev/null +++ b/changelog.d/1735-side-rails-edge.md @@ -0,0 +1,5 @@ +- Move Visual to the left rail, after Data Layers, Utilities and Authoring, and + lead the right column with Context; an open Context or CCTV panel takes the + column's full height. A switch in each panel header moves that side's panels + over their rail to the screen edge, and the scroll wheel at a screen edge + steps through that side's panels (manjunath22466, samehkhamis, #1735). diff --git a/changelog.d/1736-timeline-scrub-ages-cloud-gaps.md b/changelog.d/1736-timeline-scrub-ages-cloud-gaps.md new file mode 100644 index 0000000000..4c8deafe8f --- /dev/null +++ b/changelog.d/1736-timeline-scrub-ages-cloud-gaps.md @@ -0,0 +1,9 @@ +- Fix three time readings on the world timeline. A scrub near now goes live + only within two minutes of now, however long the track: with a layer whose + source covers years, any time in the last few weeks used to snap to live. + Fire cards and fire details count a detection's age from the end of the + 24 hours shown, and from now only when live, so a window that ended months + ago reads "new 3h" rather than "new 105d". Weather and satellite cloud + frames stay shown, and the latest reads late, for at least one and a half + of the feed's own frame spacings, so a feed whose frames come an hour apart + no longer goes blank for half of every hour (samehkhamis, #1736). diff --git a/changelog.d/1737-placement-provider.md b/changelog.d/1737-placement-provider.md new file mode 100644 index 0000000000..5d461a6dd8 --- /dev/null +++ b/changelog.d/1737-placement-provider.md @@ -0,0 +1,7 @@ +- Let a host application decide where live contacts are drawn. + `createApplicationCatalog({ placement })` takes a placement provider whose + `layer(kind)` hands Flights, Military Flights, AIS Vessels, Transit and Rail + a `place(id, wallMs)` (and optionally `observe(id, fix)`, `forget(id)`): + each layer tells it every live fix it accepts and draws a contact where it + places it. Without one, or for a contact it does not place, every layer + moves as before (samehkhamis, #1737). diff --git a/changelog.d/1738-visual-panel.md b/changelog.d/1738-visual-panel.md new file mode 100644 index 0000000000..748591426a --- /dev/null +++ b/changelog.d/1738-visual-panel.md @@ -0,0 +1,4 @@ +- Group the Visual panel into Look, Map source, Overlay and Effects with a + Reset at its foot, and add a Scope opacity slider (50–100%) that share links + carry when it is below full; Reset keeps the HUD layout, and the HUD gets + shadows when Scope is off (manjunath22466, samehkhamis, #1738). diff --git a/changelog.d/1739-cockpit-side-panels.md b/changelog.d/1739-cockpit-side-panels.md new file mode 100644 index 0000000000..a15167d325 --- /dev/null +++ b/changelog.d/1739-cockpit-side-panels.md @@ -0,0 +1,4 @@ +- Give the desktop cockpit the main page's side rails: Data Layers alone on the + left, and Display and Radio as a right rail that opens one panel at a time + beside it, at the same height, with Contact and Live Signals restyled to + match (manjunath22466, samehkhamis, #1739). diff --git a/changelog.d/1740-layer-finder.md b/changelog.d/1740-layer-finder.md new file mode 100644 index 0000000000..6079c6f44e --- /dev/null +++ b/changelog.d/1740-layer-finder.md @@ -0,0 +1,3 @@ +- Add a search and a filter (On / Off and category) to the Data Layers panel, + matching layer names in the UI language, and a section index down its side + that jumps to each group (manjunath22466, samehkhamis, #1740). diff --git a/changelog.d/1741-message-overrides.md b/changelog.d/1741-message-overrides.md new file mode 100644 index 0000000000..ebba693b3a --- /dev/null +++ b/changelog.d/1741-message-overrides.md @@ -0,0 +1,6 @@ +- Let an application that composes Core use its translator and word Core's + messages its own way. The `./i18n` entry exports `t`, `tn`, `msg`, + `translateKnown` and the number and date formatters, and + `setMessageOverrides({ en: {…}, de: {…} })` shows the application's text for + any catalog key, in the active locale or else in English (samehkhamis, + #1741). diff --git a/changelog.d/1743-wikidata-cities.md b/changelog.d/1743-wikidata-cities.md new file mode 100644 index 0000000000..5c9fb684fd --- /dev/null +++ b/changelog.d/1743-wikidata-cities.md @@ -0,0 +1,3 @@ +- Bundle 31,827 cities from Wikidata (CC0) for offline place lookups: the + nearest city, the cities around a point and a city by name, matched without + accents (manjunath22466, samehkhamis, #1743). diff --git a/changelog.d/1744-weather-source-name.md b/changelog.d/1744-weather-source-name.md new file mode 100644 index 0000000000..8ebbf855a8 --- /dev/null +++ b/changelog.d/1744-weather-source-name.md @@ -0,0 +1,4 @@ +- A weather source can name its provider for each product with + `sourceName(kind)`; the Rain radar, Lightning density and Satellite clouds + rows show it until a manifest names its own, instead of always saying NOAA + nowCOAST (samehkhamis, #1744). diff --git a/changelog.d/1745-timeline-one-control-and-marks.md b/changelog.d/1745-timeline-one-control-and-marks.md new file mode 100644 index 0000000000..2585b47608 --- /dev/null +++ b/changelog.d/1745-timeline-one-control-and-marks.md @@ -0,0 +1,51 @@ +- Timeline marks have labels. Hovering a tick shows its label (a launch's + mission name, or an earthquake's magnitude and place, such as + `M6.4 · 113 km SSE of Lata, Solomon Islands`), and a tap on or within 6 px + of a tick goes exactly to its mark rather than to the point tapped; a tap + elsewhere and a drag work as before. The arrow keys still step from mark to + mark, and the handle then tells the mark's label with the time to screen + readers and shows it over the track while focused. A layer's world clock + coverage may give each mark as `{ time, label, id, kind }` as well as a + bare time. `worldClock.coverage()` keeps `marks` as the sorted times and + adds `markDetails`, the merged marks themselves, merged on their whole + label; a label longer than `WORLD_CLOCK_MARK_LABEL_LENGTH` (60 characters, + exported from `gods-eye-view/time`) is then cut, ending in `…`, never + splitting an emoji. A zoom or a pan clears the hovered label, and a label + is never wider than the track (samehkhamis, #1745). +- The timeline marks only events: launches, and earthquakes of magnitude 6 + and up while the Earthquakes layer is on (about one every two days + worldwide). It no longer draws a tick for every weather frame, which came + every few minutes and made the track a wall of dashes; the weather frames + still set the time the timeline covers, and Play still waits at each next + frame until it loads. With no mark ahead, the arrow keys step along the + track. The map still draws every earthquake, and an earthquake layer never + widens the timeline beyond its strong quakes' own times. The Earthquakes + layer registers with the world clock (`gods-eye-view/time`) once it is + initialised, and has time to show only while on; + `gods-eye-view/layers/earthquakes` adds `EARTHQUAKE_MARK_MAGNITUDE`, + `earthquakeMagnitudeTitle`, `earthquakeMarkLabel` and `earthquakeCoverage`. + A weather row's `step` param goes to the previous or next weather frame + (samehkhamis, #1745). +- The main timeline is the only time control. The Weather panel no longer + has a slider, step buttons, Latest or Play of its own; it shows the frame + time instead: the newest frame and its age while live, the timeline time + alone at a past time; while live it shows the newest frame even when the + products are suspended (reduced motion, a hidden page, no imagery host). + The timeline's Play runs the world clock at the chosen speed for weather + too, stopping at each next frame until it loads, rather than stepping the + observed frames every two seconds and going round from the last to the + first. A weather row's `play` and `latest` params move the world clock as + the timeline does: `play` runs at the timeline's chosen speed, from the + start when live or at the end, and does nothing while every product the + row shows is suspended or while there is no time to show. The world clock + keeps a chosen rate while paused and live (`goLive()` no longer sets it + back to 1), so any play runs at it, and the timeline's speed shows the + clock's rate whoever set it (the nearest offered speed for another rate). + A weather layer made without a weather clock leaves the world clock alone + until it is first enabled, does nothing once destroyed, and destroying it + leaves the world clock's time where it is. **Breaking:** the catalog's + `weatherClock` (`gods-eye-view/application/layers`) no longer has + `setTarget`, `step`, `latest`, `play`, `pause` or `togglePlay`, its state + no longer has `playing`, and it no longer attaches itself to the world + clock as a driver; move time with the world clock (`gods-eye-view/time`, + also `weatherClock.world`) instead (samehkhamis, #1745). diff --git a/changelog.d/1746-satellites-every-frame.md b/changelog.d/1746-satellites-every-frame.md new file mode 100644 index 0000000000..deb52ae3aa --- /dev/null +++ b/changelog.d/1746-satellites-every-frame.md @@ -0,0 +1,5 @@ +- Move satellites every frame. Points were propagated once a second and held + still in between, so at 1 min/s they jumped about 45 px a second; each now + glides from its last SGP4 sample (position, velocity, gravity and its rate + of change) to the world time, resampled every second and whenever time + moves 30 s from it, within about 10 m of SGP4 (Sameh Khamis, #1746). diff --git a/changelog.d/1747-vessels-every-frame.md b/changelog.d/1747-vessels-every-frame.md new file mode 100644 index 0000000000..d0b452c47c --- /dev/null +++ b/changelog.d/1747-vessels-every-frame.md @@ -0,0 +1,5 @@ +- Move vessels every frame. Vessels between fixes, and live vessels a host + placement places, were redrawn at most every 250 ms with a frame asked for + once a second; they are now redrawn every frame, and the next frame is asked + for once the fastest drawn vessel will have moved half a pixel on screen + (Sameh Khamis, #1747). diff --git a/changelog.d/1748-clouds-feed-detail.md b/changelog.d/1748-clouds-feed-detail.md new file mode 100644 index 0000000000..bf4440e7dc --- /dev/null +++ b/changelog.d/1748-clouds-feed-detail.md @@ -0,0 +1,5 @@ +- A weather feed that supplies its own tiles can name how deep they go for + each product (`frameMaximumLevel`). Global satellite clouds are then drawn + from those tiles to that level instead of from one 2048 × 1024 image, so + they stay sharp when zoomed in; radar and the other tiled products take the + named level too. Without it, clouds keep the single image and level 3. diff --git a/changelog.d/1749-smooth-rewind.md b/changelog.d/1749-smooth-rewind.md new file mode 100644 index 0000000000..97ee20b69d --- /dev/null +++ b/changelog.d/1749-smooth-rewind.md @@ -0,0 +1,6 @@ +- Flights, military flights and vessels move back as smoothly as they move on. + A source whose snapshots at a time carry each contact's own fixes either + side of it (`timeline.spanMs`, record `fixes`) lets a seek or a drag back + within those fixes move every contact along its track, with no blank and no + wait; the step there then loads in place of every contact. A contact is not + drawn more than a minute before its first fix. diff --git a/changelog.d/1750-search-coordinate-formats.md b/changelog.d/1750-search-coordinate-formats.md new file mode 100644 index 0000000000..f6dbc4af33 --- /dev/null +++ b/changelog.d/1750-search-coordinate-formats.md @@ -0,0 +1,6 @@ +- Search reads coordinates written the other common ways, with no geocoder + or key: degrees, minutes and seconds (`40°26'46"N 79°58'56"W`), UTM + (`18T 585628 4511322`), MGRS (`18T WL 85650 11369`) and full plus codes + (`849VCWC8+R9`). Before, these went to the geocoders, which matched them + to some place by name or found nothing. Like decimal degrees, a query + either reads exactly or goes to the geocoders as before. diff --git a/changelog.d/1751-gnss-h3-cells.md b/changelog.d/1751-gnss-h3-cells.md new file mode 100644 index 0000000000..aca40437da --- /dev/null +++ b/changelog.d/1751-gnss-h3-cells.md @@ -0,0 +1,6 @@ +- GNSS Integrity bins aircraft into H3 resolution-4 hexagons, the grid + gpsjam.org uses, and draws each as its hexagon instead of a 0.5° square. As + on gpsjam.org, every hexagon with an aircraft is shown: the three-aircraft + minimum is gone, and discounting one bad aircraft remains the only + small-sample guard. Cells are keyed by their H3 index and carry their centre + and boundary. diff --git a/changelog.d/1752-uncapped-frame-rate.md b/changelog.d/1752-uncapped-frame-rate.md new file mode 100644 index 0000000000..db09e754b8 --- /dev/null +++ b/changelog.d/1752-uncapped-frame-rate.md @@ -0,0 +1,3 @@ +### Changed + +- While anything moves (layers in motion, the camera, a followed contact), the globe now draws at the display's own refresh rate instead of a fixed 60 frames a second. A parked scene still ticks at most 60 times a second. Waits that counted frames (a followed contact's first position, a shared follow view, a trail's temporary copy) now count drawn time, so they last the same at any refresh rate. Screen marks over a followed contact fade out over the same time at any refresh rate. diff --git a/changelog.d/1753-course-from-fixes.md b/changelog.d/1753-course-from-fixes.md new file mode 100644 index 0000000000..1c42498e32 --- /dev/null +++ b/changelog.d/1753-course-from-fixes.md @@ -0,0 +1,3 @@ +### Fixed + +- A civil or military aircraft whose feed sends neither a ground track nor a true heading now faces the way its newer positions went, instead of north, so a taxiing aircraft no longer appears to move sideways or backwards. An older position from another feed, or position noise on a parked aircraft, never turns it. diff --git a/changelog.d/1755-vessel-playback-frames.md b/changelog.d/1755-vessel-playback-frames.md new file mode 100644 index 0000000000..cf9404b968 --- /dev/null +++ b/changelog.d/1755-vessel-playback-frames.md @@ -0,0 +1,4 @@ +### Changed + +- Playing the world clock away from live now draws at the display's own refresh rate instead of at most 60 FPS. +- Vessels following a playing clock are moved again once the fastest would have moved half a pixel on screen, at least once a second, and at once when the camera moves or zooms. Before, every drawn vessel moved every frame by a fraction of a pixel, which took most of each frame with thousands of vessels in view. diff --git a/changelog.d/1758-ground-models-at-once.md b/changelog.d/1758-ground-models-at-once.md new file mode 100644 index 0000000000..4c8e08cc1d --- /dev/null +++ b/changelog.d/1758-ground-models-at-once.md @@ -0,0 +1,3 @@ +### Fixed + +- A grounded aircraft turns from its icon into its 3D model as soon as the 3D tiles under it have loaded. Tiles still streaming no longer count as a failed ground sample, so after a pan the models no longer appear late and in batches, up to half a minute after the view settled. diff --git a/changelog.d/870-hidden-contact-dr.md b/changelog.d/870-hidden-contact-dr.md deleted file mode 100644 index aab55229e0..0000000000 --- a/changelog.d/870-hidden-contact-dr.md +++ /dev/null @@ -1,4 +0,0 @@ -- Reduce dead-reckoning work for flights already hidden behind the horizon. - Hidden contacts update on a staggered one-in-13-ticks rotation (about once a - second) while visible contacts and contacts with fleet models retain the full - update path (Wilmer Alzate, #870). diff --git a/dev/conformance/index.html b/dev/conformance/index.html new file mode 100644 index 0000000000..16d48a5372 --- /dev/null +++ b/dev/conformance/index.html @@ -0,0 +1,114 @@ + + + + + + Renderer conformance + + + +
+

Renderer conformance

+ + + + + + +
+
+
+
+
+
+ + + diff --git a/dev/conformance/main.js b/dev/conformance/main.js new file mode 100644 index 0000000000..a1fb6c48a2 --- /dev/null +++ b/dev/conformance/main.js @@ -0,0 +1,256 @@ +/** + * The conformance page: runs the logic suite in the browser, and draws the + * reference scenes on a renderer to check them against the stored + * references (or record new ones). Driven by hand or through the + * chrome-devtools MCP; `window.conformance` exposes the same actions. + */ +import { + DEFAULT_TOLERANCE, + runConformance, +} from '../../src/render/conformance/index.js'; +import { + REFERENCE_SCENES, + sceneSupport, +} from '../../src/render/conformance/scenes.js'; +import { + compareImages, + drawScene, + referenceName, +} from '../../src/render/conformance/visual.js'; +import { createStubHarness } from '../../src/render/stub/harness.js'; +import { toEcef } from '../../src/render/stub/math.js'; +import { createCesiumSceneRenderer } from '../../src/render/cesium/sceneRenderer.js'; +import { + CESIUM_CHECKS, + createCesiumHarness, +} from '../../src/render/cesium/harness.js'; + +const REFERENCES = '/src/render/conformance/goldens/visual/'; +const SAVE = '/__conformance/references/'; +const ctx = { + toEcef, + assets: { + model: '/models/fleet/aircraft/c172.glb', + // Not served: the model failure check loads it. + missingModel: '/models/conformance-missing.glb', + }, +}; +const $ = (id) => document.getElementById(id); +const status = (text) => ($('status').textContent = text); + +const RENDERERS = { + cesium: () => createCesiumSceneRenderer({ container: $('stage') }), +}; + +const HARNESSES = { + stub: () => [createStubHarness('stub (browser)'), {}], + cesium: () => [ + createCesiumHarness({ + model: ctx.assets.model, + missingModel: ctx.assets.missingModel, + }), + { only: (id) => CESIUM_CHECKS.has(id) }, + ], +}; + +/** + * Runs the logic suite on `which`; `all` runs every check, listed or not; + * `only` (check ids) runs just those of them. + */ +async function runLogic(which = 'stub', { all = false, only } = {}) { + status(`running the logic suite on ${which}…`); + const [harness, options] = HARNESSES[which](); + const listed = all ? () => true : (options.only ?? (() => true)); + const report = await runConformance(harness, { + only: (id) => listed(id) && (!only || only.includes(id)), + }); + $('logicResults').innerHTML = + `

${report.harness}: ${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped

+ ${report.results + .filter((r) => r.status !== 'pass') + .map( + (r) => + ``, + ) + .join('')}
${r.status}${r.id}${escape(r.detail ?? '')}
`; + status(''); + return { + passed: report.passed, + failed: report.failed, + skipped: report.skipped, + failures: report.results.filter((r) => r.status === 'fail'), + skips: report.results.filter((r) => r.status === 'skip'), + }; +} + +const escape = (s) => + s.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]); + +async function pixels(blob) { + const bitmap = await createImageBitmap(blob); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const g = canvas.getContext('2d'); + g.drawImage(bitmap, 0, 0); + return g.getImageData(0, 0, bitmap.width, bitmap.height); +} + +// Object URLs shown for the current run, revoked when the next one starts. +let objectUrls = []; +function objectUrl(blob) { + const url = URL.createObjectURL(blob); + objectUrls.push(url); + return url; +} + +async function toUrl(imageData) { + const canvas = new OffscreenCanvas(imageData.width, imageData.height); + canvas.getContext('2d').putImageData(imageData, 0, 0); + return objectUrl(await canvas.convertToBlob()); +} + +/** The views the stored manifest lists, or none. */ +async function storedViews() { + try { + const res = await fetch(REFERENCES + 'manifest.json', { + cache: 'no-store', + }); + return res.ok ? ((await res.json()).views ?? []) : []; + } catch { + return []; + } +} + +async function reference(name) { + const res = await fetch(REFERENCES + name, { cache: 'no-store' }); + return res.ok && res.headers.get('content-type')?.startsWith('image/') + ? res.blob() + : null; +} + +/** Draws every scene; records references or compares against them. */ +async function runScenes({ record = false, only } = {}) { + const which = $('renderer').value; + const renderer = await RENDERERS[which](); + const results = []; + $('views').innerHTML = ''; + for (const url of objectUrls) URL.revokeObjectURL(url); + objectUrls = []; + try { + for (const scene of REFERENCE_SCENES) { + if (only && !only.includes(scene.id)) continue; + const unsupported = sceneSupport(scene, renderer, ctx); + if (unsupported) { + results.push({ scene: scene.id, status: 'skip', detail: unsupported }); + continue; + } + status(`${scene.id}…`); + // A scene the renderer refuses fails alone; the others still draw. + try { + await drawScene(renderer, scene, ctx, async (view, capture, settle) => { + const name = referenceName(scene.id, view.name); + const figure = document.createElement('figure'); + $('views').append(figure); + if (settle.state !== 'settled') { + const detail = `${settle.state}: ${settle.blockers.join(', ')}`; + results.push({ + scene: scene.id, + view: view.name, + status: 'fail', + detail, + }); + figure.innerHTML = `
${name}: ${escape(detail)}
`; + return; + } + if (record) { + const res = await fetch(SAVE + name, { + method: 'PUT', + body: capture, + }); + results.push({ + scene: scene.id, + view: view.name, + status: res.ok ? 'recorded' : 'fail', + detail: res.ok ? undefined : `save ${res.status}`, + }); + figure.innerHTML = `
${name}: recorded
`; + return; + } + const refBlob = await reference(name); + if (!refBlob) { + results.push({ + scene: scene.id, + view: view.name, + status: 'fail', + detail: 'no reference', + }); + figure.innerHTML = `
${name}: no reference
`; + return; + } + const [actual, expected] = await Promise.all([ + pixels(capture), + pixels(refBlob), + ]); + const diff = new Uint8ClampedArray(actual.data.length); + const outcome = compareImages(actual, expected, { diff }); + results.push({ + scene: scene.id, + view: view.name, + status: outcome.match ? 'pass' : 'fail', + diffFraction: outcome.diffFraction, + solidPixels: outcome.solidPixels, + mismatchedPixels: outcome.mismatchedPixels, + ...(outcome.reason ? { detail: outcome.reason } : {}), + }); + const diffUrl = outcome.reason + ? '' + : await toUrl(new ImageData(diff, actual.width, actual.height)); + figure.innerHTML = `
+
${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}
`; + }); + } catch (error) { + results.push({ + scene: scene.id, + status: 'fail', + detail: String(error?.message ?? error), + }); + } + } + if (record) { + // A partial recording keeps the other scenes' entries. + const kept = only + ? (await storedViews()).filter( + (view) => !only.some((id) => view.startsWith(`${id}-`)), + ) + : []; + const recorded = results + .filter((r) => r.status === 'recorded') + .map((r) => referenceName(r.scene, r.view)); + await fetch(SAVE + 'manifest.json', { + method: 'PUT', + body: + JSON.stringify( + { + renderer: which, + size: { + width: renderer.canvas.width, + height: renderer.canvas.height, + }, + views: [...kept, ...recorded], + }, + null, + 2, + ) + '\n', + }); + } + } finally { + renderer.destroy(); + status(''); + } + return results; +} + +$('logic').onclick = () => runLogic('stub'); +$('logicCesium').onclick = () => runLogic('cesium'); +$('check').onclick = () => runScenes(); +$('record').onclick = () => runScenes({ record: true }); +window.conformance = { runLogic, runScenes }; diff --git a/dev/stub-app/main.js b/dev/stub-app/main.js new file mode 100644 index 0000000000..ecd9e8607f --- /dev/null +++ b/dev/stub-app/main.js @@ -0,0 +1,60 @@ +/** + * The whole application on the stub renderer (`src/render/stub`), with only + * the contract's required members: the proof that the application runs on + * those members alone, and needs no code that knows which renderer it is. + * `scripts/qa-stub-boot.mjs` serves the application's page with this entry + * in place of `src/main.js`, boots it headless, runs its data layers and + * checks that no Cesium module loads. + * + * The stub runs nothing on its own: each animation frame here ticks it once. + * `window.__stubBoot` exposes the application and the renderer it made. + */ +import { createStandaloneApplication } from '../../src/standalone/application.js'; +import { createStubRendererPlugin } from '../../src/render/stub/index.js'; + +const renderers = []; + +/** Tick a renderer once per animation frame until it is destroyed. */ +function drive(renderer) { + const step = () => { + if (!renderers.includes(renderer)) return; + renderer.testing.tick(); + requestAnimationFrame(step); + }; + requestAnimationFrame(step); +} + +// The required tier, no capability at all; `?capabilities=all` gives the +// stub every capability, to see what the layers draw with them. +const allCapabilities = + new URLSearchParams(location.search).get('capabilities') === 'all'; + +const plugin = createStubRendererPlugin( + allCapabilities ? {} : { capabilities: [] }, + (renderer) => { + renderers.push(renderer); + const destroy = renderer.destroy.bind(renderer); + renderer.destroy = () => { + renderers.splice(renderers.indexOf(renderer), 1); + destroy(); + }; + drive(renderer); + }, +); + +const application = createStandaloneApplication({ + renderer: plugin, + allowQaRegistration: true, +}); + +window.__stubBoot = { + application, + renderers, + started: application.start().then( + () => ({ ok: true }), + (error) => { + console.error('Stub application failed to start:', error); + return { ok: false, error: String(error?.stack || error) }; + }, + ), +}; diff --git a/docs/APPLICATION.md b/docs/APPLICATION.md index 7c22064673..10673fd07f 100644 --- a/docs/APPLICATION.md +++ b/docs/APPLICATION.md @@ -43,7 +43,11 @@ await app.destroy(); ``` The example's containers and three remaining constructors are supplied by the -consumer. The viewer helper preserves the standalone viewer's render settings; +caller. The standalone scene also returns `trimStaleCommands()`, which drops +the draw commands the Cesium scene keeps after a turned-off layer stops drawing; +the application tools call it one frame after each layer disable. A scene +without it keeps those commands, and so the layer's memory, until they are +overwritten. The viewer helper preserves the standalone viewer's render settings; it neither selects map sources nor reads keys. Supply a visible credit container and retain all attribution required by the chosen sources. Cesium is external to this export: the consuming build must provide the same instance used elsewhere @@ -81,6 +85,119 @@ constructed component objects; the component instances themselves remain mutable `ready` means all constructors have returned. Background feed activity and the standalone share-restoration result keep their existing separate contracts. +## Pointer input + +`gods-eye-view/input` exports `inputFor(viewer)`, the scene's one input +dispatcher. Every layer and tool takes its pointer input from it, and so can +the caller: one pointer handler per viewer, and a click picked once and +handed to every subscriber. + +```js +import { inputFor } from 'gods-eye-view/input'; + +const input = inputFor(viewer); +const off = input.onClick((event) => { + if (event.ownerId === 'flights') showFlight(event.id); +}); +// Later: +off(); +``` + +`onClick` runs while no tool holds the pointer (the draw tool, the imagery +box), so a vertex placed on an aircraft is not also a click on it. Its event +reads lazily; a subscriber that reads nothing costs no pick: + +| Member | What it is | +| -------------------- | ------------------------------------------------------------------------- | +| `screenPosition` | Where the user clicked, in CSS pixels; for DOM and overlay hit-tests | +| `position` | Where that lands in the pick buffer (corrected under sensor styles) | +| `gesture` | `{ travelPx, durationMs }` of the press, to tell a click from a drag | +| `topHit` | The renderer's `Hit` on top at `position`, or `null` for the map itself | +| `drawHit` | `topHit` when it is an item of a draw set, else `null` | +| `hit` | `topHit`, or on a coarse pointer the contact under a surface pick | +| `id`, `ownerId` | The hit's pick id and the layer that registered it, or `null` | +| `meta` | The hit's own metadata, when it carries any | +| `surface` | Whether the hit is the map itself | +| `drill(limit)` | The draw-set `Hit`s under the click, shared by every subscriber | +| `windowHit(w, h)` | `{ id, drawHit, surface }` of a pick over a `w`×`h` window | +| `ground()` | The world position under the click, or `null` over the sky | +| `native` | The renderer adapter's own `{ pick, pickWindow(w, h), drill(limit) }` | +| `pick`, `pickWindow` | `native.pick` and `native.pickWindow`, for code bound to the engine picks | + +A hit is the renderer contract's `Hit` (`src/render/contract/query.d.ts`). +Something drawn outside the renderer's draw port is a `Hit` with `set: ''`, +named by the adapter. Positions are plain `{ x, y }` objects. The dispatcher +takes its pointer events from the renderer's input port and its picks from +its query port, so a viewer with no renderer bound needs the Cesium adapter's +factories loaded (`gods-eye-view/render/cesium/unbound`), or `inputFor` throws. + +`onPointer(type, fn, { lease })` subscribes to `down`, `move`, `up`, `click` +or `dblclick`; with a lease it runs only while that lease is current. A tool +takes its lease with `claimPointer(ownerId, { onLost })` from the same export +(and gives it back with `releasePointer(lease)`), which also keeps every +ambient subscriber off its clicks; `isPointerFree()` and `pointerOwner()` +report who holds it. The newest claim takes over, as on the renderer's input +port: the tool holding the pointer has its `onLost` called once and turns +itself off, and its late release frees nothing. `suspendCamera(reason)` and `suppressStockClicks()` return their +own release: camera input and the viewer's stock select and double-click-track +come back when the last hold is released, so two holders cannot undo each +other. The renderer's input port owns the camera controller's `enableInputs`: a direct +write (Cesium's camera flights make one when they start and end) is kept, but +reads true only while no hold is out. A caller-supplied `createScene` that creates its own viewer registers +`defer(() => inputFor(viewer).destroy())` right after it; the standalone scene +does this and returns the dispatcher as `scene.input`. + +## Height queries + +`gods-eye-view/queries/heights` exports `heightsOf(viewer)`, the one place +height queries go. Layers, tools and the camera ask it instead of asking the +renderer's query port (`sampleHeight`, `sampleHeightNow`, `clampToSurface`) +or the scene themselves, so how the renderer answers heights can change +without touching them. Pass the viewer the renderer is bound to, not its +scene. A viewer with no renderer bound is answered by the Cesium adapter's +fallback once the caller has loaded `gods-eye-view/render/cesium/unbound`; +until then, every query answers `null`. + +```js +import { heightsOf } from 'gods-eye-view/queries/heights'; + +const heights = heightsOf(viewer); +const ground = heights.now({ lon, lat }, { exclude: [ownSetId] }); +if (ground !== null) place(ground); +``` + +| Member | What it answers | +| ----------------------------- | ------------------------------------------------------------------------- | +| `now(point, opts)` | Height in metres from what is loaded, or `null` | +| `clampNow(position, opts)` | The ECEF `{ x, y, z }` moved onto the drawn surface, or `null` | +| `batch(points, opts)` | A promise of heights once the most detailed tiles stream; `null` per miss | +| `clampBatch(positions, opts)` | A promise of clamped `{ x, y, z }` copies; `null` per miss | +| `supported()` | `{ surface, clamp }`: whether the drawn surface can be queried at all | + +A point is `{ lon, lat }` in degrees or `{ longitude, latitude }` in radians. +`against: 'surface'` (the default) reads what is drawn, 3D tiles and globe; +`against: 'terrain'` reads the loaded terrain alone; `against: 'tiles'` the +tiles without the globe. Both `surface` and `tiles` include draw sets drawn +with `includeInHeightQueries`; `clampNow` and `clampBatch` always clamp to +the surface. `exclude` lists draw set ids to see through, of those drawn with +`includeInHeightQueries`; every other draw set is seen through already. Every +miss is `null`, and every caller treats it as one; `batch` and `clampBatch` +reject when the query itself fails. Without depth-texture support the Cesium +renderer answers no `surface` or `tiles` height; `now` still answers +`terrain` from the loaded tiles, while `batch` misses terrain too. + +## Cesium internals + +The app reaches private Cesium fields only through +`src/render/cesium/internals.js`, one named helper per field (the main and +offscreen pick views, a billboard's collection, a cluster's point collection, +the widget's render-loop latch, the WebGL context and whether a camera flight +is under way). `internals.test.mjs` fails when the installed Cesium stops +declaring one of them, and when a private field is reached anywhere else. +Imagery that rations its tile requests states the policy as a hook with +`withTileRequestHook(provider, { requestImage, credit })` from +`src/render/cesium/tileRequests.js`, which leaves the provider untouched. + ## Standalone wiring `src/main.js` reads the existing browser configuration and starts @@ -187,7 +304,28 @@ instances. Configure sources with `application/sources` before registration or state restoration, and release them after the consumers stop. The catalog constructor (`application/layers`) also requires `wind`, `weather` and `cyclones` sources with `getSnapshot` for the Weather layers, and owns the -observed-history clock those layers share for the catalog's lifetime. +observed-history clock those layers share for the catalog's lifetime. That +clock, the catalog's `weatherClock`, follows the world clock (`gods-eye-view/time`) +and has no time controls of its own: move time with the world clock's `seek`, +`play`, `pause` and `goLive` (`weatherClock.world` is the one it follows). + +A layer gives the world clock's timeline the time it can show with +`worldClock.register({ id, coverage })` (`gods-eye-view/time`), which returns +the unregister; call `worldClock.coverageChanged()` when that time changes. +`coverage()` returns null while the layer has none, or +`{ start, end, marks? }` in epoch ms. `marks` are the moments worth going to, +drawn as ticks the timeline's arrow keys step to and a tap on or within 6 px of +snaps to. Each mark is a number, or `{ time, label?, id?, kind? }`: `label` is +short text (cut to 60 characters, ending in `…`) shown when the pointer is on +the tick and told with the time while the handle is on the mark, `id` the layer's own key for the event and `kind` +what sort of event it is (`'launch'`, `'earthquake'`). The two forms may be +mixed; a mark without a finite time, and a `label`, `id` or `kind` that is not +a non-empty string, are ignored. `worldClock.coverage()` returns the union of +the registered layers, `{ start, end, marks, markDetails }`, or null: `marks` +is every mark's time once, in order, as numbers, and `markDetails` the marks in +time order, each a frozen `{ time, label?, id?, kind? }` holding only the +fields given, with marks given alike by several layers once and a bare time +left out where a mark with more to say shares it. A `weather` source may also supply decoded frames: an optional `getFrameImage({ product, time, size, bbox, signal })` returns a whole-extent or detail image and an optional `getFrameTile({ product, time, z, x, y, size, @@ -195,6 +333,12 @@ signal })` returns one tile or null for a transparent tile, each as an `ImageBitmap`, `ImageData`, canvas or `VideoFrame` of exactly the requested size, which the layer draws once and closes. Without them the layers read the image and tile routes (`WeatherFrameFeed` in `src/layers/weather/source.js`). +It may also name its source with an optional `sourceName(kind)`, `kind` being +`'radar'`, `'lightning'` or `'satellite'`: the layer's row shows that name until +a manifest names its own, and NOAA nowCOAST when the source names none. The +name is read once, when the layer is built, and held to the same rule as a +manifest's `display.source`. The map credit still comes from each manifest's +`display.credit`, so a source that is not nowCOAST sets that too. `application/services` accepts boundary, terrain, regional-context, weather and summary services; its weather service supplies cockpit local conditions, not the @@ -230,3 +374,125 @@ starts and switches the language with the `./i18n` entry (`startPageLocale`, `localePicker: false` to `createApplicationControls` instead of editing the markup. Node tests that import application modules register the component loader with `node --import=/build/register-vue`. + +### Cockpit subjects + +Core's Cockpit rides a tracked aircraft, the tracked satellite and the +selected AIS vessel. An application adds kinds of its own with +`services.cockpitSubjects` on `createApplicationControls`: a list of +providers, checked once when the controls are built +(`src/cockpitSubjectProviders.js`). A malformed provider, or one with a member +that throws when read (a getter), is left out with a warning and the rest are +kept. A provider's subject takes entry when it was selected after every +built-in subject present (a tracked aircraft or satellite, a selected vessel), +whose own fixed order is unchanged, and needs the provider's `layerId` on; the +provider then holds its subject, hands the camera a frame and the generic HUD +a view model on every update, and releases it on exit. Provider methods are +synchronous and are called on the provider, so a class instance's methods keep +their `this`; one that throws or returns a promise is treated as having +failed. What a method returns may carry getters: one that throws when read +makes a candidate none, a frame malformed (the view ends) and a HUD view keep +the last; a worded member (labels, entry face, look) that throws keeps its +last good words. + +```js +import { getLocale, onLocaleChange } from 'gods-eye-view/i18n'; +import { pointAtS } from 'gods-eye-view/layers/rail/paths'; + +const words = { + en: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT RIDE' }, + de: { + view: 'Fahrtansicht', + exit: 'Fahrtansicht verlassen', + exitText: 'VERLASSEN', + }, +}; + +/** Ride the Rail layer's selected train; `rail` is its layer instance. */ +const ride = { + kind: 'example-ride', + layerId: 'rail', + entryFace: { icon: 'train', label: 'RIDE' }, + // A function is read again when the page's language changes. + labels: () => words[getLocale()] ?? words.en, + candidate() { + const train = rail.getSelectedTrain(); + return ( + train && { + id: train.key, + name: train.label, + selectedAt: train.selectedAtMs, + } + ); + }, + // Only a train bound to its line can be ridden: read() needs its path. + isEntryAllowed: () => Boolean(rail.getSelectedTrain()?.path), + hold: (id) => rail.setCockpitSubject(id), + read(nowMs, ctx) { + const train = rail.getCockpitSubject(); + if (!train?.path) return null; // ends the view + const point = pointAtS(train.path.line, train.path.s); + return { + id: train.key, + latitude: point.lat, + longitude: point.lon, + heightM: train.position.railHeightM, // null stands it on the shared floor + name: train.label, + headingDeg: + train.path.direction < 0 ? point.bearingDeg + 180 : point.bearingDeg, + speedMps: train.motion.reportedSpeedMps ?? train.motion.derivedSpeedMps, + // The layer already moves the train smoothly: sit on it. + anchor: 'exact', + eye: { upM: 3.5 }, + }; + }, + hud: (frame) => ({ title: frame.name }), + release(id, { restore }) { + rail.setCockpitSubject(null); + if (restore) rail.focusTrain(id); + }, +}; + +createApplicationControls({ /* ... */ services: { cockpitSubjects: [ride] } }); +``` + +The `./i18n` entry gives `getLocale()` and `onLocaleChange()`: +Core translates only its own strings, so a provider words its labels, entry +face and HUD for the page's language (labels may be functions, as above; the +HUD is read again on a change). `gods-eye-view/layers/rail/paths` is the +Rail layer's pure path module (`createRailPath`, `pointAtS`, `projectOnPath`) +for a provider placing a train along its line. The frame, HUD view and +candidate fields are documented in `src/cockpitSubjectProviders.js`; the Rail +and Transit read APIs in `src/layers/rail/cockpitSubject.js` and +`src/layers/transit/cockpitSubject.js`. A snapshot read again while nothing in +it changed is the one read before, so `read` may take one on every update; a +train's `path.line` is a frozen copy of its line, for `pointAtS` and +`projectOnPath`. The `layers/rail/paths` export and the +Rail and Transit read APIs (`getSelectedTrain`, `getSelectedVehicle`, +`getCockpitSubject` and the snapshots they return, `path.line` among them) +are experimental and may change without notice. + +A candidate's `selectedAt` is a token that changes each time the user selects +the subject, even the same one again, so entry counts it as selected then; a +new `id` under the same token is the same selection (a train's selection +moving to another feed's copy of it). The Rail and Transit snapshots give one, +`selectedAtMs`: when the user last selected the train or vehicle by a click or +`focusTrain`/`focusVehicle`. It is null after a deselection and for one +selected only by a hold, since a hold is not the user's selection. + +A frame with `heightM: null` stands on the shared floor, or where it last +stood while that floor is cold. If no height has been known since entry, the +view waits, showing ACQUIRING SURFACE, for at most five seconds +(`COCKPIT_GROUND_WAIT_TIMEOUT_MS`), then ends and releases the subject. + +`hold(id)` returns `true` once it holds the subject, or `false` to refuse +entry; any other answer, `undefined` included, refuses entry too, with one +warning. A refused hold, and one that throws or returns a promise, is followed +by `release(id, { restore: false })`, again once a returned promise settles, +so `release` must be harmless for a subject it does not hold and when called +more than once. + +Leaving the view does not track again an aircraft that was tracked before +entry, as with the bridge and orbital views: when the user leaves by the exit +control, the map goes back to the ridden subject through +`release(id, { restore: true })`. diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index b30c3aba19..44d598cac2 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -33,12 +33,13 @@ export inventory. Use declared exports rather than reaching into internal files. | `src/layers//` | Source acquisition, records and Cesium resources with explicit controller/renderer owners | | `src/sources/` | Portable protocols and source contracts; request state belongs to each factory instance | | `src/services/` | Supplied application operations; scene construction owns caches and cancellation | +| `src/render/` | The renderer contract, the stub renderer, the conformance suite and Cesium renderer pieces | | `src/voice/` | Portable action schemas/session, common controls, action execution and separate protocol adapters | | `server/providers/` | Node route factories, process-scoped provider caches and shutdown cleanup | | `server/standalone/` | Environment, local settings writes and server composition | See [application construction](APPLICATION.md) and the -[infrastructure contract](INFRASTRUCTURE-LAYERS.md) for construction interfaces. +[infrastructure contract](INFRASTRUCTURE-LAYERS.md) for construction interfaces, and the [renderer contract](RENDERER-CONTRACT.md) for what a renderer provides. ## Import direction gates @@ -293,9 +294,9 @@ the user's later collapse choice, including body remounts. Mark the body `max-height` and puts the scroll offset back afterwards. Panel bodies only scroll on an open-card change, with one write, never on a refresh. -Compose `createRailCards({ container, document, onParams, onOpen })` and -`createRailTimeline({ container, document, onCommit, onPreview, onStep, -onLatest, onPlay })`. Cards reconcile `{ id, title, badge, open, compact, +Compose `createRailCards({ container, document, onParams, onOpen })`. Rails +have no time controls of their own; the world timeline moves time. Cards +reconcile `{ id, title, badge, open, compact, compactStatus, blocks }` in place. Their full-width native button headers expose `aria-expanded` and `aria-controls`; articles expose `data-open`. The feature adapter owns accordion state. Generic cards do not select data or enable layers. @@ -330,10 +331,9 @@ consumers. They expose `summary.settings`, `summary.actions` and optional subscriptions still refresh the cards. Cards own configuration and readings. Weather orders cyclones, wind, then a bordered Observed history group containing -the timeline and active radar, satellite and lightning cards. The group heading -and scope name its active products. The timeline stays visible whenever any -observed product is enabled; fewer than two ticks disables transport. Pass -`heading: false` to the timeline when the containing group owns the heading. +the frame time and active radar, satellite and lightning cards. The group +heading and scope name its active products. The frame time shows whenever any +observed product is enabled and has a frame; the world timeline moves time. Exactly one active card is open. Header clicks and newly enabled ids choose it (the last new entry wins a batch); refreshes and clock ticks retain it. First appearance uses cyclones with storms, otherwise the first card. Disabling the @@ -341,7 +341,7 @@ open layer falls back to the first remaining card. A WeakMap per document keeps explicit choices through body remounts without adding share state. Card opening, storm selection and layer enabling remain independent. -Optional card/badge/slider class names provide feature styling. Card titles use +Optional card/badge class names provide feature styling. Card titles use `.data-name` typography; meta/time/badges use `.data-toggle-meta` typography; setting/result labels use `.panel-title`; chips retain `.data-toggle-chip`. Reserve one status line, even without a legend. Use app tokens. Wind's footer @@ -471,6 +471,13 @@ release listeners; pending action feedback is limited to its current owner. rendering, HUD and share operations. `src/standalone/controls.js` provides the running application's instances. The shell imports no standalone bootstrap or concrete live layer implementation. +The shell reaches the renderer through its ports alone, and loads no +renderer: given a viewer with no renderer bound, load +`./render/cesium/unbound` once first, which also provides the celestial +ring's precise ICRF rotation (`src/sky/icrf.js`; until then the ring uses +the TEME approximation). Whether Cockpit's aircraft is an entity of the +viewer's own is the `viewerDrawsEntity` service's to say; the application +scene supplies it. Panel layout, position/drag, notices, recording and deferred UI work have separate owners with synchronous cleanup. Existing scene, share and HUD engines retain their entry points. `ui/styles` loads the ordered stylesheet entry; component @@ -508,6 +515,15 @@ perform no network requests and discover no additional modules. standard sources and their setup/fallback policy. The standalone facade wires these to the application's render governor. +`maps/imagery`, `maps/terrain` and `maps/3d` are the Cesium renderer's +(`src/render/cesium/`). `maps/controller` and `maps/defaults` are +Cesium-free: they make their scene changes and build their providers +through the map engine the renderer provides as it loads +(`src/maps/engine.js`). The application's renderer provides it; with a +viewer with no renderer bound, load `./render/cesium/unbound` once first, or pass the +engine as the controller's and `createDefaultMapSources`' `engine` option. +Without one, constructing a controller throws, naming that export. + A registry supplies `sources`, `defaultId`, `unknownId` and optional `recoveryId`. Each source has a user-facing `descriptor`, availability/reason, and either an `imagery({ signal })` factory or a supplied `tileset`/`createTileset({ signal })`. @@ -572,6 +588,13 @@ separate from standalone setup. Scene construction returns these operations; the catalog and controls use the same surface owner. Layers still own their individual ground-snap caches and model resources. +The entry is Cesium-free: ground snapping and mesh floor sampling ask the +renderer's globe (`isSettled`), camera (`pose`) and query (heights) ports, and +see through the caller's draw sets by id. A viewer with no renderer bound needs +the Cesium adapter's factories loaded (`gods-eye-view/render/cesium/unbound`) +first; until then the snap and the sampler answer nothing and location framing +throws, naming that export. + Terrain cancellation rejects late replies before caching, clears floor queues and removes the map-stack listener. Annotation lookup caches are instance-owned and cleared on cancellation. Geometry selection and floor policies are unchanged. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 6073b5c842..811e2a1fd6 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1,5 +1,31 @@ # God's Eye View Current State +An aircraft (civil or military) faces its reported ground track, else its +true heading (readsb `true_heading`). With neither, it faces the way its own +fixes went (`courseFromFixes`, `src/data/courseFromFixes.js`): the course runs +from an anchor fix to the newest once they are 30 m apart, and the anchor then +moves on, so frequent fixes of a slow aircraft add up while position noise on +a parked one never makes a course. A fix that is not a second newer (a repeat, +or an older position from another feed) and one reported slower than 2 m/s +give no course and keep the last; an aircraft with no course at all faces +north. + +While anything moves (a layer in motion, the camera, a followed contact), the +globe draws at the display's own refresh rate; there is no fixed 60 FPS cap. +The Cesium frame port (`src/render/cesium/ports.js`, its `idleFps`) caps a +parked scene at `IDLE_FRAME_RATE` (60, `src/renderGovernor.js`) ticks a +second while no hold is out, because Cesium still runs the clock, data sources +and update listeners on every animation frame even when it skips the draw; the +viewer starts at that cap until the frame port takes over. Through the idle +render governor, the camera port holds continuous render from `moveStart` to `moveEnd`, and samples its +pose every 250 ms in between, so a camera drifting by rounding errors (no +`moveEnd`) is released after half a second at rest and held again if it moves. The world clock holds continuous render while +it plays away from the live edge (not while it steps or waits for data), so +playback draws at the display's rate too. Waits that used to count frames (a followed contact's first +position, a shared follow view) count drawn time +through `src/time/frameWait.js`, at most 100 ms a frame, so they last the same +at any refresh rate and a background tab does not use them up. + Docker Compose mounts the checkout with the shared SELinux `:z` label so containers can read it on enforcing SELinux hosts. The separate image-owned `node_modules` volume and loopback-only port publishing remain unchanged. @@ -76,7 +102,7 @@ does nothing, wherever it starts. Rotation drags that start on the planet, and zoom, are unchanged. How much of the frame shows the planet's surface is measured by casting a 32×18 grid of view rays at the ellipsoid; while the scope mask is on (the default) only the rays inside its keyhole count, since the mask -hides or dims the rest. Voice tilt and in-place turns of a free 3D camera above +hides or dims the rest. Voice tilt and in-place turns of a free camera above 1,000 km stop when about a tenth of the frame still shows the surface (or about as much as it showed when it started), never less than about 1% of the visible frame, and a view that already shows less only keeps or gains what it has. A @@ -107,7 +133,7 @@ Views with more surface than that, such as the oblique orbital Director shots, are left as they are, and so are tracked or locked cameras, a camera flight in progress, a Director scene while it plays (holds included), a pointer held down on the globe (a drag held still; with several fingers down, until the -last is released) and the 2D and Columbus modes; a check a flight, scene or +last is released); a check a flight, scene or held pointer defers runs once it ends. A release outside the window that the page never sees counts as given once the window loses focus, the page is hidden, the canvas loses the pointer's capture, or the pointer moves with no @@ -118,6 +144,11 @@ it is until the next move. A voice turn requested while the camera is tracked is judged by the pose voice's release of the follow camera will leave, before that release, so a refused turn keeps the tracking. +The app draws only the 3D globe: the renderer it draws through has no 2D or +Columbus view. Voice tilt, in-place turns and the move-end recovery above are +written for that globe alone and carry no check for the other scene modes, +which in Cesium's 2D and Columbus views made them do nothing. + Analyst region queries resolve unique Natural Earth names offline without geocoding, so Gold Coast and Ivory Coast name the West African natural regions. Duplicate names require a geocoded containment anchor; when several entries for @@ -365,6 +396,26 @@ The source factories are exported at `layers/directions/source` and `layers/recent-imagery/source`. Configuration is applied at construction time; this does not introduce live source replacement. +Application catalog composition also accepts an optional `placement`, a +host-supplied placement provider (`src/data/placementProvider.js`): an object +whose `layer(kind)` returns, for `aircraft`, `military`, `vessels`, `transit` +or `rail`, either null or `{ place(id, wallMs), observe?(id, fix), +forget?(id) }`. While live, each of those layers tells it every fix it accepts +(time, position, the height it draws the fix at, reported speed, course and +ground state) and draws a contact where `place` puts it: position, height +(the layer's own when none is given), course and speed. A null answer, a +provider that throws, a kind it leaves out, or no provider at all keeps the +layer's own motion, unchanged; following the world clock, the layers never +ask it. Transit and rail vehicles a provider places are advanced every frame +in view while their placed position changes; one it holds still lets the +render loop idle and is asked again each second, moving on once its placement +does. A placed transit vehicle is drawn at its placed point, and a placed +train where it is placed rather than on its bound railway line. Live vessels +a provider places move on between refreshes: redrawn in place every frame, +with the next frame asked for as soon as the fastest drawn vessel will have +moved half a pixel on screen, at least once a second while the provider places +any drawn vessel, and none once the layer is off. + Application catalog composition accepts an optional `streetLevelProviders` list. An explicit list replaces the default Mapillary provider; an empty list removes all imagery providers. Without that option, Mapillary is registered only when @@ -627,6 +678,139 @@ panel that holds its row, and `set_panel_open` reaches it as `utilities-panel` or by "utilities", "draw", "drawing" or "import". On a phone it sits collapsed in the Layers sheet under Data Layers. +## The Visual panel — November 14, 2026 + +Visual (`#pp-toggles`, `src/ui/views/panels/DisplayPanel.vue`) is headed +VISUAL, has the edge switch in its header like the other side panels, and is +grouped from the top: Look, the six style presets with their 1–6 keys, and +Map source, the map source chips (`VisualPresets.vue`); Overlay, the HUD, +detection, style parameters, 3D aircraft, Scope and Clean UI; Effects, +Celestial, Bloom and Sharpen; and Reset to default at the foot. Each control +is a card (`src/ui/styles/visual-panel.css`) whose header row ends in an +on/off pill worded in the current language (Clean UI, an action, has none; +the buttons carry their state as `aria-pressed`). Under the Cyber HUD the +cards keep Cyber's own red skin. The presets and chips call the +same Display store actions as the dock's Visual Presets tray, which stays on +desktop and phone as before, along with Location; voice `Visual Presets` +still opens that tray. On a phone the More sheet shows that tray right above +Visual, so Visual leaves out its own presets and chips there. In Cockpit, +the groups that Cockpit's Display popover takes leave the panel as before and +keep their own styling there. + +Scope has an Opacity slider (`#scope-opacity-slider`, 50–100%, default 100%; +`SCOPE_OPACITY_MIN_PCT` in `src/ui/visualSettings.js`, since a fainter mask +reads as Scope off while labels still fade outside the keyhole) +that fades the whole mask (`setScopeMaskOpacity` in `src/scopeMask.js`, the +canvas's CSS opacity) without repainting it or changing the altitude +terminus; it is disabled while Scope is off and keeps its value. Share links +carry it as `sco` in the long form and field 30 in the compact form, written +only below 100%, so links made before it keep their codes and open at full +opacity, and a link without it sets the opacity back to 100%; a link asking +for less than 50% opens at 50%. Scenes do not +save it: a scene shot leaves the opacity as it is. + +Reset to default (`resetVisual` in `src/ui/displayBindings.js`) brings back +the out-of-the-box look: the Normal style, the first-run post defaults +(bloom off, sharpen on at 49%, the HUD shown, Dense detection at 75% +with its fade and outside opacity, the celestial ring off), Elastic +allocation, Scope on at 100% feather and 100% opacity, and 3D aircraft on in +Proximity. The HUD layout follows the Normal style, as choosing it does: the +Tactical HUD, except that the Cyber HUD stays Cyber. Inside Contacts, which +lends detection for the session, the reset's detection becomes what leaving +Contacts puts back and what a share link carries. It leaves the map source, the pinned scope terminus, Sonar's +settings, other styles' parameters, the layers and the panels alone. + +With Scope off the side rails, open panels and the dock's trays carry a soft +drop shadow and the rails' labels and icons a text shadow +(`src/ui/styles/scope-off-shadows.css`), so their edges hold against bright +imagery. + +## Side rails and the screen edge — November 14, 2026 + +Visual (`#pp-toggles`, the display settings, rail item `palette`) is the last +panel of the left column, after Data Layers, Utilities and Authoring, and +opens from the left rail like them (`PanelLayoutController`, falling back to +the right column in a host without a left stack). Context leads the right +column, followed by CCTV, Street Level and the other right panels. An open +Context or CCTV panel takes the column's full height; the other right panels +keep the content-sized layout and its hysteresis band. With nothing open, a +rail's icons and their names show as two glass pieces side by side; once a +panel opens, the icons stay in place and a highlight slides to the open one. + +Each collapsible panel header has an edge switch (`UiPanelEdge.vue`, +`src/ui/panelEdge.js`): it moves that side's panels over their rail to the +screen edge, with the rail as a row of icons above the open panel, and back. +The choice is per side, kept in `localStorage` (`gev.panelEdge`), and applies +on the desktop shell only: phones and Cockpit keep their own layouts and do +not show the switch. + +Scrolling the wheel at a screen edge (`src/ui/railEdgeScroll.js`, from the +edge to just past the rail, at most 84 px) steps that side's rail to its next +or previous panel instead of zooming the globe, wrapping round at either end. +One gesture is one step, trackpad coasting included, with at least half a +second between steps; a step that comes too soon is held until then and is +dropped if the pointer leaves the strip. Panels, controls, dialogs and the +world timeline in the strip keep their own wheel. The strip is off on phones +and touch screens, while the rails are hidden (clean view, recording), and it +follows the rails' sides in a right-to-left language. On a phone, Visual is in +the More sheet with the dock's Visual Presets, as before. + +## Wikidata cities pack — November 15, 2026 + +`src/data/local_data/wikidata_cities/cities.json` bundles 31,827 settlements of +15,000 people or more from Wikidata (CC0, 1.6 MB): name, position, population, +country and Wikidata id. `src/data/wikidataCities.js` reads it on the first +lookup and answers `nearestCity` (the largest city within 12 km, else the +nearest within 60 km), `citiesAround`, `findPlace` ("Paris, France", or the +nearest namesake within 150 km of the view, else the largest) and +`countryName`. Names match without case or accents ("lodz" finds Łódź). The +app never calls Wikidata; `scripts/build-wikidata-cities.mjs` rebuilds the +pack and fails if well-known cities are missing or a known grouping such as +the New York metropolitan area gets in. Nothing shows names from it yet; the +Context panel is its first reader. Sources and licence: `DATA_SOURCES.md`. + +## Data Layers finder and section index — November 15, 2026 + +The Data Layers header has a search button and a filter button +(`src/ui/views/panels/LayerFinder.vue`). Search opens a field under the +header that matches each layer's name on screen and its English name; Escape +closes it and leaves the panel open. The filter is a small popover with two +groups, Status (All layers, On, Off: whether the layer is enabled) and +Category (the list's groups, kept by their key, so a language change keeps +the choice). The arrows, Home and End move through it and Escape closes it. +Rows and groups that are left out hide; chips under the header show the +active filters and clear them, and "No layers match" says when nothing is +left. Neither the search nor the filter is saved or put in share links. A +voice request that points at a hidden layer clears the finder first +(`gev:layer-finder-clear`). + +A column of ticks down the list's inline end +(`src/ui/views/panels/LayerSectionIndex.vue`) has one tick per group still +shown; hovering or focusing a tick names its group beside it, on whichever +side has room, and clicking scrolls the list there. The tick for the group in +view is lit. Phones do not show it. + +## Cockpit side panels — November 14, 2026 + +On the desktop, the cockpit's side panels match the main page's +(`src/ui/styles/cockpit-panels.css`). The left rail shows Data Layers only: +Authoring, Utilities and Visual, with their panels, are hidden, since the +cockpit's own Display panel stands in for Visual. Display and Radio +(`CockpitUtilityControls.vue`) become a right rail of two icons with their +names beside them, and each opens one panel at a time beside the rail, with a +header and a "−" to close it. The rail's buttons are disclosures +(`aria-expanded`, `aria-controls`) and go through the `toggleCockpitUtility` +action (`src/ui/radioBindings.js`); closing a panel gives focus back to the +rail. Both rails start at the same height: the left one in CSS, and Display +and Radio through the cockpit layout pass, whose floor +(`COCKPIT_UTILITY_MIN_TOP_PX` / `_RATIO` in `src/ui/cockpitPresentation.js`) +matches it, so an open panel still stops short of the briefing. Contact and +Live Signals are shorter, in the same glass, with the briefing's rows and +weather tiles tightened; Regional News stays a briefing page. In a right-to-left language, the rail keeps its +physical side as the cockpit's other windows do. The Cyber HUD and the phone +keep their own cockpit layouts, with the Display and Radio launchers as +before, and edge mode does not apply in the cockpit. + ## God's Eye View in conversations — October 2, 2026 Tool answers that can be shown in God's Eye View include a view: camera, layers, @@ -719,6 +903,8 @@ Display's native Scope checkbox defaults ON with feather at 100%, adjustable from 0–200%. OFF disables the slider while retaining its value. HUD layout changes preserve both settings; share links and scenes restore them. The historical missing-`scf` fallback remains 35%; explicit 0% keeps the hard edge. +Its Opacity slider (0–100%, default 100%) fades the mask; share links +restore it (`sco`), scenes do not (see The Visual panel). With Scope OFF, Tactical and Minimal add text-sized black backplates at 70% opacity behind telemetry, vertical metadata and scene chrome. Original @@ -839,9 +1025,10 @@ resources and subscriptions. The globe relief helper is enabled with Wind and released when Wind is disabled. It uses terrain vertex normals for view-directed shading, falling back to global globe-curvature shading when normals are unavailable; the fallback does not show local hillshade. Neither mode -adds elevation data or represents sunlight. Relief declines to replace an -existing globe material, restores the prior empty material only while still -owning it, and leaves later owners intact. +adds elevation data or represents sunlight. Relief is the globe port's +`hillshade` surface shading: the renderer never replaces a globe material +someone else holds (it waits until that one is gone), gives the globe back +when Wind is disabled, and leaves later owners intact. Source acquisition retains deadlines, body budgets, disconnect cancellation, per-model/field singleflight caching and one-minute failure backoff. Application catalog construction owns each instance. @@ -865,7 +1052,9 @@ other map content draws over the shells, and shells are not pickable. A map-source change tears down one renderer and restages the shown observation on the other. A map without an imagery host pauses history while metadata refresh continues, then resumes when a host returns. -Globe tiled products use 256 px tiles to maximum level 6. The tile proxy accepts +Globe tiled products use 256 px tiles to maximum level 6, or to the level a +feed that supplies its own tiles names for the product (`frameMaximumLevel`, +0–12; any other answer keeps 6). The tile proxy accepts size=256 (default), 512 or 1024 and keys cached bytes by size, retaining the 24-hour immutable response and eight upstream slots. The image proxy serves every product as one whole-extent PNG at its advertised bounds, up to 4096×2048 for @@ -907,7 +1096,11 @@ open latest. Global infrared fetches one capped 4 MiB, 2048×1024 mosaic per frame and decodes and processes it before staging. Globe hosts crop that canvas into 256 px tiles to maximum level 3 on a geographic 2×1 root grid bounded to the manifest extent, -avoiding request-dependent contrast seams. +avoiding request-dependent contrast seams. On globe hosts, a feed that supplies +tiles and names a level for global infrared instead has it drawn from its tiles +to that level, +each tile given the same display transfer as regional infrared tiles, and no +mosaic is read. On globe hosts, regional infrared retains network tiles and processes each decoded tile once; shells process each whole frame once. Exact-time tile and image responses are immutable for 24 hours; manifests and @@ -1039,7 +1232,7 @@ Keyless terrain tiles retry when Re:Earth throttles them. The browser fetches `terrain.reearth.land/cesium-mesh/ellipsoid/{z}/{x}/{y}.terrain` directly; no proxy in this repository sees those requests (`/api/terrain/heights` is the separate point-height endpoint), and the upstream edge answers zoom-out bursts -with HTTP 429 under load. `src/maps/terrain.js` hands Cesium a `Resource` +with HTTP 429 under load. `src/render/cesium/mapTerrain.js` hands Cesium a `Resource` whose retry policy (`src/maps/terrainRetry.js`) every derived tile fetch inherits: 429, 502, 503 and 504 replies retry up to three times, 750 ms doubling to a 15 s cap, with every retry waiting behind one shared cooldown @@ -1414,7 +1607,9 @@ unchanged. Polled layer refreshes and the HUD's camera readout pause while the page is hidden. An app embedded inline in a panel keeps both running, because the panel's host can report the page as hidden while it is on screen. This is the -same rule the render loop follows (`keepPanelRendering` in `app/embed.js`). +same rule the render loop follows (`keepPanelRendering` in +`render/cesium/panelRendering.js`, which the Cesium plugin hands the +application and the application scene hands the embed views). Application scene setup owns request services, terrain/floor caches and annotation lookup state. Controls, layers and voice share those owners, and cancellation @@ -1574,15 +1769,19 @@ The view pass reruns while the camera moves, paced by its own cost. The camera picker lists the cameras in view, active camera first, and closes with the count of cameras outside the view. -Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames. +Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. Traffic and bikeshare expose factories through `./layers/traffic` and `./layers/bikeshare`. Traffic separates road requests, ingestion, animation, flow matching, styling, viewport lifecycle and development timing. Each source owns its decoded flow cache; cancelled bodies cannot refill it. Bikeshare separates its city registry, station source, parsing, rendering, selection and -proximity lifecycle. Existing standalone sources, live/simulated labels, road -budgets, station availability and polling behavior are retained. +proximity lifecycle; its station dots and selected-station highlight are two +renderer draw sets and it no longer reaches Cesium, so a caller handing it a +Cesium viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. Existing standalone sources, +live/simulated labels, road budgets, station availability and polling behavior +are retained. Installations and proximity context now expose `./layers/installations` and `./layers/awareness` factories. Each owns its records, selection, presentation, @@ -1601,7 +1800,17 @@ a fresh winning record. Dense removal clears only its own provenance, and a fresh core rebuild or lifecycle reset replaces the corresponding ownership. Source adapters retain the existing CelesTrak and Launch Library endpoints; standalone entries provide scene services and the satellite dependency. +The satellites layer draws through the renderer's draw port and no longer +reaches Cesium: the dots are one point set moved in a single write a frame, the +tracked satellite's dot a set of its own drawn where the follow camera framed +it, and the orbit rings a line set dimmed behind the globe and turned with the +Earth each second. A caller handing it a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. The mission factory separates paths, replay, camera, panel, overlays and placement. +Its markers, lines, live rings and pad zone are renderer draw sets, and it +follows a mission through the camera port, so a caller handing it a Cesium +viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. Launch Library pad coordinates retain unknown values: missing fields use the reported location coordinates when available, and launches without a known pad position stay off the map. Genuine zero coordinates remain valid. Undisclosed @@ -1622,12 +1831,40 @@ and scene services. Disable and teardown cancel pending refreshes; malformed snapshots preserve the last good display. Refresh restoration keeps selection identity without announcing a new user selection. Source/label, LOD thresholds, card limits, fire identities, altitude placement and analyst records are retained. +The layer draws its fire glows through the renderer's draw port and no longer +reaches Cesium; a caller handing it a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. Earthquake rendering is exposed through `./layers/earthquakes`. The layer owns -its entities and request lifecycle; the application supplies the overlay host -and snapshot source. The standalone adapter keeps the existing USGS daily feed, +its renderer draw set and request lifecycle and no longer reaches Cesium; the +application supplies the overlay host and snapshot source. A caller handing +it a Cesium viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. `depthColor` returns a renderer +colour `[r, g, b, a]` and `depthAccent` its CSS. The standalone adapter keeps the existing USGS daily feed, M2.5+ filtering, static discs, magnitude labels and analyst records. Disabling or -destroying the layer cancels pending work and ignores late results. +destroying the layer cancels pending work and ignores late results. While on, +the layer registers its quakes of magnitude 6 and up +(`EARTHQUAKE_MARK_MAGNITUDE`) with the world clock as timeline marks, spanning +only their own times, and none while off; the map still draws every M2.5+ +quake. Each mark is labelled with the magnitude as the map shows it and the +feed's place, cut to 40 characters (`earthquakeMarkLabel` in +`src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon +Islands`, or `M6.4` with no place). + +Air quality (`./layers/air-quality`) draws its station discs as one renderer +draw set of ground-clamped fills and reads the view through the camera port; it +no longer reaches Cesium, so a caller handing it a Cesium viewer, +with no renderer bound, loads the `./render/cesium/unbound` export once +first. + +Cockpit (`./ui/cockpit`) flies the camera through the camera port on the frame +port's `preUpdate`, with the shared geo maths, and no longer loads the Cesium +camera factory: a caller handing it a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first, or its +controller throws naming it. Whether the aircraft it flies still draws comes +from its `trackedEntityDrawn` service (the shell asks the entity's record, +and the application scene's `viewerDrawsEntity` for an entity of the viewer's +own); without one, Cockpit takes the aircraft as drawn. ## Rendered-mesh floor readings — November 9, 2026 @@ -1653,12 +1890,26 @@ directly under a deck or a roof overhang reads the structure above it, and a vehicle between readings takes the nearest one, so its floor steps where the nearest reading changes. +The sampler and the aircraft ground snap (`src/services/groundSnap.js`) reach +the renderer only through its ports: the camera's `pose()` for the probe +height gate, the globe's `isGlobeVisible()` (the sampler runs only with +the globe hidden) and `isSettled('surface')` (sampler) and +`isSettled('tiles')` with `isSettled('surface')` (snap) for whether the tiles +have streamed, and the query +port's heights, seeing through the caller's draw sets by id. Cockpit's ground +probe names the tracked contact's icon and model sets, which the flights and +military layers keep on its entity record (`groundSets`). + ## Vessel components and sources `src/data/aisLiveVessels.js` assembles `createVesselLayer` from the `./layers/vessels` package entry. The factory owns feed lifecycle, keyed records, rendering, selection, trails and cards in separate components. The standalone entry supplies its AISStream source, scene services and existing row limits. +Its ship icons are one renderer icon draw set (held motion, course rotation, +focus emphasis, horizon cull) and the entry no longer reaches Cesium, so a +caller handing it a Cesium viewer, with no renderer bound, +loads the `./render/cesium/unbound` export once first. Incomplete observations retain missing keyed vessels for at most five minutes since their last accepted receipt, within the renderer's row budget (plus the @@ -1706,7 +1957,7 @@ Applications supply the existing floor/snap, geoid, picking, sprite, camera, trail, focus, readout, context, aircraft presentation and render services. The factory never constructs a second application registry. Configure a source before initialization; replacing it while initialized is rejected. Model loads -use the supplied asset resolver, including the preload path. Enrichment receives +use the supplied asset resolver, including the up-front fleet set load. Enrichment receives an abort signal and cannot update a later lifecycle after destruction. Existing camera, terrain floor, trail, selection and measured model-size policies remain. @@ -1714,31 +1965,29 @@ A tracked civil or military aircraft's trail (`src/data/trailContinuity.js`) lif the pen, drawing nothing, between two points more than 48 minutes or over 1,500 kt apart (a parked aircraft within 0.1 nm keeps one line for up to three hours) and at a waypoint with no altitude; a ground waypoint is drawn on the ground. The head joins the -aircraft only within 150 km. Each trail keeps up to 2,000 points, a full day of history -at one fix per minute plus the live session; past that the oldest recorded points go -first, and the oldest reports only once none are left. The renderer +aircraft only within 150 km. Each trail keeps up to 2,000 reports, a full day of history +at one fix per minute plus the live session; past that the oldest go first. The renderer (`src/data/trailRenderer.js`) freezes every chunk of 128 points except the newest into static geometry, so a long trail costs about as much per frame as a short one; `scripts/qa-trail-freeze.mjs` checks that a freeze never shows a blank frame. -While an aircraft is tracked, its trail between reports is the path its icon was -drawn along: the displayed position is recorded about once a second or every 150 m -(`recordTrailPoint`). Recorded points are thinned by shape: one stays only where -dropping it would move the line more than 30 m across the track or in height from any -position it stood for, or leave a straight piece longer than 10 km, so straight flight -adds a vertex every 10 km at most and a turn keeps its curve. A recorded point that -would turn the line back sharper than 120° over a short step is dropped. Reports stay -in the trail as anchors, in time order. Recorded points never join two reports that are -not one flight under the 48-minute and 1,500 kt rules; the points between them go and -nothing is recorded across such a pair. A report for a time the display has already -passed replaces what was drawn after it, and nothing is recorded until the icon has -eased onto it, so the line reads arc, report, corrected path. History from before tracking started, and the backfill, run report to report. +A trail holds the aircraft's reports and nothing else, in time order: what the icon was +drawn at between them is never kept, so a late report cannot leave a kink. Between two +reports that are one flight and both carry a track, the icon is drawn along, and the +trail drawn through, one curve (`src/data/fixCurve.js`): a biarc, two constant-rate +turns sent to the renderer as contract `arc` segments, passing through both reports and +leaving each along its reported track, so the icon sits on its trail with no offset. +Pairs with no track, slower than 40 m/s, or with a track more than 75° off the line +between them are joined straight. The trail samples the curve at least every degree of +turn. History from before tracking started, and the backfill, run report to report the +same way. The trail never runs past the icon or through its 3D model, and the head runs from the newest kept point outside the model to the icon (to the model's tail when the model is -the visual). A contact with no new report coasts along its reported track for 5 minutes -past its last real report, at no more than 1,500 kt and never below known ground, then stops; +the visual). A contact with no new report coasts straight on along its reported track for 5 minutes +past its last real report (no turn: a turn rate measured over earlier reports outlives +the turn), at no more than 1,500 kt and never below known ground, then stops; one that went quiet on the ground, or within 150 m of a known ground floor, holds at its last -report, records nothing and draws no head (with the ground unknown, a low barometric +report and draws no head (with the ground unknown, a low barometric altitude alone does not hold it). The hold-or-coast choice is made once per report (`staleHoldsForFix` in `src/data/motionModel.js`), and the forward fix built when a repeated position carries new speed or course follows the same rules and is never a trail report. A live report @@ -1815,7 +2064,7 @@ layer's existing lifecycle and selection guards continue to reject late work. ### Following the world clock A source may declare a timeline: it can answer a snapshot at a given time. -`source.timeline` is `{ coverage(), stepMs, subscribe? }`, validated by +`source.timeline` is `{ coverage(), stepMs, spanMs?, subscribe? }`, validated by `readSnapshotTimeline` (`src/sources/live/contract.js`): `coverage()` returns the span `{ start, end }` in epoch ms it can answer, or null while it does not know yet; `stepMs` is the spacing of its snapshots; the optional @@ -1838,7 +2087,12 @@ Playing, the layer stays a snapshot ahead of the time, and play does not pass a snapshot still loading for more than 8 seconds. Those snapshots apply as polls do, so contacts move on smoothly: aircraft are drawn at the clock's time rather than behind it, and vessels between two fixes move along the great -circle, never past the newer one. Records, absences and the Layers panel's age +circle, never past the newer one. Drawn vessels move again once the fastest +of them would have moved half a pixel on screen at the speed it last moved, +at least once a second, and at once when the camera moves or changes height +by a tenth of its height or the view zooms, with frames asked for as for +placed live vessels; vessels out of view move on a share of them each frame, +each within 250 ms, and one that comes into view is moved to the time first. Records, absences and the Layers panel's age are judged at the clock's time. Outside the coverage the layer shows no contacts and loads nothing; while the coverage is unknown it loads nothing and clears nothing. A snapshot that fails clears the time and is asked again after @@ -1848,6 +2102,20 @@ the older is aborted before a newer starts. Moving the view while vessels follow area at the same time. Back at live the contacts are cleared and the layer polls at once. +A timeline may also declare `spanMs`: each record of a snapshot at a time then +carries `fixes`, `{ atMs, lat, lon, altitudeM? }` in time order, its own track +from `spanMs` before the time to `spanMs` after it +(`src/time/timelineFixes.js`). The layer places each contact on its fixes at +the clock's time, so a seek or a move back that stays within the fixes the +loaded snapshots carry is no jump: nothing is cleared, play does not wait, +and contacts move to the time smoothly. The snapshot at a step before the +newest loaded is asked for once and then stands in for every contact: it +brings back any that had left after it and drops those not there yet, while +those it has keep their place, as their fixes put them. Paused, a time nearing +the end of the fixes after the newest asks for the snapshot there. A contact is not drawn more than a minute before its first +fix, as it was not there yet. Each contact keeps at most 240 fixes, at least +20 seconds apart, and the loaded snapshot times span at most 20 minutes. + A snapshot at `atMs` describes the world as it stood then: `observedAtMs` is at or before `atMs`, no record is observed later than `atMs`, freshness and staleness are judged against `atMs`, `atMs` is echoed back, and a vessel @@ -2063,10 +2331,13 @@ hidden; tilted past the Earth's limb neither the sensor nor the swath reads. A swath is confirmed only on the operator's, an agency's (ESA's eoPortal included) or an academic page for its platform. From 16×, with flat imagery on the globe (not Google 3D tiles) and the view at -nadir, every 2 s the view asks the base imagery layer for the tiles it will -need 5 to 20 s ahead along the ground track (`prefetchImageryAhead` in -`src/ui/cockpitOrbitalView.js`), so the browser has them cached when the -view arrives. The level is the one Cesium will draw there +nadir, every 2 s the Cesium renderer asks the base imagery layer for the +tiles the view will need 5 to 20 s ahead along the ground track, so the +browser has them cached when the view arrives. The renderer works this from +its own camera (`preloadImageryAhead` in +`src/render/cesium/imageryLookAhead.js`): a vertical field of view as narrow +as an orbital view's at 16× for the camera's height, a look straight down, +and the camera's own motion over the ground, which gives the track. The level is the one Cesium will draw there (`imageryLevelForView` in `src/cockpitOrbital.js`, following Cesium's own choice: the terrain level whose error spans at most the globe's maximum screen-space error, then the imagery level whose texels are nearest that @@ -2076,7 +2347,7 @@ at the lowest priority, so a request is declined while the imagery server's slots are taken by the tiles on screen and is the first dropped when the scheduler is full (a declined or dropped tile is asked for again later, one that failed to load is not); it remembers the last 512 tiles asked for and does not ask for those again, starts over on another base map (cancelling the old map's -pending requests), and cancels the requests still pending on exit. Across the track it samples the centre line, a third +pending requests), and when the view widens (below 16× or on exit) cancels the requests still pending and forgets the tiles asked for. Across the track it samples the centre line, a third out and the frame's edges. While tilted off nadir the view looks away from the track, and with the world clock more than a minute from now (paused or played back) it will not pass where the look-ahead points, so nothing is @@ -2208,6 +2479,83 @@ the subject (tracking stopped, Satellites off) or tracking another target ends the view without refocusing. `src/ui/cockpitOrbitalView.test.mjs` covers entry, camera, zoom, look, HUD and exit. +### Application subjects + +An application can add its own first-person subjects beside the aircraft, +vessel and satellite: `services.cockpitSubjects` to `createApplicationControls`, +a list of subject providers (`src/cockpitSubjectProviders.js`, checked once by +the coordinator; a malformed one, or one with a member that throws when read, +is left out with a warning and the rest are kept). A provider names +its layer, an entry face and labels in the page's language, and supplies four +operations: `candidate()` (what entry would ride now), `hold(id)`, +`read(nowMs, ctx)` (a camera frame each update) and `hud(frame, ctx)` (a HUD +view model), with `release(id, {restore})` on exit. Entry needs the provider's +layer on, no Context change in flight and the provider's own +`isEntryAllowed(candidate)`; voice stays aircraft-only and is refused, with +the reason, while a provider's view is in use. + +The built-in kinds keep their fixed entry order (a tracked aircraft, then the +tracked satellite, then the selected vessel), so without providers entry is +unchanged. A provider's candidate takes entry only when it was selected after +every built-in subject present, by when the Cockpit first saw it or saw it +selected again (its `selectedAt` changing): a train picked after an aircraft +was tracked takes entry, and an aircraft tracked after it takes it back. +Providers' candidates are ordered most recently selected first, then by +priority; one first seen together with a built-in subject comes after it. The +first in that order decides alone: when its gate is shut there is no entry +rather than the next subject's. + +A frame places the eye `eye.upM` above `heightM` (the shared floor where the +frame gives none, or where it last stood while that floor is cold; with +neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for +at most `COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the +subject is released: no height stands in for a floor never read), slews toward `headingDeg` at the provider's rate, and may +turn off the floor clamps (`groundClamp: false`, for a subject inside a +structure) or keep the anchor exactly on the subject (`anchor: 'exact'`, for a +layer that already moves it smoothly; a frame with no `speedMps` is always +exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs: 0` updates the +camera every rendered frame. A frame that is null, malformed or for another +subject ends the view (`restoreTracking: false`), as an aircraft tracked +meanwhile and the provider's layer turning off do; the exit control asks the +provider to restore its subject. The generic HUD shows the provider's kicker, +title, meta line, speed with its unit and tag, readout cards, always-visible +source rows, banner, route card and Live Signals rows, a veil that darkens the +picture under the HUD (with passing light streaks, which stop under reduced +motion), arrow-key look-around when the provider asks for it, and a progress +line along the bottom edge (`src/cockpitProgress.js`: close ticks merge, +labels never overlap). Core translates none of the provider's text: a host +words it for the page's language (`gods-eye-view/i18n`: +`getLocale`, `onLocaleChange`). Its entry face, labels and look may be +functions, read again when they are shown and on a change of language, as the +HUD view is. + +The Rail layer offers a read API for such a view: `getSelectedTrain()` and +`getCockpitSubject()` (a snapshot of the train: where it is along its line, +which way it runs (`pathBinding.js` learns it), its rail height, speed as +reported or derived, position source, feed credit and stops, and +`selectedAtMs`, when the user last selected it by a click or `focusTrain`, +even again; null after a deselection and for a train only a hold selected), +`setCockpitSubject(key)` (its marker, 3D model and card hidden, the selection kept, its +feed held, clicks and Escape left to the view; the held copy stays the one +drawn of its train while held, another feed's copy hidden, and it keeps +moving, still selected, when its category is turned off) and +`focusTrain(key)` (false for a train the layer does not draw); its pure path +module is exported as `gods-eye-view/layers/rail/paths`. That export +and these read APIs are experimental and may change without notice. A snapshot read again while nothing in it changed is +the one read before, and its `path.line` is a frozen copy. Transit +offers the same for a vehicle (`getSelectedVehicle`, `getCockpitSubject`, +`setCockpitSubject`, `focusVehicle`): a held vehicle keeps playing when it is +out of the camera's view, and its sprite, 3D model, card, trail and detection +box are hidden; released, it is out of play until a visibility sweep finds it in +view. Its snapshot's `position.groundHeightM` is the floor where playback draws +it (the drawn marker's height while it is placed, else its segment's two +reports' floors at the playback fraction), not the newest report's, and null while that floor is unknown. Rail's `path.direction` is the +way the drawn train runs: once playback has placed it, a report that runs back +turns it only when playback reaches that report. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, +`src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, +`src/layers/rail/cockpitSubject.test.mjs` and the Transit lifecycle tests +cover them. + ## Context coordination Context controls own Contacts/Space Missions state, entry and exit transactions, @@ -2229,6 +2577,17 @@ shown without a fade once it is decoded (or after one second if its decode never settles), so a new camera's preview is blank only while its frame loads. Disposal releases listeners, subscriptions, image handlers, summary timers and chip-hide timers. +The panel opens when a camera becomes active and collapses when the layer is +switched off, from its own switch or anywhere else. The panel chrome applies +the collapse, so a panel the desktop accordion only folded has its saved and +shared state closed too. Clear selected data layers and Context isolation +(Contacts, Space Missions) switch the layer off without the user asking: the +panel and its share preference stay as they are, and the layer comes back to an +open panel. Only the switch-off isolation makes counts (`suspendsLayer`, true +while `_clearLayersOutsideContextMode` switches the layer off): the user +switching CCTV off inside Contacts closes the panel as anywhere else. A panel opened by hand while the layer is off stays open, and its +meta line reads the catalog count, not the last active camera. + ## UI disposal UI disposal releases the CCTV subscription, command-dock observer, legacy drag @@ -2244,6 +2603,14 @@ owners. Tuner calculations have a pure entry, with existing layer exports preserved. Destruction removes listeners and state subscriptions before ending tuning; a delayed Enable result cannot reveal or refocus removed controls. +The stations, their clusters and the selected marker draw through the +renderer's draw port, and the layer no longer reaches Cesium. Stations drawn +too close together on screen stand behind one cluster dot, grouped as the +default renderer's entity clustering grouped them (`geo/screenCluster.js`, +42 px, three or more), reclustered as the camera moves and when the filter +changes. A caller handing the layer a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. + ## Giroc / Webcam Romania CCTV source pack `config/cctv_sources.romania.json` is an optional single-camera pack for Giroc, @@ -2392,7 +2759,7 @@ and a Denver coordinate underground. Search now resolves the application's ground-floor elevation (bounded wait, same ellipsoidal datum) before framing and warms the cell; after landing, `src/cameraGroundGuard.js` samples the rendered surface under the target and the camera once tiles stream in and lifts the eye -to 120 m clearance, holding heading and pitch. Navigation ownership changes (Director, tracking, keyboard/UI controls and direct camera flights), layer/app teardown, and pointer/wheel gestures cancel the check and remove its listeners. `scripts/qa-context-arrivals.mjs` types Camp Mabry +to 120 m clearance, holding heading and pitch. Navigation ownership changes (Director, tracking, keyboard/UI controls), any other caller moving the camera or starting a flight before a retry, layer/app teardown, and pointer/wheel gestures cancel the check and remove its listeners; the guard compares the pose it started on rather than wrapping camera methods. `scripts/qa-context-arrivals.mjs` types Camp Mabry and a Denver coordinate and requires at least 60 m clearance. ## Layer panel ownership @@ -2407,10 +2774,11 @@ provides its confirmed toggle, taxa presets and fixed-order, nonempty legend. ## Sky background -`src/sky/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale +`src/render/cesium/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale Bright Star Catalogue stars and a soft ESO/S. Brunier Milky Way. Both layers rotate from ICRF/J2000 into the Earth-fixed frame at the scene clock, with -a TEME fallback while Cesium's IAU 2006 tables load. Bundled assets and +a TEME fallback while Cesium's IAU 2006 tables load. The precise rotation reaches +Cesium-free code (the celestial ring) through `src/sky/icrf.js`. Bundled assets and their provenance are documented in `src/data/local_data/sky/README.md`. Anime fades out the Milky Way with its style intensity to avoid cel-shaded @@ -2420,8 +2788,9 @@ is validated against Cesium 1.138.0 and must be revalidated on upgrades. `scripts/qa-anime-sky.mjs` checks asset readiness, visible Normal sky and Anime band coverage against a Vite dev server. -`scripts/qa-sky-model-lighting.mjs` compares a lit `airplane.glb` against -black and white environment maps in isolated scenes. +`scripts/qa-sky-model-lighting.mjs` compares a lit fleet airliner +(`public/models/fleet/aircraft/a320.glb`) against black and white environment +maps in isolated scenes. ## Model atmosphere on Apple Metal @@ -2442,6 +2811,53 @@ future driver fix restores the effect with no code change; iOS/iPadOS platform detection is the backstop for when no probe context can be created. Applied during viewer construction, before any tile builds a draw command. +## Render failure notice + +When the globe stops drawing, the scene chrome says so instead of leaving a +black globe behind working controls. `installRenderFailureNotice()` +(`src/render/cesium/renderFailure.js`) listens for Cesium's `renderError` and the canvas' +`webglcontextlost`, logs the error, and publishes a notice that +`RenderFailure.vue` shows as an alert dialog with focus on its first action. +The app's viewer uses `showRenderLoopErrors: false`, so Cesium's dead-end +"Rendering has stopped" panel no longer appears; `applicationViewerOptions()` +keeps it by default for other callers. + +- **Retry** restarts the render loop. The notice stays until a frame starts + and ends without an error: Cesium raises `postRender` after a failed frame + too. +- **Reload**, after a lost context, reloads the page; the address keeps the + view. +- **Reset view** opens `appRootUrl()`, without the hash or `/share/` + path; the query, such as `?lang=`, is kept. + +Pitfalls: + +- An error thrown outside Scene's error handling (a frame listener, `onTick`, + a resize) stops the loop without a `renderError`. The notice wraps the + widget's `render()` and `resize()` and raises it as one, once even with + `rethrowRenderErrors`. +- A throwing listener leaves its Cesium event mid-raise, with listener changes + only queued. The wrapper finishes those raises first (`finishRaise()` over + `frameEvents()`), so a layer turned off or on meanwhile behaves. +- A render error marks the loop stopped while its next frame is still queued. + The wrapper keeps the loop marked running, so a Retry or a shown tab + (`src/app/tools.js`) before that frame starts no second loop. +- After a lost context, later render errors are only logged, so the notice + keeps saying why. The listener neither prevents nor restores the loss. +- When the globe draws again, focus goes back where it was, or to the globe's + canvas, which the map's keys read as the map; the canvas is focusable only + until focus leaves or the globe is pressed. Focus the user moved stays put. +- The notice sits above floating panels such as the Québec camera viewer, and + its buttons are 44 px tall on touch screens. + +An inline conversation panel never reloads or navigates its host's page: it +offers Retry after a render error only, and no notice after a lost context, +where the panel runtime's own notice applies (`src/app/globePanelRuntime.js`). +Its timer (`keepPanelRendering()`) draws only while the render loop is on and +logs nothing itself, so each render error is logged once, by the notice. An +error a timer frame throws is caught there: it has already been raised as a +render error. + ## Map Source control ownership Map Source controls own chip listeners, source-state subscriptions and selection @@ -2453,11 +2869,14 @@ remain unchanged. ## Visual effects ownership -VisualEffects owns style-stage creation, crossfades, animation scheduling, bloom -and sharpen. Display supplies actions and renders settings; effect execution has -no DOM dependency. Existing presets and the 500 ms transition remain unchanged. -Stopping the controller revokes animation before asynchronous UI teardown; final -destruction removes its stages and restores the borrowed bloom configuration. +VisualEffects keeps the records of the styles, their crossfades, bloom and +sharpen, and drives them through the renderer's effects port: it defines each +preset there as a style, and the renderer runs the passes and animates the +animated ones. Display supplies actions and renders settings; effect execution +has no DOM dependency. Existing presets and the 500 ms transition remain +unchanged. Stopping the controller revokes animation before asynchronous UI +teardown; final destruction removes its styles and turns bloom and sharpen off, +and the renderer restores the scene's bloom configuration when it goes. Snow is no longer a visual preset. A share link that names it, in either the long or compact form, opens on Normal and drops the Snow shader parameters. A view passed to embed mode or `show_in_gods_eye_view`, and a saved scene shot, @@ -3289,7 +3708,8 @@ reads `NASA FIRMS · LIVE · updated …`. A source may instead answer the 24 ho to a set time, naming its end as `at` (epoch ms): the row then reads `NASA FIRMS · 24 h to MM-DD HH:MM UTC`, `getStats()` reports `at`, and `get_active_fires` says "in the 24 hours to" that time and reports it as -`window_end`. The dev proxy never sets `at`. +`window_end`, and card and detail ages count back from that time instead of +now. The dev proxy never sets `at`. The FIRMS CSV parser rejects impossible acquisition calendar dates before the proxy filters records to the trailing 24 hours, while retaining valid UTC acquisition times. FIRMS ages round to whole hours before choosing a unit, so a 47.6-hour age reads "2d", not "48h"; with detections filtered to 24 hours, this shows mostly in the `STALE · cached {age}` stats line. @@ -3332,9 +3752,14 @@ which embeds the MAP_KEY. windows reuse the active load. Disabling or returning Contacts to passive mode clears its anchor; passive refreshes cannot reclaim it. Background repaints refresh context records without publishing a new selection. - Installation tiles decode only the `landuse` layer. Reloads keep the Cesium - entities of sites whose geometry is unchanged, so outlines and fills do not - blink. While Contacts has a subject, the layer loads a window around it + Installation tiles decode only the `landuse` layer. The site dots, the + selected site's dot (a set of its own, so selecting one redraws no other), + their ground outlines and the selected site's fill are renderer draw sets; + reloads keep the drawn items of sites whose geometry is unchanged, so + outlines and fills do not blink. The layer no longer reaches + Cesium; a caller handing it a Cesium viewer, with no + renderer bound, loads the `./render/cesium/unbound` export once first. + While Contacts has a subject, the layer loads a window around it instead of the camera view (100 km half-width at mid latitudes, shrinking so it fits 16 z9 tiles), moves it only after the subject travels 20 km, and ignores camera `moveEnd`; clearing the subject returns to the viewport. The @@ -3491,9 +3916,12 @@ which embeds the MAP_KEY. > so a turned-off layer's entities stayed reachable (Data Centers kept 116 > MiB). `src/sceneCommandRelease.js`, installed in `src/app/tools.js`, > requests one frame through `governorRequestRender` after every layer -> disable and then trims those arrays. It reads private Cesium fields; -> `src/sceneCommandRelease.test.mjs` pins them and fails if Cesium renames -> them or changes which passes it truncates. +> disable and then has `src/render/cesium/sceneCommandRelease.js` (handed +> handed over by the Cesium plugin through `src/app/scene.js`) trim those +> arrays. It reads private Cesium +> fields through `src/render/cesium/internals.js`; +> `src/render/cesium/sceneCommandRelease.test.mjs` pins them and fails if +> Cesium renames them or changes which passes it truncates. > **2026-08-08 — performance waves 1+2:** the app idles via an explicit render > governor (`src/renderGovernor.js` — hold/release from every per-frame @@ -3606,20 +4034,22 @@ This is the current runtime/source-of-truth snapshot for the project. > 24.09 m aft (70 % of the model's rendered envelope, so inside it), 2.22 m > below centre (6 %), and 2e-9 m off the centreline. > - **The tracked trail attaches to REAL HULL, aft and below (2026-08-23):** -> `MODEL_TRAIL_ANCHOR_NATIVE` (`src/data/modelVisualAnchor.js`) holds, per GLB -> and in RAW glTF coordinates (see the transform-chain entry below), the point -> of the hull's CENTRELINE PROFILE (its y = 0 slice) closest to the aft-belly -> AABB corner. It is NOT the corner: a bounding-box corner is empty -> space, 4.80 m off the nearest triangle on `airplane.glb` and 6.14 m on -> `jet.glb`, so the trail ended in mid air beside the aircraft. The head segment +> `FLEET_TRAIL_ANCHORS` (`src/data/fleetTrailAnchors.js`, generated by +> `scripts/measure-fleet-trail-anchors.mjs`) holds, per fleet aircraft and +> helicopter model and in RAW glTF coordinates (see the transform-chain entry +> below), the point of the hull's CENTRELINE PROFILE (its centreline slice) +> closest to the aft-belly AABB corner. It is NOT the corner: a bounding-box +> corner is empty space (4.80 m off the nearest triangle on the airliner +> asset this was first measured on, 6.14 m on the jet), so the trail ended in +> mid air beside the aircraft. The head segment > is drawn from a point behind the aircraft to this anchor, so the anchor must > stay aft (83–96 % of each aft extreme) or the segment enters at the tail and -> stops inside the fuselage. `modelScale.test.mjs` reads the POSITION BUFFERS — +> stops inside the fuselage. `fleetModels.test.mjs` reads the POSITION BUFFERS — > real vertices and triangles, because accessor min/max cannot tell a corner > from a surface — and re-derives on-hull, aft, lowest-at-its-station, > on-centreline, and the construction itself. Re-measure, never re-guess. > - **The trail anchor rides CESIUM'S transform chain, not a hand-rolled one -> (2026-08-23 regression fix):** `MODEL_TRAIL_ANCHOR_NATIVE` stores RAW +> (2026-08-23 regression fix):** `FLEET_TRAIL_ANCHORS` stores RAW > glTF coordinates and `modelAnchorWorld()` assembles > `modelMatrix × components.transform × axisCorrection` — the same chain > `ModelSceneGraph` renders with, built from Cesium's own exported @@ -3654,7 +4084,7 @@ This is the current runtime/source-of-truth snapshot for the project. > ENVELOPE, and between them the drawn start slides along the segment so the > visible length grows CONTINUOUSLY from zero. Three earlier cuts are recorded > because their shape matters: testing segment LENGTH against the radius HID -> real trail (58 m aft of `airplane.glb`'s 34.41 m envelope gives a 33.98 m +> real trail (58 m aft of an airliner's 34.41 m envelope gives a 33.98 m > segment, suppressed, though ~23.6 m of it is open air); CLIPPING at the > envelope and keeping only what lay outside stopped a moving trail visibly > SHORT of the aircraft, since a bounding sphere encloses a lot of empty space @@ -3899,7 +4329,7 @@ isCurrent })` gates BOTH halves of the map-stack switch, which is its only > tunnels. Every other layer > is untouched: aircraft, vessels and satellites draw their markers over the > scene on purpose and keep their labels over it. The test runs on the GPU -> (`src/data/sceneOcclusionProbe.js`): one occlusion query per contact, +> (`src/render/cesium/sceneOcclusionProbe.js`): one occlusion query per contact, > repeated every 100 to 200 ms, answered a frame or two later, with nothing > read back from the GPU and so no stall. A contact hides as soon as a > "hidden" answer arrives and returns 600 ms after its last one, which keeps @@ -4336,18 +4766,22 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > it, and narrow screens retain Cesium's surface with an internal > scroller. The title, close control, links, and persistent Google/Cesium line > remain unchanged and visible. -> - **Distant-aircraft recession:** both civilian and military billboard fleets +> - **Distant-aircraft recession:** both civilian and military icon sets > retain their locked class/ground scale and `NearFarScalar`, then multiply a -> limb-relative taper in the existing ~12 Hz tick. The taper is 1 below 0.5× +> limb-relative taper. The sets say so themselves (`SetSpec.recede`, with +> the tuning as its parameters, sent again when the tuning changes), and the +> renderer works the taper out each frame from `render/recession`. The +> taper is 1 below 0.5× > geometric limb distance and smoothsteps to 0.45 scale plus a 0.35 alpha-haze > factor at the limb. That treatment eases continuously back to identity from > 3,500–4,500 km camera height, avoiding a globe-view threshold pop. These > values, the start ratio, blend band, composed floor, and write epsilon remain > runtime tunings. No aircraft is count-culled or made fully transparent. -> Focus emphasis and limb haze multiply at one deadband-gated write site, and -> their product is clamped to 0.20 before freshness alpha is applied. Ambient -> fleet models receive that same composed alpha; class/ground/cockpit repaints -> preserve the current limb scale instead of dropping it for a tick. +> Focus emphasis and limb haze multiply, and their product is clamped to +> 0.20 before freshness alpha is applied. Ambient fleet models receive that +> same composed alpha, worked out on each fleet tick from the camera then +> and written again once it moves by more than 0.005; their set itself does +> not recede. Under the IR boost they draw at full alpha. > - **Focus-aware contact de-emphasis:** civilian/military aircraft and > satellites publish the selected target's padded screen bounds and camera > distance from the same per-frame position cache already consumed by their @@ -4434,10 +4868,13 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > untracking, so a stationary slow press on a plane still selects it. Escape > still releases tracking in place. The 200 px feel needs close-range field > verification; fleet model sizing remains unchanged. -> - **Deterministic sprite stacking:** contact collections reassert the stable -> bottom-to-top order CCTV, FIRMS, bikeshare, AIS, military, then civilian -> flights after every relevant layer init/enable and immediately after FIRMS -> lazily registers its detection sprites. Always-visible contact +> - **Deterministic sprite stacking:** contact sets are made at draw orders +> (`SetSpec.drawOrder`, from `spriteDrawOrder`) that stack them bottom to +> top as CCTV, FIRMS, bikeshare, transit, directions, AIS, military, then +> civilian flights on top, whichever layer was turned on first; picks +> name the topmost first. The orders are negative, so every overlay at the +> default order (selection highlights, route endpoints, the tracked plane) +> still draws over all of them. Always-visible contact > depth settings are unchanged. Cesium OIT weighted blending may soften strict > alpha layering on some GPUs, so the ordering remains a real-browser check. > - **Deterministic card stacking:** CCTV, FIRMS, vessel, and tracked-target @@ -4594,8 +5031,14 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > celestial ring, annotations SVG, missions frame tick, and traffic). > - **World-label accounting:** All intended label/card migrations use the > shared host. The former native `LabelGraphics` exception for cable reference -> labels was retired on 2026-08-18; cable text may render over tile geometry, -> so **zero native world-label creation sites remain**. The mission replay DOM vehicle, awareness +> labels was retired on 2026-08-18; cable text may render over tile geometry. +> The Directions A/B letters (`directions-markers` source) and data-pack media +> labels (a pooled `data-pack-labels:` source per pack resource, through +> the pack handle's `label`) moved to the host on 2026-11-04, and +> `src/noCesiumLabels.test.mjs` no longer keeps an allow-list, so **zero +> native world-label creation sites remain**. A media pack shown without an +> `overlayHost` fails to load rather than drawing a native label. The mission +> replay DOM vehicle, awareness > compass, annotation SVG callouts, and host-owned detection isolation target > are explicit exceptions; the awareness ring and cockpit contact pips are > non-text out-of-scope surfaces. Annotation callout text, geometry, leaders, @@ -4640,10 +5083,10 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > Cesium entity carries no label graphic. > - **Phase 5 ISS and tracked-satellite labels:** The ISS path and large red > point remain native, while persistent `ISS` text is a one-entry moving -> ambient-label host source. Its getter reads the already-propagated point -> cache, preserving the 1 Hz fleet epoch and eliminating the former second ISS +> ambient-label host source. Its getter reads the point's own position, which +> moves every frame, eliminating the former second ISS > propagation. Satellite tracking continues to publish exactly one protected -> tracked-lane card through `gevLabelModel` and `_trackedDisplayCached`; the +> tracked-lane card through its entity record's `labelModel` and `_trackedDisplayCached`; the > tracked entity is point-only. Tracking ISS suppresses the ambient entry and > untracking restores it, preventing duplicate ISS text. Disable, orbit-text > preference changes, catalog rebuild, and destroy clear/hide the source. @@ -4658,7 +5101,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > - **Phase 5 tracked civil aircraft label:** A tracked flight's Cesium entity > is a billboard-only camera target with no native label. The flight source > retains callsign/registration fallback, flight-level/altitude, speed, stale -> state, airline/type, and plausible-route formatting in `gevLabelModel`; the +> state, airline/type, and plausible-route formatting in the entity record's `labelModel`; the > one protected tracked-lane host card renders that complete model. Its > position getter reads only `_trackedDisplayCached`, the same authoritative > Cartesian already consumed by the tracked visual and camera, and never @@ -4768,8 +5211,11 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > - **Tracked-readout ownership:** `trackedReadout.js` is now a presentation-model > bridge only; it owns no canvas, projection, post-render listener, layout, > keyhole fade, or paint path. Civilian flights, military flights, satellites, -> and mapped installations write explicit `gevLabelModel` objects and expose -> `gevDisplayPosition` getters backed by their layer-owned frame/display cache. +> and mapped installations write explicit `labelModel` objects and +> `displayPosition` getters, backed by their layer-owned frame/display cache, +> into the app's entity records (`src/data/entityRecords.js`), never onto the +> Cesium entity. A layer's private per-entity state goes in its own store from +> `createEntityStore()` (ALPR markers: `src/layers/alpr/markerState.js`). > Selected AIS vessels continue using the vessel source's protected selected > card, so they do not create a duplicate tracked readout. The host registers > the active readout in the protected tracked lane with a zero ambient quota; @@ -4830,8 +5276,9 @@ activeCameraCardEnabled: true })` may publish it through the retained > - **Flights 3D/cockpit hardening:** the destination-direction cue is an > inline SVG rather than a remotely loaded Material Icons ligature, so a > blocked or late font can no longer expand the literal word `navigation` -> across the cockpit. The grounded `airplane.glb` belly offset is calibrated -> to the current asset's measured Y-up bounds (`0.063` native units). +> across the cockpit. A grounded aircraft stands its fleet model's scaled +> clearance (the catalog's `clearance`, measured below the model's origin) +> above the ground. > Contact Previous/Next and Live Signals aircraft handoffs now > re-seed the first-person camera anchor at the selected flight immediately; > bounded feed-correction smoothing remains scoped to the same aircraft. @@ -5164,7 +5611,7 @@ its criteria cannot be silently ignored. | FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×2 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | | Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) | | Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | -| GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) | +| GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per H3 res-4 hexagon (GEV NIC/NACp threshold + gpsjam.org grid, formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) | | S2 GhostMaps 👻 (`s2-ghostmaps`) | S2 Underground's public GhostMaps repository on GitHub (KMZ intel products, keyless, CC BY-NC-SA 4.0) | `src/layers/ghostMaps/` via `src/app/layers/ghostMaps.js` | `/api/ghostmaps/catalog`, `/api/ghostmaps/events` (server-sent events), `/api/ghostmaps/file/{product}` | branch head checked every 15 s; new commits pushed to the page; 5 min catalog backstop | | Sea Marks ⚓ (`sea-marks`) | OpenSeaMap seamark raster tiles (keyless; CC BY-SA 2.0 tiles, OSM data ODbL) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | | Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | @@ -5178,8 +5625,13 @@ GNSS Integrity samples a 250 nm circle around the Earth point under the screen centre. Camera reads debounce for 600 ms with a monotonic 2.5 s minimum gap; nearby views share whole-degree cache keys, and a minute poll refreshes data. Counts and bands cover visited views over 30 minutes, including regions now off -screen. Non-pickable ground primitives preserve Street Level and perimeter -selection. The legend describes a low-accuracy score, not the raw aircraft share; +screen. Cells are H3 resolution-4 hexagons, gpsjam.org's grid, keyed by their H3 +index (`gnssCellKey`) and drawn from `cellToBoundary` (via `h3-js`) as clamped +polygons in one shapes set of the draw port, redrawn only when a cell or band changes; a cell across the +antimeridian is drawn with its longitudes unwrapped around its centre. As on +gpsjam.org there is no minimum aircraft count: every cell with an aircraft is +shown, and the one-aircraft discount is the only small-sample guard. +Non-pickable ground primitives preserve Street Level and perimeter selection. The legend describes a low-accuracy score, not the raw aircraft share; `getStats().levels` exposes nominal, medium and high counts separately. Transient source failures keep activation enabled and show unavailable/degraded @@ -5665,13 +6117,14 @@ the same navigation authority as every other camera destination. given; re-arming for the other endpoint reuses that lease rather than asking for a second claim, and every release names the lease, so a superseded instance can never free the claim its replacement holds. The claim is held until -the click that uses it has finished being dispatched — every layer binds its -own handler to the same canvas and they all run inside one browser event, so a -claim dropped the instant the endpoint is placed would hand the rest of that -same click to the ambient handlers bound after this one. It is returned on the -next tick after placement, and immediately on cancel, Escape, CLEAR, disable -and destroy; if another tool already holds it nothing is armed and the row says -so. Maneuver-dot selection is an ordinary ambient handler and yields while any +the click that uses it has finished being dispatched: the input dispatcher +checks the claim once per click, before any subscriber runs, but DOM canvas +listeners (the evidence cards) still see the same browser event afterwards, so +a claim dropped the instant the endpoint is placed would hand them that click. +It is returned on the next tick after placement, and immediately on cancel, Escape, CLEAR, disable +and destroy. The newest claim takes over: arming takes the pointer from a tool +holding it, which is told and turns itself off, and a newer tool taking it +disarms the layer as Escape would. Maneuver-dot selection is an ordinary ambient handler and yields while any tool holds the pointer. FLY runs through the UI shell's immediate-navigation facade — the same camera authority validated voice destinations use — and is handed the shared ground-floor read and corridor warm, so the dolly does not @@ -5729,7 +6182,26 @@ Helsinki, the Netherlands, Norway, South East Queensland, Rio de Janeiro Ontario — Toronto (TTC surface vehicles; the subway publishes no positions), MiWay, Hamilton HSR, Durham Region, YRT/Viva, Guelph, Burlington, Barrie and Kingston. Mode silhouettes -identify buses, trams, subways, trains, ferries and unclassified vehicles. +identify buses, trolleybuses, trams, cable cars, subways, monorails, trains, +funiculars, gondolas (aerial lifts), ferries and unclassified vehicles. + +A vehicle's mode comes from, in order: the feed's fleet-number hint +(`vehicleMode`, which knows a bus standing in on a streetcar route); the feed's +correction for a route its own routes.txt mistypes (`routeCorrections`: Le +Havre's funicular `8-FUNI`, which LiA's routes.txt types as a bus); the GTFS +`route_type` of its route, when its record carries one as `routeType` (basic +0–12 or extended 100–1799, each extended type taken as the basic mode it is a +kind of: 200 coach is a bus, 101 high-speed is rail, 405 is a monorail); the +feed's route-id hint (`routeMode`); and the feed's default (`transitModeFor`, +`src/data/transitFeeds.js`). The GTFS-Realtime decoder carries no route type, so +a record from the bundled proxy is classified by the hints alone. Route hints +read from each operator's routes.txt cover Prague's trolleybus lines and Petřín +funicular, and Bucharest, Cluj-Napoca and Turin's trams, trolleybuses and metro +lines (and Turin's Sassi–Superga rack tramway, typed a funicular in its +routes.txt). Le Havre's funicular is a correction, not read from routes.txt: its +route hint and its correction both say funicular. Vilnius publishes no route ids in its positions, so +its trolleybuses read as buses. Retained history classifies its epochs the same +way, so a trail joins the live vehicle. Retained transit history uses the same outlier quarantine as live observations and preserves the active live bracket. Rejected reports do not publish route or mode @@ -5795,9 +6267,10 @@ External halos are 1/1.5 px in normal, 1.25/1.25 px in CRT and 2/2 px in sensors final unpadded display size. Each mode has an outline with a front (a nose, a bow or a chamfered cab) for a vehicle with a known course and a symmetric outline for one without, which would otherwise sit at rotation 0 and point -north; a vehicle switches to the pointed glyph when a course arrives. Six modes, two sizes, three -profiles and the two outlines cap the raster cache at 72 variants. Normal mode colours are bus `#5EF08A`, tram -`#FFC24A`, subway `#FF4538`, rail `#D9A6FF`, ferry `#5FD6FF`, and unknown +north; a vehicle switches to the pointed glyph when a course arrives. Eleven modes, two sizes, three +profiles and the two outlines cap the raster cache at 132 variants. Normal mode colours are bus `#5EF08A`, +trolleybus `#B6F04A`, tram `#FFC24A`, cable car `#FF8F4A`, subway `#FF4538`, monorail `#FF6FB8`, rail +`#D9A6FF`, funicular `#E8C98A`, gondola `#7FA8FF`, ferry `#5FD6FF`, and unknown `#D8DDE5`. Selection keeps the mode colour. Sensors reuse each normal silhouette's exact outer path, filled opaque white without interior panel lines, with an opaque `#05080C` halo. Only the external padding grows; the unpadded silhouette remains @@ -5846,11 +6319,27 @@ synchronizes visible playback before its next frame. Playback reserves numeric scratch before the first sample, including unknown heights, and reuses caller-owned sample and segment storage. -**Scene work.** Stationary and animated billboards use separate, adjacent -collections above CCTV and Bikeshare. Traffic, Bikeshare and Transit share camera -sensitivity claims; the original sensitivity returns after the last release. -Visibility checks combine the camera frustum and ellipsoid occlusion at no more -than 4 Hz; missing map bounds do not admit the globe's far side. Camera arrivals +**Scene work.** Stationary and animated vehicles are two draw-port icon sets +(`transit::still` and `transit::moving`), made at adjacent draw orders +from the sprite order (`spriteDrawOrder`), above CCTV and Bikeshare. Each marker +is a plain record (position, show, image, size, colour, rotation); a frame +writes the changed ones to their set in one batched upsert, markers taken out +in one task go in one removal, and a marker that starts or stops moving moves +between the sets. The renderer moves and turns an icon without restyling it. +Rotation is computed in screen space through the query port's projection +(`perspectiveCourseRotation`), as before. Clicks read the draw-port hit. The +layer no longer reaches Cesium, so a caller handing it a Cesium viewer, +with no renderer bound, loads the `./render/cesium/unbound` export +once first. Transit listens to the camera port at its own `changed` threshold +(0.05); the port measures each listener separately, so no layer changes +another's camera trigger. +Visibility checks combine the camera port's frustum and the query port's +ellipsoid occlusion at no more than 4 Hz; missing map bounds do not admit the +globe's far side. Whether the globe is the bare ellipsoid is asked of the +height service at the camera's subpoint each time the globe's surface +changes; the answer comes asynchronously, the last one holds until then, and +floors are read again when it flips. +Camera arrivals rebuild an unprepared or cold marker corridor during that visibility sweep, adopt a loaded surface, and update both heightPending and surfaceReady diagnostics. A resolved display sample clears its pending-height gate without waiting for a poll. Frame work @@ -5881,7 +6370,8 @@ it does not establish Google 3D acceptance. The full run samples completed frames at 1920×1080 CSS pixels, records DPR, and measures moving fleets of 800 and 3,000 vehicles with 128 fixes each and DETECT on. Street/metro targets are respectively: transit frame CPU p95 ≤1/4 ms, frame -interval p95 ≤20/25 ms, billboard uploads ≤256 KiB/1 MiB per frame, and retained +interval p95 ≤20/25 ms, billboard uploads ≤256 KiB/1 MiB per frame (counted by +`src/render/cesium/uploadProbe.js` for the two marker sets), and retained heap growth ≤24/48 MiB. The 3,000-vehicle CPU budget is 4 ms (recorded browser measurement 3.4 ms); the 800-vehicle budget stays at 1 ms (measured 0.9 ms). Transit-authored frame allocation is ≤8 KiB/frame at both fleets, attributed @@ -6519,7 +7009,7 @@ silently demoting every later lookup for the session. - The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected. - The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies. -- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. +- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. With no tracked aircraft, an AIS vessel already selected (the vessel layer's `getSelectedInfo()`) becomes the subject, at activation and again when a deferred dependency settles, exactly as a vessel selected while `CONTACTS` is on; no nearest flight is picked and the camera is not moved. - `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width. - The Context header holds only its title and collapse control. It no longer carries a Radio shortcut or a compact Radio player: Radio is the `RADIO` section inside the panel, with its own disclosure and the single `ENABLE` power control. Cockpit keeps its own compact Radio utility. - Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. Outside Cyber, the two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour. Cyber keeps its separately framed mode buttons, its red panel titles, and in layout-focus a framed, centred standby card over its radar art. @@ -6530,7 +7020,7 @@ silently demoting every later lookup for the session. - On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification. - A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated. - Contacts rows and the Cockpit Contact counts name each cohort's provider: the source of the last snapshot, marked `FALLBACK` or `STALE` as its layer row would be. A poll in flight keeps the mark, where the layer row shows `LOADING`. A flight snapshot from the adsb.lol regional fallback reads `adsb.lol · FALLBACK`, not `OpenSky`. -- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is a polyline because WebGL draws ellipse outlines at 1 px whatever width is asked for, drawn as an unpickable primitive rather than an entity so a click or tap on its edge reaches the contact underneath (headless viewers without a primitive collection get a static entity instead); it is rebuilt when the subject moves. Three dim sonar pulses (3 px with a 1 px dark outline, same colours, at most 60% opacity) grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius. One unpickable 250 km disc draws both the pulse lines and the gradient, its shader reading the pulse radii and opacities each frame, so a click or tap near a pulse still reaches the contact underneath; the disc follows the subject by a model-matrix rotation and is rebuilt only after the subject moves 20 km, and not at all while the pulses rest. While the camera is below the disc's 2.5 km height, where it would sweep across the sky, the pulses rest: the disc is hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the disc and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one render request 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`), so they repaint at about 12.5 fps and never beat the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or in a scene without primitives or preRender and postRender hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. +- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline whose outer 1 px, half a pixel on each side, is a dark halo around a 3 px Context-blue core, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is one outlined line in an unpickable draw-port line set (`src/layers/awareness/rangeRing.js`), so a click or tap on its edge reaches the contact underneath; the halo is the line's own outline, so the translucent core and halo never darken where they meet; it moves when the subject moves. Three dim sonar pulses (3 px with a dark edge half a pixel wide on each side, same colours, at most 60% opacity), each an outlined line in the same set, grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius: one unpickable flat ellipse 2.5 km up with 270 km semi-axes, filled with a 256-pixel canvas painted with the band (two canvases in turn, each under a new key). The ellipse stands until the subject has moved 20 km from where it was built, the canvas keeping the band concentric with the subject meanwhile, and not at all while the pulses rest. Fronts and band are fixed in the world, so they step every 80 ms however many frames are drawn and look the same whether the camera moves or not; crossing the 2.5 km rim height shows or hides them at once. While the camera is below the band's 2.5 km height, where it would sweep across the sky, the pulses rest: the band and fronts are hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the band and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one step 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`) whose changes ask for the frame that draws them, so a parked view repaints at about 12.5 fps, one frame a step, and never beats the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or on a renderer without frame hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. - For a selected live aircraft or vessel, the context window refreshes from the existing tracker/feed position every 750 ms, so nearest distances and cohort counts follow the subject without introducing a duplicate poll loop. - Aircraft cohort membership uses every locally loaded, selectable contact inside the 250 km window, including a plane hidden only by horizon culling or because its 3D model owns the visual. Counts and navigation therefore do not change with the current camera angle or billboard/model handoff. - Nearby examples in the context panel are focus controls: they use their owning layer's existing selection/tracking path, then frame that contact. Static-installation distances use ellipsoidal surface distance so the count matches the ground-projected context disk. @@ -6546,8 +7036,8 @@ silently demoting every later lookup for the session. ### Motion & Symbology Correctness (June 10, 2026) -- **Flights (commercial + military)** render one poll interval behind real time (30s/15s) and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The display latency is an intentional product decision — do not "fix" it away. The fleet dead-reckons at ~12Hz (1m² write gating); a contact already hidden behind the horizon whose last position still is re-reckons on a staggered one-in-13-ticks rotation (about once a second) instead, so the worldwide feed's ~13k contacts no longer cost a full pass when well under 1% are on screen. Anything that position puts in view, and any contact with a fleet model, takes the full pass immediately, and hidden-inclusive proximity queries read positions at most about a second old; aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.” -- **World-space headings at every angle** (`src/data/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder. +- **Flights (commercial + military)** render behind real time and interpolate between two known feed-stamped fixes (OpenSky `time_position`; adsb.lol `receipt − seen_pos`). The delay (`src/data/displayDelay.js`) follows how late the feed is: the 90th percentile of the newest 256 lags (a report's receipt time less the same contact's previous report time) plus 5 s, never under the layer's floor (30 s civil, 15 s military) nor over five minutes, so the anonymous OpenSky feed, whose reports arrive about 90 s old every 30 s, draws about two minutes behind. Before 16 lags, first reports' ages plus a poll interval stand in. The delay moves toward that aim by at most 0.2 s per second up and 0.05 s per second down (an aim within 2 s leaves it be), and takes it at once only while nothing is drawn; deliveries following the world clock, or replacing the world at another time, leave it alone and draw with no delay. Every consumer (icons, the renderer's live motion clock, labels, HUD, detection, the tracked camera and trail) reads the one delay. When a newer report puts a moving contact elsewhere than it is drawn (it was coasting past its newest report), it eases onto the new path over at least 3 s, at most 30% faster than its speed and within 20 s, from where it would have been that frame; more than 5 km off, it jumps. The display latency is an intentional product decision — do not "fix" it away. The whole fleet dead-reckons at ~12Hz (1m² write gating); aircraft get a 3-poll grace period (faded icon) before removal, except the tracked aircraft, which is kept until 10 minutes after its newest fix. When a position epoch pauses, both layers coast for five minutes on the last speed and heading (at most 1,500 kt), then stop dimmed as SIGNAL LOST; contacts on or near known ground hold instead. Source backoff marks each contact and the cockpit `STALE` and dims the tracked aircraft, as a missed update does; the cockpit then holds the exact layer position instead of continuing inertial flight. Repeated-position kinematic changes create a forward-only synthetic fix rather than mutating history, and grounded history is lifted only when no owned 3D model already controls its datum. A nominally successful worldwide OpenSky response whose own snapshot epoch is more than two minutes old prefers the existing 250-nm viewport-scoped adsb.lol fallback and labels the source/coverage accordingly when that upstream is available. If the fallback is also unavailable, the layer's freshness/error fields use the source epoch—never the cache receipt time—so the UI reports an old snapshot rather than “just now.” +- **World-space headings at every angle** (`src/data/screenRotation.js`; the scene-reading helpers in `src/render/cesium/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder. - **Military/OpenSky reconciliation** (`src/data/militaryRegistry.js`): known-military ICAOs render amber in the flights layer (60s self-poll of the cached mil endpoint when the military layer is off) and are suppressed there while the military layer renders them. - **Satellites**: core catalog from CelesTrak's stations, visual, GPS, GLONASS, Galileo, GEO, resource, weather, planet, SAR and science groups, tracking lands ~726km out via `viewFrom` (tracked entity owns a point graphic so the tracking camera engages), rings realign via primitive modelMatrix (no per-second rebuild flicker), optional `setParams({catalog:'dense'})` Starlink mode. - **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. @@ -6681,7 +7171,7 @@ silently demoting every later lookup for the session. `activeCameraCardEnabled` presentation option can publish the retained protected-card path. Disable tears the tier down completely. Coverage/viewshed semantics unchanged. -- **Satellites**: orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. Pass prediction (`src/data/satellitePass.js`; `getNextSatellitePass`, `getNextIssPass`) scans at 20s, bisects rise/set to ~0.2s, fits the peak with a parabola, and marks a pass visible when the satellite is outside a cylindrical Earth shadow while the observer's Sun is at or below −6°. `next_iss_pass` preserves its geometric-pass ordering and appends visibility metadata. General `next_satellite_pass` accepts a loaded NORAD ID or unambiguous name, searches 24 hours and optionally requires estimated visibility. These estimates do not account for weather or satellite brightness. +- **Satellites**: every point moves every frame. Each satellite's SGP4 sample (position, velocity, gravity and its rate of change; `src/layers/satellites/motion.js`) is reckoned forward or back to the world time and turned into the Earth-fixed frame, so points glide at any play speed instead of stepping once a second. Core satellites take a fresh sample every second, or as soon as the world time is 30 s from their sample (fast play, a seek), which keeps every point within about 10 m of SGP4; Starlink extras are sampled round-robin, more per frame the faster time plays, and a point more than two minutes from its sample waits for the next one. Hidden points are not moved until shown. Orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. Pass prediction (`src/data/satellitePass.js`; `getNextSatellitePass`, `getNextIssPass`) scans at 20s, bisects rise/set to ~0.2s, fits the peak with a parabola, and marks a pass visible when the satellite is outside a cylindrical Earth shadow while the observer's Sun is at or below −6°. `next_iss_pass` preserves its geometric-pass ordering and appends visibility metadata. General `next_satellite_pass` accepts a loaded NORAD ID or unambiguous name, searches 24 hours and optionally requires estimated visibility. These estimates do not account for weather or satellite brightness. - **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer selects the unified right-side Context panel's Space Missions mode and enables the required satellite layer. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from either Context or the left Data Layers rail restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills that same panel with navigation/details, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable; its text is non-interactive shared-host presentation. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, which skips the year check rather than rejecting the match. Speed is the magnitude of the SGP4 inertial velocity vector at the same propagation epoch as position, displayed in km/s with km/h available as hover detail. Unavailable operator, site, launch-time, orbit, current-altitude, and speed values omit their detail rows instead of reserving panel space with placeholders. Newly launched payloads absent from the core operational groups use CelesTrak's cached active TLE feed as a lookup-only fallback; weak constellation-name matches are rejected. The replay callout maps compressed animation progress onto Launch Library's mission-relative timeline, showing the historical UTC date/time at the marker's current path position; unavailable timelines remain explicit. Matched live satellite positions propagate at one-second cadence and use a distinct green dot/callout with the current UTC date/time. When no mission is selected, the Context panel presents a scrollable newest-first roster of every launch in the rolling window, including the smaller 5 px operator-colored marker, provider, and launch date. Hovering or keyboard-focusing a row shows four compact cyan corner brackets on both that roster row and its corresponding globe dot, rotates the globe at the current zoom to center it, and gives its label declutter priority without selecting it; the globe label remains unbracketed. Selecting a roster row invokes the same mission isolation and full-orbit framing as clicking its globe marker. The replay vehicle is one screen-space SVG/CSS HUD overlay rather than separate Cesium billboard, label, and reticle graphics. It is hidden during ordinary Focus and manual close views, where the standard selected launch-site label remains visible, and exists only while ascent replay is active. Its fixed pixel scale is shared by ascent and insertion, so camera range never resizes the rocket on screen before the phase boundary. Generic Launch Library pad names are reduced to their identifying suffix, and replay timestamps use a cyan state title over unprefixed white UTC date/time values. `REPLAY ASCENT` holds the unframed cyan/white rocket at the pad for a real-time `T−10` countdown, transitions through `LIFTOFF`, and attaches six tapered cyan/white ellipse waves directly below it from liftoff through insertion to convey thrust without adding scene geometry. While replay is active, the single start button is replaced by compact Play, Pause, and Cancel icon controls. Pause freezes countdown or mission time, vehicle/stage positions, camera target, labels, and thrust-wave animation; Play resumes from that exact frame, and Cancel releases replay camera ownership. The rocket and thrust group rotates from the path's live screen-space tangent, so its nose follows the visible ascent curve while the adjacent text remains upright. The camera begins as a close oblique launch chase, then smoothly widens between roughly 120 and 420 km vehicle altitude into a higher oblique context view that keeps the moving rocket targeted while exposing the ascent bend and orbit connection. At insertion the rocket/thrust glyph is replaced by the fixed-size cyan orbit dot, which the camera follows through the existing globe-scale orbit pullback. The chase camera limits per-frame yaw changes across heading wraps so it cannot abruptly cross in front of the vehicle and make ascent read in reverse; the replay-speed slider affects mission playback but not countdown duration. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. @@ -7199,8 +7689,8 @@ request viewbox and continues searching without that geographic preference. - UTILITIES ▸ **Draw** turns the globe into a whiteboard drawn by hand. Pick a shape (icon buttons for Area, Line and Pin) and a colour swatch for the next shape, click the vertices on the real world, and finish. **Keyboard contract, live only while Draw is on and never while you are typing in another field:** Enter finishes the shape (as does a double-click, and the two cannot both submit it — the session is replaced before the annotate call is awaited); Backspace removes the last vertex; Esc cancels the shape in progress, and a second Esc — Esc on an empty session — leaves draw mode. **Clear** wipes the board (the shape in progress and every placed mark), so removing marks does not require the console or the microphone. - **Drawn shapes are listed under Draw like Import's files** (`src/ui/views/panels/DrawMarkList.vue`, rows worded by `presentDrawMarks` in `src/annotations/drawMarks.js`): one row per hand-drawn mark (`manual: true`; voice marks are not listed) with its colour swatch, its name, and show/hide, fly-to and remove. The draw tool publishes the rows with the rest of its controls and answers the row actions (`renameDrawMark`, `recolorDrawMark`, `toggleDrawMark`, `flyToDrawMark`, `removeDrawMark`) through the display store; it republishes on the engine's `onChange`, so a voice clear or an expiry updates the list. Rows are keyed and updated in place: a board change never takes a name being typed (the field keeps its draft while focused) or the button under a click. The name is saved on Enter or on leaving the field, once; Esc restores it, before anything else and with the row's colours open too. Both keep focus in the field, so neither drops it to the page or leaves Draw. The swatch opens the five colours right after it (shown at the end of the row), with the current colour focused; the arrows, Home and End try another, and a click or Esc closes them and returns focus to the swatch. Both colour groups (the next shape's and a row's) are one `DrawSwatches` radio group with a single tab stop, coloured from `DRAW_COLOR_CSS`; on touch screens each dot answers a 24 px target. An unnamed shape shows its kind, and an unnamed line its length; a renamed line keeps its length (`Ridge walk — 950 m`). **Hidden** keeps a mark on the board at alpha 0, and the world renderer takes every one of its entities out (`show = false`), so no material that keeps its own colour (the line's flowing stroke) still paints it; the screen renderer does not project a hidden callout, so it cannot push a visible label aside; `fly_route` skips a hidden route; and with every mark hidden the annotations render hold is released. **Fly to** is an immediate navigation (`runImmediateNavigation('drawing', …)`), like Import's: Cockpit refuses it and a running orbit, follow or track lets go first. A line is framed by its whole path, across the antimeridian too. -- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the Cesium handler, the preview data source, the borrowed click actions and the `window.__gevDrawTool` handle. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam. -- **The pointer, for an application's own tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner)` takes the pointer as Draw does and returns its lease, or `null` while another tool holds it; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. An owner without a name in `pointerOwnerNames.js` is named by its id when another tool reports who holds the pointer. +- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the pointer subscriptions, the preview draw sets, the borrowed click actions and the `window.__gevDrawTool` handle. The live preview (a dashed rubber band, dashed behind the surface too through the line's `depthFail` style, and a dot per vertex) is two sets on the renderer's draw port, so the tool no longer reaches Cesium; the rubber band follows each move's `pickPosition`, the dispatcher's sensor-corrected pick-buffer point, as clicks do. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam. +- **The pointer, for any other tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner, { onLost })` takes the pointer as Draw does, from any tool holding it, and returns its lease; `onLost` is called once when a newer claim takes it, and the tool turns itself off there; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. - **Row actions are an application's own.** `createApplicationTools({ drawMarkActions })` hands `initDrawTool` buttons for drawn areas' and lines' rows; the standalone shell passes none, so the open-source build shows no new button and makes no new request. Each action (`drawMarkActions` in `src/annotations/drawMarks.js`) is `{ id, icon, label(name), shapes: ['area', 'line'], accepts?(geometry, shape), run({ id, shape, name, title, geometry }) }`: the icon a Material Symbols name, the label worded by the application, `name` the person's own and `title` the row's (the name, else `Area` or `Line · 950 m`), the geometry `drawMarkGeometry`'s `[lon, lat]` `Polygon` (closed; a `MultiPolygon` for an area handle with several parts) or `LineString`, longitudes wrapped into [-180, 180]. A pin, and a shape that crosses the antimeridian or has a part that cannot be given whole, has no geometry and is offered nothing. Malformed actions and repeated ids are dropped once, at construction. What `run` returns or resolves to is a note under the row (`role=status`; past 200 characters it is cut at a word with an ellipsis); the row is busy (`aria-disabled`, no second press) until it settles, a rejection or a throw clears the note and is logged (so an action words its own refusals and resolves with them), and a shape's note goes with the shape, so a late answer never lands on a removed one. - Contract: a finished shape is submitted through the SAME `annotationEngine.annotate()` the voice agent uses, with geometry supplied and `manual: true` (`type: area` + `ring`, `type: route` + `path`, `type: pin` + coordinates). `resolveSpec` short-circuits manual specs (`resolveManualSpec`) so no geocoder, Places or Overpass call is made. A drawn area is a real (not synthesized) outline and drapes solid; a drawn line is a `route` with `mode: 'manual'`, labelled with its length and never a travel time; a pin is a point. Drawn marks therefore render with the whiteboard look, persist, appear in `.list()`, and clear with `clear_annotations` / `.clear()`. A drawn shape is never merged with another as a duplicate: every one is drawn on purpose, and every one is unnamed until its row names it, so two pins dropped close together are two pins. - **A vertex is a lon/lat, and the mark is DRAPED.** Clicks are picked through `pickWorldFromScreen` — one of two scene helpers the annotation resolver factory (`src/annotations/resolver.js`) exposes alongside `sampleGroundHeight`, so the app has ONE depth-aware pick cascade rather than a second written beside it — which returns the height the pick landed on as well as the coordinate, so the live preview hangs on the roof or hillside under the pointer instead of sinking to sea level. The world renderer draws areas and routes with `clampToGround`, so the height is dropped at finish in one place (`finishSpec`) rather than being carried downstream and discarded silently: what you get is the outline you drew, lying on the surface beneath it. @@ -7210,9 +7700,10 @@ request viewbox and continues searching without that geographic preference. - **Measurements and centres are computed on unwrapped longitudes** (`unwrapLongitudes` / `wrapLongitude` in `drawMode.js`, used by `ringAreaM2`, `ringCentroid` and the engine's manual-area anchor). A ~50,000 m² rectangle straddling the antimeridian reads its 0.002° width as 359.998° under raw arithmetic: it measured thousands of square kilometres and anchored on the Greenwich meridian, half a world from the shape. Path length was already safe — haversine is periodic in the longitude delta — and a test pins that so a "fix" cannot break it. - **Bounds.** One shape holds at most `MAX_VERTICES` = 512 points; two clicks within 0.5 m are one vertex (that is what makes a double-click finish without leaving a stray point); a vertex that is not a finite on-globe coordinate is refused. A shape that encloses nothing is refused rather than placed: three collinear points are not an area and a line under a metre long is not a line, and the hint says which. - Drawn-area measures round before choosing m², ha or km², so 9,999.6 m² displays as `1.0 ha`, not `10000 m²`, and 999,960 m² as `1.00 km²`, not `100.0 ha`. -- Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`) and **every** ambient scene selection handler — the shared tracking click gesture behind flights, military and CCTV, plus vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers and the CCTV calibration gizmo — returns before picking. A vertex over an aircraft is a vertex, not a selection. -- **The claim is a LEASE.** `claimPointer(owner)` returns an opaque token or `null`; `releasePointer(lease)` takes that token. A second claim fails even under the same owner name, because two live instances of one tool — an old one mid-teardown and its replacement — are two owners; releasing by name let the old instance free the claim its successor was holding, and every layer started selecting through the live session's vertices. A superseded lease now releases nothing. -- **Cesium's own click actions are borrowed too.** The Viewer binds a selecting LEFT_CLICK and a tracking LEFT_DOUBLE_CLICK on its own handler, outside every layer and therefore outside the shared claim — guarding the layers alone still left a drawn vertex selecting the entity under it. Both are removed for the session and restored, as the same function objects, when it ends or the tool is destroyed. +- Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`), and the scene's input dispatcher (`src/input/dispatcher.js`) hands its clicks, moves and double clicks to the draw tool's leased subscriptions only: **every** ambient subscriber — flights, military, CCTV and its calibration gizmo, vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers — is skipped for that event before anything is picked. A vertex over an aircraft is a vertex, not a selection. +- The input dispatcher no longer reaches Cesium. It takes its pointer events from the renderer's input port (`findInput`, `src/render/rendererOf.js`) and its picks, drills and ground points from the query port, with positions as plain `{x, y}`. A click's hits are the contract's `Hit`; something drawn outside the draw port is a `Hit` with `set: ''` that the Cesium adapter names (`src/render/cesium/nativeClick.js`), which also hangs the engine's own picks on `event.native` (`pick`, `pickWindow`, `drill`, through the follow helper) for layers still bound to them. The adapter's pick reuses the query port's pass for the same pixel, window and frame, so an empty click still costs one pick pass; a sky click makes no depth pass unless a globe tile is on its ray. A touch tap's contact search drills Cesium's own picks, eight deep, so something drawn outside the draw port still stops it or is found by it. +- **The claim is a LEASE, and the newest claim takes over.** `claimPointer(owner, { onLost })` returns an opaque token; `releasePointer(lease)` takes that token. A second claim, even under the same owner name, ends the lease out, and its holder's `onLost` is called once, after the new lease holds the pointer: Draw turns off as if toggled off (the half-drawn shape and preview go, the stock clicks come back), the imagery box cancels, and Directions disarms. Two live instances of one tool — an old one mid-teardown and its replacement — are two owners, so the replacement wins; releasing by name let the old instance free the claim its successor was holding, and every layer started selecting through the live session's vertices. A superseded lease releases nothing. This is the renderer contract's rule (`input.claimPointer`), and the two are one: each scene's input dispatcher bridges its renderer's input port (`bridgePointer`), so the port holds a lease while a tool holds the pointer (the port is not free), and a claim made on the port itself takes over from the tool like any newer claim. That lease takes no press itself: the dispatcher decides who hears each event when it arrives, as each layer's own handler used to (a click reaches ambient selection only if no tool holds the pointer then, and a tool's subscribers only while its lease is current), and Cesium's own select and double-click follow run unless the tool holds them off (`suppressStockClicks`: Draw and the imagery box do, Directions does not). +- **Cesium's own click actions are suppressed too.** The Viewer binds a selecting LEFT_CLICK and a tracking LEFT_DOUBLE_CLICK on its own handler, outside every layer and therefore outside the shared claim — guarding the layers alone still left a drawn vertex selecting the entity under it. The tool takes the dispatcher's `suppressStockClicks()` hold for the session; both actions come back, as the same function objects, when the last hold is released (the imagery box takes the same hold). - **Enter belongs to whatever has the keyboard.** The finish key is taken only from the canvas and the page body. With a control focused — Clear, a shape button — Enter activates that control, as a keyboard user expects; it does not quietly finish the shape. - Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`. - The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`. @@ -7237,14 +7728,14 @@ request viewbox and continues searching without that geographic preference. - Only a new head costs REST calls: one recursive tree and one commit. An optional `GITHUB_TOKEN` raises the REST limit. - After an upstream outage, a successful branch-head check clears the error and pushes a recovered catalog even when the commit is unchanged. Cached products stay in place; subsequent healthy unchanged checks stay silent. - The new catalog goes to `.gev-cache/ghostmaps/catalog.json` and to every open page over server-sent events (`/api/ghostmaps/events`, 25 s heartbeat, at most 64 subscribers). Default products are downloaded at once. - - The layer reloads only products whose blob changed. The new edition's data source is added before the old one is removed. A product that leaves the catalog leaves the globe. + - The layer reloads only products whose blob changed. The new edition's draw sets are added before the old ones are removed. A product that leaves the catalog leaves the globe. - The row reads `LIVE` while the stream is open. A five-minute catalog read is the backstop. - **Files.** `/api/ghostmaps/file/{product}` serves only catalog products. Files are downloaded by commit-pinned raw URLs, so a CDN cannot return an older edition. They are cached on disk by blob sha, and blobs no current product uses are pruned. A request whose `?v=` names the current blob is `immutable`. Repository paths never reach the page. - **Source ownership.** The application catalog receives `sources['s2-ghostmaps']` through the shared source contracts; an omitted or null source stays unavailable without opening a stream or fetching. The standalone source factory supplies the same-origin implementation and accepts replacements. Packed-image URLs are released on cancelled or failed product construction, and remain owned by a successfully loaded product until it is removed. - **Voice and locales.** S2 can be toggled through its registered id and aliases. The model already sees the S2 GhostMaps brand in the id, and compact alias-hint separators keep the complete voice prompt within its existing 52,000-character limit; accepted aliases are unchanged. The row and reports are translated in Spanish, Russian and Simplified Chinese. -- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into one `CustomDataSource` per product. - - Points become ground-clamped billboards with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. - - Lines and polygon outlines are ground-clamped polylines. +- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into renderer draw sets (icons, lines and shapes) per product edition. The layer no longer reaches Cesium, so a caller handing it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first. + - Points become ground-clamped icons with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. + - Lines and polygon outlines are ground-clamped lines; polygon fills are ground-clamped shapes. - Styles, StyleMaps and inline styles are honoured. Icons come only from images packed in the same KMZ and at most 512 KB. Anything else uses a per-product round marker. - Network links, overlays, models and remote hrefs are never followed. Hidden placemarks are skipped. Bounds are 20,000 placemarks and 250,000 positions per product. - **Reports.** Clicking a marker opens a card with the product, folder, edition date and the placemark's report fields. `src/layers/ghostMaps/records.js` reads ArcGIS popup tables as text only: `` and internal fields are dropped and values are capped. Description markup is never inserted into the page. The first `http(s)` research link opens from the card. The card is `stateless`, so it comes and goes with the click, as CCTV cards do. It is also `horizonCull`ed, so it hides when its marker turns behind the planet. Picks are registered under `s2-ghostmaps`. @@ -7253,14 +7744,15 @@ request viewbox and continues searching without that geographic preference. ### Import Your Own Files (October 2026) - UTILITIES ▸ **Import** reads GeoJSON (`.geojson`/`.json`), KML, KMZ and GPX from the picker or a file drop anywhere in the app. Each file gets show/hide, Fly-to and Remove controls. GeoJSON and GPX use the row's color; KML/KMZ retain their styles and show a hatched swatch. The file bytes remain on the device for the page session. Rendered overlays can appear in map screenshots sent through voice or other existing screenshot tools. -- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 against loaded terrain and, in the nearby camera footprint on photoreal maps, `clampToHeightMostDetailed`, then draw in one owned native BillboardCollection per file, with static positions and no per-frame point Entity visualizer or clamping callbacks. Point metadata remains in `dataSource.importedEntities` for framing/style inspection; non-point geometry stays in the normal source collection. Pin collections mount only after source admission, follow file show/hide, and are destroyed on removal. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy. +- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 through the height service: the loaded terrain's height (0 on the bare ellipsoid, whose coarse tiles can sag far below it) and, in the nearby camera footprint on photoreal maps, the mesh height (`clampBatch`). They then draw as static icons in the file's own draw sets (pins, lines and shapes), with no per-frame clamping callbacks. GeoJSON lines and polygon edges follow rhumb lines, split into steps of at most half a degree. Each file's sets mount only after admission, follow its show/hide, and are removed with it. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy. - **Navigation.** Row Fly-to uses `runImmediateNavigation('file', …)`; Cockpit can refuse it and existing follow/track ownership is released first. Automatic Fly-to is stamped when a batch is submitted and reasserted before flying. Pointer/wheel gestures and newer navigation supersede it, including time spent in the queue. Framing uses every finite visible point/path/polygon-hole/wall vertex plus rotated overlay bounds, with viewport-aware range and a nadir view. The target uses available terrain/cached ground height and the ground guard on arrival. Empty footprints never fall back to deferred `viewer.flyTo`. -- **Clock.** Imports expose no source clock and no entity availability. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged. -- **Input handling.** Coordinates and GeoJSON geometry types are checked before Cesium allocation. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits. -- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, native labels and descriptions are removed, and generated pins share one lossless image URL per canvas. +- **Clock.** Imports keep no clock and no time ranges: everything in a file draws at all times. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged. +- **Input handling.** Coordinates and GeoJSON geometry types are checked before anything is drawn. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits. +- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, labels and descriptions are removed; only a short plain name reaches a drawn item. The default pins are shared SVG images. - **Bounds.** File size ≤50 MiB; inflated KMZ ≤120 MiB; ≤20,000 entities (including multipart children and Folder containers); ≤250,000 positions; ≤2,000 normalized style definitions and distinct image links; ≤12 files per session. Exact repeated styles share definitions without changing inheritance or inline overrides. Files of 20–30 MB fit the byte budget, subject to geometry/image limits. Refusals name a reason and batches continue; with multiple failures the hint shows the first reason. -- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes data sources, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import. -- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, native style/image equivalence, large-file painted output and frame times. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules. +- **Code layout.** `src/data/geoFileImport.js` reads, bounds and sanitizes the files. `src/data/geoImportFeatures.js` turns the sanitized KML or GeoJSON into plain features (pins, lines, walls, polygons and ground overlays) with the styles Cesium's KML and GeoJSON loaders gave them: icon, scale, colour, heading and hot spot; line and polygon colours and widths; extruded or clamped geometry. `src/data/geoImportPins.js` draws those features through the renderer's draw port (`drawOf`), settles ground pins through the height service and frames the file for Fly-to. None of the three reaches Cesium, so the Cesium allow-list is empty. `src/data/geoImportShared.js` holds the error, limits, deadline and feature names they use. +- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes each file's draw sets, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import. +- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, that what the import draws matches Cesium's own `KmlDataSource` reading of the same file (positions, scale, heading, colours, widths, fills), large-file painted output and frame times. The QA scripts read what a file drew through `window.__gevGeoImport.drawn(id)`. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules. ### Recent Imagery (September 2026) @@ -7275,7 +7767,7 @@ pins and share links already supply complete boxes. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. - **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. - **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once. - **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). @@ -7284,14 +7776,15 @@ pins and share links already supply complete boxes. ### 3D Aircraft + Tracking (June 2026) - **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. -- **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. +- **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. Tiles still streaming is not a miss: no sample is taken, so it earns no retry backoff, and the first fleet tick after the tiles settle samples (2026-11-15); only a sample that finds no ground backs off (2 s, doubling to 30 s). WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. - **Ground-snap clock rollback recovery.** If the wall clock moves before the sampling-window start, ground snap opens a new window while retaining the normal four-samples-per-250-ms budget. Retry timestamps more than the maximum 30-second backoff ahead of the current clock are ignored. A smaller rollback can retain a bounded retry delay of up to 30 seconds. -- Commercial and military aircraft use the same high-level FLEET model regime: 2D billboards when zoomed out, optional glTF models when closer, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Since 2026-08-16 (Hangar fleet) models are PER-CLASS: real CC-BY GLBs for light/bizjet/turboprop/widebody/helicopter/uav (`CLASS_MODEL_REAL` in `src/data/aircraftClass.js` — meters-baked, scale 1, per-model belly/radius; provenance in `public/models/README.md`), the shared `airplane.glb` for the remaining civilian classes, and the military layer maps weight classes (real GLBs / 747 heavies / `jet.glb` fastjets, per-model heading offsets, flat amber or emergency red). Textured civilians carry a HEAVY tint, not a light one: `MODEL_COLOR_BLEND_AMOUNT` is `0.94` in BOTH layers under Cesium's `ColorBlendMode.MIX`, so the class colour supplies 94% of the surface and the asset's own texture ~6%. The visual direction is clean light silhouettes with only a weak diffuse contribution from the approved textures, so liveries deliberately do NOT read. IR boost raises the blend to a full `1.0`. Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit. -- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). With the class colour supplying 94% of the surface, the models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; the two preload calls only warm the glTF cache and are never drawn. +- Commercial and military aircraft use the same high-level FLEET model regime: 2D billboards when zoomed out, optional glTF models when closer, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons. The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the tracked colour (cyan, or amber in Military Flights) and the emergency red multiply into the mesh, so its paint still shows. IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit. +- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and add/keep radii as the aircraft (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is a bone-white ringed disc (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`) instead of a chevron, never rotated, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its disc but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay. +- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload. - The DISPLAY-rail `3D` toggle is the user-facing activation path for both aircraft layers. Their small approved GLBs build their render resources without Cesium's frame-spread job queue, preventing continuous Photorealistic 3D Tiles streaming from starving model readiness; model caps, tracking, camera, and fallback billboards are unchanged. - **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only below `MODEL_ALT_CEIL_M` and only for the nearest `MODEL_MAX` in view — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. **Consequence for returning users:** a stored `gev:layer-state:v2` blob is a FULL options snapshot, so a session that wrote one before this change carries `models3d:false` and keeps 3D off until the operator flips it (or clears the key) — the durable snapshot is treated as the recipient's own state, by design. - **Consequence of the flip on the recorded tracked/fleet inversion:** the 150–800 km band where surrounding contacts draw as models while the SELECTED one is still a glyph is now what an operator sees WITHOUT arming anything. The inversion itself is unchanged and still deliberate (see `src/data/trackedModelRegime.js`); only its reachability changed. @@ -7303,7 +7796,7 @@ pins and share links already supply complete boxes. - Fleet model eligibility is distance-based with on-screen priority and hard caps (`MODEL_MAX`, `MODEL_MAX_ALL`) to avoid draw-call explosions. Each model owns its own `modelMatrix`; shared scratch matrices are forbidden because they caused stacking/flicker. - Tracked aircraft use standalone model primitives driven from the already-settled dead-reckoned display position, while the tracked Cesium entity remains billboard-backed so `viewer.trackedEntity` always has a ready bounding sphere. - Flights and military layers mirror the same tracking invariants: no warm-up freeze/jump, altitude-scaled framing, trail head glued to the displayed plane, no pull-out when switching targets, and no cross-layer orphan when switching between commercial and military tracks. -- Regression surface: `npm run test:track` drives the real app headless with synthetic aircraft feeds and asserts the tracking invariants without depending on live OpenSky/adsb data. Arrival-rotation checks observe the settle frame and then the first reveal frame, each within a 500 ms wall-clock budget that sits inside the one-second idle fallback, rather than assuming the 80 ms fleet cadence fits inside four rendered frames; an incorrect first orientation fails immediately. Only an inconclusive timeout is retried (once); a timeout keeps every angle it measured (the settle frame before a reveal timeout, and the late frame itself, which is read before the deadline check), so a measured wrong angle fails without retry. `src/data/trackedModelRegime.test.mjs` pins the tracked contact's threshold math, the enter/exit asymmetry, and the default-on / cockpit / TR-3B / deselect wiring in both layers. +- Regression surface: `npm run test:track` drives the real app headless with synthetic aircraft feeds and asserts the tracking invariants without depending on live OpenSky/adsb data. The harness reads what the app draws through its own seams: what the camera follows through `src/data/followed.js`, icons from the draw port's icon sets as the renderer holds them, and models by their `{set, id}` pick ids. Arrival-rotation checks read the drawn rows' course (the icon sets turn each icon along it on the GPU every frame, so there is no CPU rotation pass to repair a stale nose) and observe the settle frame and then the first reveal frame, each within a 500 ms wall-clock budget; an incorrect first orientation fails immediately. Only an inconclusive timeout is retried (once); a timeout keeps every angle it measured (the settle frame before a reveal timeout, and the late frame itself, which is read before the deadline check), so a measured wrong angle fails without retry. `src/data/trackedModelRegime.test.mjs` pins the tracked contact's threshold math, the enter/exit asymmetry, and the default-on / cockpit / TR-3B / deselect wiring in both layers. ### TR-3B conversion Easter egg (August 2026) @@ -7592,6 +8085,76 @@ easier to meet (detection is now on more often), but does not create it. above and the DISPLAY-rail entry below (was `OFF`). - Style shader starting params: CRT/NVG/FLIR pixelation `1.2` (just above the native `1.0` floor); thermal/FLIR ships an optional Ironbow "Predator" palette (`palette` uniform, default `0` = accurate grayscale). +## Renderer contract + +`src/render/contract/` types the renderer contract, version `0`: nine ports +(frame, globe, draw, camera, query, input, effects, credits and quality), +plus the renderer itself. `PORTS` lists every member at run time, and +`contract.test.mjs` keeps that list and the types in step. +`src/render/stub/` is a renderer that draws nothing, with the default +camera's exact maths. `src/render/conformance/` is the suite: logic checks +in Node, plus camera traces recorded from Cesium's own `Camera` into +`goldens/camera.json`. It also holds the reference scenes, whose views are +checked against `goldens/visual/` on the `/dev/conformance/` page. +`npm run qa:conformance` runs the logic checks on the Cesium renderer in +headless Chromium, in CI too. After `destroy()` the Cesium renderer's +handles do nothing, and `renderOnce` and `capture` reject. See +[RENDERER-CONTRACT.md](RENDERER-CONTRACT.md). + +### The application and its renderer + +The application starts on whichever `RendererPlugin` it is given +(`createStandaloneApplication({ renderer })`), and on Cesium when none is. +`src/app/scene.js` loads the Cesium adapter (`src/render/cesium/application.js`) +only then, with `import()`; the standalone page starts that load as it +starts, beside its own setup. Outside `src/render/` no code reaches a +renderer's own objects: the record of files that still did, +`src/render/viewerAccessAllowList.json`, is empty. + +- What every layer and tool is handed is the scene object + (`createSceneHost`), bound to the renderer: its container, and whether it + is destroyed. Everything else goes through the renderer's ports. +- What a renderer's own plugin adds beside the contract (stale draw-command + trims, inline panel drawing, the zoom-out guard, its own map engine, the + detection overlay's occlusion probe, what QA scripts read) it hands through `src/render/applicationHooks.js`; the + application uses each where given and does without where not. + Renderer-only startup (Cesium's free-look limit, credit keyboard access) + runs in that plugin's `create`. +- The map stacks switch through the plugin's map engine, else the globe + port (`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, Cesium + ion imagery as `world` imagery, terrain as `world` terrain, or the + ellipsoid where no keyless terrain is offered, and photoreal as the port's + photoreal base. A photoreal base that fails to come back leaves the globe + shown. +- The renderer follows its container's size (`Renderer.resize`, from a + `ResizeObserver`). +- The credits: the Cesium renderer's plugin says it shows them in a display + of its own (`ownCreditDisplay`; `#cesium-credits`), which it keeps. On the + stub, the application shows what the credits port lists in its own line + at the bottom left (`#gev-credits`, `src/ui/creditsView.js`): the inline + credits on the line, the rest (the layers' data credits among them) in + the "Data attribution" list it opens, a keyboard button with Escape to + close. + +`npm run qa:stub-boot` boots the whole application on the stub with only +the contract's required members (`dev/stub-app/main.js`, served in place of +`src/main.js` on the application's own page), headless. It fails if +the credits line is not shown or its list is empty, if Cesium's code is +requested (the one stylesheet `vite-plugin-cesium` links +into every page is reported), on any page or console error, or if a data +layer (flights, military aircraft, transit, traffic, CCTV, AIS vessels, +weather radar and satellite, wind, satellites, FIRMS, wildlife, shipwrecks, +news) fails to turn on or off. A +feed's failed response (no key, no network) is reported, not failed; +`--strict` also fails a layer that drew nothing, and `--all-capabilities` +gives the stub every capability. CI runs it in the browser job. + +`src/geo/` (export `./geo`) is the Cesium-free maths: WGS84, ECEF and +geodetic conversions, surface normals and east-north-up frames, as plain +`{x, y, z}` objects. It follows Cesium's formulas step for step, and +`geo.test.mjs` checks it against Cesium. The stub renderer's maths is built +on it. + ## Operational Notes - **Earthquake discs are STATIC geometry.** Every quake is a `CLAMP_TO_GROUND` @@ -7848,8 +8411,9 @@ easier to meet (detection is now on more often), but does not create it. Every failed read cancels its body and aborts its owned request, including declared and streaming byte-cap failures. - Development captures opened with `?trafficDebug=1` mint an interaction anchor - from the exact `camera.changed` event that arms each debounced load, then emit - scheduling-correlated User Timing entries for production `response.json`, road + from the exact camera-port `changed` event that arms each debounced load, + then emit scheduling-correlated User Timing entries for production + `response.json`, road parse, dot construction, heat-line rebuild, and next-post-render boundaries. Every trace is paired with the exact camera-change that scheduled its load; mismatches are counted drops. Cesium's `moveEnd` remains a diagnostic @@ -7875,7 +8439,7 @@ The Space Missions roster prioritizes data-rich records using available mission, When no live catalog track is available, the mission view marks the approximate orbital ring as `PROJECTED ORBIT` in purple and renders the ascent-to-insertion transfer in green; catalog-backed satellite orbits remain cyan. The replay vehicle is a smaller solid cyan silhouette without the former orange flame; its initial pad anchor uses photoreal terrain, globe height, or launch elevation fallback so it remains above the surface during tile loading. Replay begins at a close launch-complex range so pad detail remains visible before the camera widens into the ascent context view. Its initial camera heading is perpendicular to the ascent/orbit direction for a profile view, then eases into tangent tracking. Small screen-space reprojection changes are damped for the animated marker on both ascent and orbit, while large camera or phase changes snap to the authoritative path position. -Space Missions keeps the Satellite layer available for catalog/TLE matching but suppresses its standalone fleet points and orbit rings. While those visuals are hidden, their per-frame dense propagation, one-second core point-buffer rewrite, and one-second orbit-matrix rotation are suspended; selected mission telemetry continues to propagate independently. The selected mission's live or estimated satellite marker uses fractional wall-clock time, so it moves continuously rather than creating a once-per-second position discontinuity and one-frame photoreal globe LOD pulse. +Space Missions keeps the Satellite layer available for catalog/TLE matching but suppresses its standalone fleet points and orbit rings. While those visuals are hidden, their sampling, per-frame point moves, and one-second orbit-matrix rotation are suspended; selected mission telemetry continues to propagate independently. The selected mission's live or estimated satellite marker uses fractional wall-clock time, so it moves continuously rather than creating a once-per-second position discontinuity and one-frame photoreal globe LOD pulse. During ascent replay, the camera, Cesium callbacks, and HTML vehicle overlay share one replay sample per rendered frame. The tracked overlay is projected directly from that shared position instead of applying a second screen-space lag filter, preventing the vehicle and globe from repeatedly advancing and snapping back. @@ -8184,6 +8748,25 @@ request HTTPS tiles even on HTTP localhost, with the existing Content Security Policy unchanged. Ion attribution and Bing's per-tile credits are preserved; other ion imagery assets continue through the SDK's standard ion factory. +The imagery, terrain and 3D factories are the Cesium renderer's +(`src/render/cesium/mapImagery.js`, `mapTerrain.js`, `google3d.js`; the +package exports `./maps/imagery`, `./maps/terrain` and `./maps/3d` point +there). The catalog, the default registry and the controller are +Cesium-free: they reach those factories, and the scene operations a +switch makes (imagery layers, terrain, the globe's visibility, tilesets), +through the scene's map engine (`mapEngineFor` in `src/maps/engine.js`). The +Cesium plugin hands the application its own engine with each renderer it makes +(`src/render/cesium/mapEngine.js`, through `src/render/applicationHooks.js`), +and the application scene loads the photoreal base through it too. A renderer +whose plugin hands none switches through its globe port +(`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, ion's world +imagery as `world` imagery, photoreal as the port's photoreal base (turned off +while hidden, on again when shown), and world terrain, or without a key +Re:Earth's keyless terrain as `quantizedMesh` terrain at its URL +(`src/maps/keylessTerrain.js`), as the Cesium engine draws it; a renderer +without the `terrain` capability keeps the ellipsoid. A viewer with no renderer bound gets the Cesium engine, with the +other unbound ports, from the package's `./render/cesium/unbound` export. + The controller accepts other source registries without adding provider branches. Each instance caches source construction, ignores superseded scene changes and releases imagery layers/listeners on replacement. Destroy invalidates pending @@ -8217,24 +8800,68 @@ Wind supports selectable GFS/IFS models with persisted model choice. Each fetch Weather combines the GFS/ECMWF surface forecast with three observation layers: NOAA Rain radar (CONUS), Satellite clouds (regional GOES or slower global infrared), and 15-minute lightning density (Americas and Pacific). One transient observed -clock drives all enabled observation rows. Earlier/Later use the sorted union of -non-suspended products' advertised times; each product selects its nearest frame -at or before the requested UTC time, never a future frame or an interpolation. +clock moves all enabled observation rows with the world clock; the world +timeline is the only time control. Each product's advertised times span time on +that timeline but are not marks on it: the timeline marks only events (launches, +and earthquakes of magnitude 6 and up while that layer is on), so its arrow keys +step to those, or along the track where there are none. A mark may carry a +label (a launch's mission name, cut to 27 characters in capitals as the mission +index shows names; an earthquake's magnitude and place). Marks merge on their +whole label; one longer than 60 characters (graphemes, so an emoji is never +split) then shows cut, ending in `…`, and a label is never wider than the +track. A zoom or +a pan clears a hovered label. The pointer within +6 px of a tick shows its label over the track, and a tap there goes to the +mark's time exactly; a tap elsewhere goes to the time under it and a drag +scrubs. With the handle on a mark, its label follows the time in the handle's +`aria-valuetext` and shows over the track while the handle has focus. The +coverage contract is in [APPLICATION.md](./APPLICATION.md). A weather row's `step` +param goes to the previous or next weather frame. Each product selects its +nearest frame at or before the world time, never a future frame or an +interpolation. The maximum gap is 30 minutes for radar, regional infrared and lightning, and -3 hours for hourly global infrared. A missing eligible frame hides that product +3 hours for hourly global infrared, but never less than one and a half of the +feed's median frame spacing over its latest frames, so a regional feed whose +frames come an hour apart holds each for 90 minutes; the latest frame reads late +after the same floor (20 minutes for radar and regional infrared, 45 for +lightning, 4 hours for global infrared). A missing eligible frame hides that product and reports the gap; rows show actual displayed UTC time with synced/nearest labels. Manifest rollover preserves the requested history time, even when frames expire. -Latest follows each product's own newest frame, so its timestamps can differ. -Playback advances two seconds after all products settle, wraps, and stops with -fewer than two union times or when all products are suspended. Hidden documents, -reduced motion and unavailable imagery hosts suspend products. Re-enabling or +Live follows each product's own newest frame, so its timestamps can differ. +The timeline's Play runs the world clock at the chosen speed and stops at each +product's next frame until that frame loads (for at most eight seconds), so +every frame shows. Hidden documents, reduced motion and unavailable imagery +hosts suspend products. Re-enabling or restoring a host joins the retained history target. The wind row explicitly says -“Forecast · does not follow history” while the observed clock is in history mode. -The catalog exposes `weatherClock` and destroys it with its lifetime signal. +“Forecast · does not follow history” while the observed clock is in history mode, +unless a host follows the world clock for `wind` (`weatherClock.follows('wind')`): +its source then follows the timeline and the row says nothing of it. In history +mode, frame ages and the “Source observations delayed” status are measured from +the timeline time rather than the wall clock, and the timeline readout shows the +time alone; live, they count from now as before. +The Weather panel's frame time shows the newest frame and its age while live +(each product's newest, suspended products included), and the timeline time +alone at a past time. +The catalog exposes `weatherClock` and destroys it with its lifetime signal. It +has no time controls of its own: `weatherClock.world` is the world clock it +follows, where time moves. A weather row's `play`, `latest` and `step` params +move that world clock as the timeline does: `play` runs at the speed chosen on +the timeline (the world clock keeps its rate while paused and live, and the +timeline's speed selector shows the clock's rate, or the nearest offered speed +for a rate a host set), from the start of the covered time when live or at its +end, and does nothing while every product the row shows is suspended or while +there is no covered time. A weather layer built without a +shared clock builds one of its own on the page's world clock when first +enabled (`createWeatherClock({ shared: false })`) and keeps it for its +lifetime; destroying it leaves the world's time where it is, and enabling it +after that does nothing, and only the last +shared weather clock destroyed sends the world live. Neither has a frame replay +of its own. -Source, opacity, coverage navigation and transport controls live in the WEATHER -panel's cards and timeline, not in the rows. The viewer clock is untouched. +Source, opacity and coverage navigation live in the WEATHER panel's cards, not +in the rows; the panel shows the frame time and has no time controls. The +viewer clock is untouched. Observation layers are off by default; share/persist includes appearance and product, while history is transient and shared links open latest. Rendering retains the previous frame when an incoming frame fails; no eligible historical frame instead hides imagery. diff --git a/docs/DIRECTOR-DATA-PACKS.md b/docs/DIRECTOR-DATA-PACKS.md index bf64efd0bf..3c223e33f9 100644 --- a/docs/DIRECTOR-DATA-PACKS.md +++ b/docs/DIRECTOR-DATA-PACKS.md @@ -95,6 +95,11 @@ registry of source functions. Each receives `{ path, signal, maxBytes }` and returns `{ bytes: Uint8Array, mimeType }`. Custom transports must honor the signal, bound reads and return the real MIME type. They remain application code, not scene document fields. Without registrations, referenced sources fail closed. +A standalone `SceneDirector` also passes `dataPacks.overlayHost`, the +world-overlay host that draws pack world text such as a media pack's label (an +object with `setEntries(sourceId, entries)` and `clearSource(sourceId)`); +without it a media pack fails to load. `createApplicationTools` passes the +application's shared host. The portable session receives format adapters separately. Each adapter receives `{ pack, asset, anchors, signal }` and returns a resource with an idempotent diff --git a/docs/I18N.md b/docs/I18N.md index f94d30d563..fd8234ea2b 100644 --- a/docs/I18N.md +++ b/docs/I18N.md @@ -83,6 +83,21 @@ menu.onChoose = (code) => switchLocale(code); // switched in place and stored (i `switchLocale` does what a choice in the globe picker does, and returns `'unchanged'` for the active language. `onLocaleChange` tells the application's own menu to mark the new language. +The same entry exports the translator Core's text goes through (`t`, `tn`, `msg`, `translateKnown`, `formatNumber`, `formatDate`, `formatRelativeTime`), so the application's own text follows the same language. To show its own wording for one of Core's messages, it overrides it by the catalog key, in English and in any locale it words: + +```js +import { setMessageOverrides } from '/i18n'; + +setMessageOverrides({ + en: { 'Download scene JSON': 'Download scene file' }, + de: { 'Download scene JSON': 'Szenendatei herunterladen' }, +}); +``` + +Keys are the catalogs' (`context|text` for a context, the English plural for `tn`). A `t` entry is text; a `tn` entry is `{one, other, …}` forms, chosen by the plural rules of the locale they are worded in; an entry of the other kind is ignored. An overridden message shows the application's text in the active locale, else its English: an English-only override replaces Core's translations of that message too, so word every locale that should keep its own. Each call replaces the earlier overrides and `{}` removes them. + +Call it before views render. `onLocaleChange` listeners word their text again at once, but a view already drawn keeps its text until it next renders. Import it from the `./i18n` entry only: a second copy of the module (a path alias into Core's sources) keeps its own overrides and language. + ## Rules - **Pass literals.** `t('Close')`, not `t(label)` (unless `label` holds a `msg()` value) and never a template literal with `${…}`. diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md index aa8cd05587..f8f9b48623 100644 --- a/docs/INFRASTRUCTURE-LAYERS.md +++ b/docs/INFRASTRUCTURE-LAYERS.md @@ -31,8 +31,9 @@ const layers = createInfrastructureLayers({ | `overlayHost.clearSource` | `(sourceId)`; remove that source's overlay entries | | `registerEntityContext` | `(entity, metadata)`; register selectable feature metadata, including the owning layer and data source | | `selectEntityContext` | `(entity)`; select that registered feature | -| `clearSelectedEntityContextForLayer` | `(layerId)`; clear selection only if owned by this layer | -| `removeEntityContextsForLayer` | `(layerId)`; remove records owned by the layer on destruction or failed setup | +| `clearSelectedEntityContextForLayer` | `(layerId, { evicted })`; clear selection only if owned by this layer; `evicted` when its feature left the data | +| `removeEntityContextsForLayer` | `(layerId, { retainIds })`; remove records owned by the layer on destruction or failed setup, or those a new feature set no longer has | +| `getSelectedEntityContext` | optional; `()` the selected record, so `replaceFeatures` keeps a selection the new set still has | | `governorRequestRender` | `(reason)`; request a frame through the existing render scheduler | Each returned layer supports `init(viewer)`, `enable(viewer)`, `disable(viewer)`, @@ -45,18 +46,43 @@ Callbacks must be ready before enable and remain usable through destruction. Disable retains the loaded dataset for reuse and clears selection and listeners. Concurrent enables share one load. Destroy is permanent, aborts pending fetches, -discards late results, and clears the owned data source, context records, overlays, +discards late results, and clears the owned draw sets, context records, overlays, input handler and listeners. The layer never creates an application context store, overlay host, viewer, or render scheduler. The consumer must resolve one compatible Cesium installation shared with its viewer; it must not bundle separate copies. +The layers draw, size their stems and fly the camera through the renderer's +ports. A viewer the application has bound a renderer to needs nothing more; a +Cesium viewer with no renderer bound loads +`gods-eye-view/render/cesium/unbound` once first; until then the layer reports +an error naming it, as it does for a dataset it cannot load. +A selected feature is the context record its draw item carries as `meta`; the +layer no longer sets the viewer's `selectedEntity`. +Features keep their own simplestyle `fill`, `fill-opacity`, `stroke`, +`stroke-opacity`, `stroke-width`, `marker-color` and `marker-size`, given as +hex, `rgb()` or `hsl()` colours or by the CSS colour names the default renderer +knows (it has no `rebeccapurple`, and spells `lavenderblush` `lavendar_blush`); +a `marker-symbol` is stamped on the pin as the default renderer stamped it: a +one-character string as bold upper-case text, any other value as the Maki icon +of that id from the renderer's assets, the plain pin when the icon cannot be +loaded. The assets are found as the renderer finds them from a page script: the +`CESIUM_BASE_URL` global, else the folder `Cesium.js` is loaded from; a +page bundling Cesium as modules sets `CESIUM_BASE_URL` for icon pins. Polygons with heights are drawn at them, outlined; points with +heights stand their pin on the stem's tip. Edges follow rhumb lines. + `gods-eye-view/infrastructure/geojson` exports the lower-level `createLocalGeoJsonLayer(options, services)` and existing infrastructure overlay -helpers. `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers. +helpers. Its options also take `loadFeatures({ signal })`, a loader resolving to +GeoJSON features in place of `url`, and `featureColor(properties)`, a CSS colour +per feature for its fill, stem, dot, pin and label accent. The layer it returns +also has `dropCachedFeatures()`, so the next `enable` loads again, and +`replaceFeatures(viewer, features)`, which draws a new feature set in place of +the current one: the current one stays drawn until the new one is built, and +stays if that fails (the call then rejects). `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers. Consumers use the package exports, which do not import standalone application globals. Dataset files and source/license notices remain under `src/data/local_data/`. -Their input counts are 4,352 datacenter features and 704 dam features. Cesium may -expand multipart geometries into multiple entities; entity and stem counts are -different measurements. This change does not refresh or relicense the datasets. +Their input counts are 4,352 datacenter features and 704 dam features. A multipart +geometry draws as several parts, each with its own stem; part and stem counts are +different measurements from feature counts. This change does not refresh or relicense the datasets. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 7bf6d3751c..8b33ce6244 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -32,6 +32,11 @@ hardware-rendered overlay scenes. | 3 | 558.527 ms | 1,809.592 ms | 438.8 ms | 60 / 60 FPS | 105.1 MiB | | Median | 604.849 ms | 1,855.836 ms | 439.5 ms | 60 / 60 FPS | 105.1 MiB | +These frame rates were measured when the globe was capped at 60 FPS. It now +draws at the display's refresh rate while anything moves and ticks at most 60 +times a second when parked (the Cesium frame port's idle rate, +`IDLE_FRAME_RATE` in `src/renderGovernor.js`). + The initial-settle measurement is the more useful launch reference because it includes the first visual and data settling window. All three samples reached the display ceiling during both motion and rest. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md new file mode 100644 index 0000000000..9b055c2269 --- /dev/null +++ b/docs/RENDERER-CONTRACT.md @@ -0,0 +1,746 @@ +# Renderer contract + +The renderer contract is what the application asks of a 3D renderer. The +Cesium renderer draws the application through it, and the stub renderer +stands in for it in tests. The contract is version `0`. Today the application +still drives Cesium directly; later work moves the layers onto the contract +one family at a time. + +The package exports these modules: + +| Export | What it is | +| ------------------------------------ | -------------------------------------------------------------------------------------- | +| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check | +| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests | +| `gods-eye-view/render/camera/events` | The camera port's events: `changed` per listener, `moveStart`/`moveEnd`, command hooks | +| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison | + +The pieces that do not depend on Cesium are exported too, each with its +own `.d.ts`: + +- `gods-eye-view/render/input/router`: the input port's leases and routing; +- `gods-eye-view/render/stub/camera`, `.../stub/viewRectangle` and + `.../stub/harness`: the stub's camera, its view rectangle and its + conformance harness; +- `gods-eye-view/render/motion`: where a moving icon is drawn at a time; +- `gods-eye-view/render/vectorBase`: the vector base painter; +- `gods-eye-view/render/iconSegment`: icon motion segments; +- `gods-eye-view/render/recession`: how a set that recedes shrinks and + fades its items toward the limb; +- `gods-eye-view/render/windStreamlines`: the wind field's streamlines; +- `gods-eye-view/geo/screenCluster`: screen-space clustering. + +`src/render/neutralExports.test.mjs` checks that each is declared, that its +names match what it exports, that it type-checks under strict TypeScript and +that it imports no Cesium. + +A camera controller takes the camera events from `render/camera/events` +and the geodesy it needs (`geodesicAt`, `horizonFrom` and the rest) from +`gods-eye-view/geo`, so it measures and fires exactly as the stub does. `CameraControllerFactory` +(`camera.d.ts`) types such a controller: what it is given (`NativeCamera`) +and what it gives back (the camera port and its two frame steps). + +## Ports + +A renderer is created by a `RendererPlugin` (`{ id, create(options) }`). It +exposes nine ports, each typed in its own file in `src/render/contract/`: + +| Port | File | Covers | +| --------- | -------------- | ----------------------------------------------------------------------- | +| `frame` | `frame.d.ts` | The render-on-demand loop, frame phases, continuous holds, scene time | +| `globe` | `globe.d.ts` | Base (photoreal, terrain, vector, imagery), imagery layers, split, sky | +| `draw` | `draw.d.ts` | Draw sets: icons, points, lines, shapes, models, quads, meshes, fields | +| `camera` | `camera.d.ts` | Pose, views, flights, `lookAt`, follow, user controls, events, matrices | +| `query` | `query.d.ts` | Picks, projection, rays, heights | +| `input` | `input.d.ts` | Pointer events with their pick made, leases, stock behaviours | +| `effects` | `effects.d.ts` | Screen styles, bloom, sharpen, screen modulation | +| `credits` | `credits.d.ts` | Data credits owed | +| `quality` | `quality.d.ts` | Quality knobs, device facts, frame signals | + +Version `0` is still being shaped, and not only by additions. Members +were removed or replaced (among them `camera.move`, `look`, +`rotateAround` and `zoom`, now step views placed with `setView`; +`query.sampleHeightNowMany`; `input.ctrlWheelZoom`, now the `ctrlWheel` +zoom input), `depthFailColor` and `depthFailDash` became one `depthFail` +style, and quality settings became detail only. The Cesium port and the +stub follow those changes. + +Some members and options were added to version `0` later. Each is +optional: + +- `globe.isGlobeVisible()` (capability `globeVisibility`) reads back whether + the globe surface is shown, for code that holds only the scene. +- `camera.followFrame()` (capability `followFrame`) reads the frame the eye + is placed in, as a column-major 4×4 matrix to ECEF: a follow's own frame + (east-north-up, or the orbit frame `autodetect` chose), a `lookAt` + target's east-north-up frame, or the identity. `setView` keeps that frame + while it places a world pose. A share link's follow offset is + re-expressed in it, satellites included. +- `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that + changes whenever what surface heights answer against changes (base, + terrain or photoreal route swapped, the globe shown or hidden) and never + otherwise (not on camera moves or tile loads), so the application can key cached + heights by it. `isSettled('surface')` says whether that surface has + loaded what is in view; a renderer without it answers `surface` as `base`. +- `SurfaceShading` is `hillshade`: view-lit shading of the drawn terrain's + own relief (the ellipsoid's curvature where terrain has no normals) that + only darkens, at most `strength` opacity. The Cesium port draws it as a + globe material it takes only while no one else holds the globe's + material. +- Fields: `windStreamlines` takes `alpha` (changed without a rebuild) and + `paused`; `rasterShell` replaces `detailWindow` with + `detail: {image, rectangle}`, a sharper image drawn in place of the base + one, and says how shells stack, blend and update. `FieldHandle.on('drawn')` + says once per spec or `update` that it is drawn, never while hidden. These + change `fields` itself rather than add to it, so the renderer follows + them where it lists `fields`. The Cesium adapter lists `fields` and + draws `rasterShell` and `windStreamlines`. It reads the grid's samples as + points, the first column at `rectangle.west` and the first row at + `rectangle.north`, rows running south. Over the whole globe its paths + wrap east and west; over part of it they seed inside the rectangle, + equal-area, and stop at its edges. +- `ModulationSector` gains `radius` and `floor` and says what it modulates: + icons, points and models dimmed toward `floor` outside the band, the map, + lines and shapes as they are, picks unchanged. Its pass is named + `screenModulation`. This changes `screenModulation` itself; only the stub + lists it, and the Cesium adapter does not draw it yet. +- `camera.on('changed', cb, { threshold })` measures each listener by its + own threshold under the capability `cameraChangeThreshold`; a renderer + without it fires every `changed` listener at 0.5. +- A line item's `depthFail` style, solid or dashed, draws the parts behind + the surface (the Draw tool's rubber band is dashed there too); without one + they are hidden. +- A solid line's `outline.widthPx` is the outline's whole width, half on + each side, inside the line's own width: an 8 px line with a 4 px outline + is 2 px of outline, 4 px of colour and 2 px of outline, as Cesium draws + it. The check `draw.lines.outline` pins it. +- A shape's `lit` chooses shading by the renderer's fixed light (true) or a + flat colour (false); omitted, extruded shapes are lit and the rest flat, + as before. The Cesium port lights unclamped shapes only + (clamped ones drape unlit). The `shapes-lit` scene draws both. +- `SetSpec.recede` (`RecedeSpec`, for icon and model sets) makes a set's + items shrink and fade toward the globe's limb, replacing the icon item's + own `recede` flag. Its parameters (each optional: where receding starts + as a share of the limb's distance, the scale and haze reached at the + limb, the least focus × haze draws with, and the eye heights over which + it all eases off for a view of the whole globe) and the maths are + `render/recession`'s, so the renderer draws exactly those factors: an icon + draws at its scale times the scale factor, and an icon or model at its + alpha times `max(combinedAlphaFloor, focus × haze)`. `ModelItem.focus` + dims a model as `IconItem.focus` dims an icon. It changes live + (`setOptions`). The Cesium port draws a receding icon set on the GPU, + the factors worked out in its shader, and fades a receding model set's + models each frame before the scene draws, writing a model's colour again + once its focus and haze move by more than 0.005. The check + `draw.sets.recede` makes and changes both kinds, and + `draw.sets.recede.models` reads a receding model's pixels: at focus 0.25 + it draws faded, and a `combinedAlphaFloor` of 1, set live, brings it back. +- `SetSpec.drawOrder` stacks sets drawn over depth: a higher one draws over + a lower one and is picked first; equal ones keep the order they were + made in. The Cesium port stacks opaque icons and points by it; + translucent ones blend order-independently there. +- A rectangle shape's `rotation` (radians counter-clockwise) turns it about + its centre in longitude and latitude, as a KML ground overlay turns, and + its image fill turns with it. The Cesium port drapes image fills too, each + on a ground primitive of its own. +- `camera.controls.keepEarthFramed` (capability `keepEarthFramed`) stops + the user's outward zooms at a whole-Earth view (about 40,000 km, or + higher where a camera command left the eye) and, from high up, turns the + view down toward the globe so the whole Earth stays in frame; camera + commands are not held to it and end its turn. The Cesium port eases the + view until the Earth's limb is 8° below its centre line above 300 km + (`zoomOutGuard.js`). The application turns it on where a renderer has it. +- `query.occlusionTest()` (capability `occlusionTest`) tests many points + against the depth of the frames drawn without waiting for the GPU; the + detection overlay leaves out the street vehicles it finds hidden. The + Cesium port builds its test with `gods-eye-view/render/occlusion` + (`createDepthOcclusionTest`, given a `DepthSource`: depth packed into + RGBA8 or a depth texture, standard or logarithmic, with the view it was + drawn from). +- `RendererPlugin.applicationHooks(renderer)` hands the application what + lies beside the contract (`ApplicationHooks`); see + [The application and its renderer](#the-application-and-its-renderer). +- `frame.renderNow()` throws when the frame fails to draw. With + `{ifDue: true}` it runs one tick of the loop now, as the loop's own would + (camera flight, input, clock), and draws only a frame that is due. + +The Cesium port lists `gpuTiming` where its context has +`EXT_disjoint_timer_query_webgl2`: while anyone listens to frame signals, +each drawn frame is timed on the GPU from `preRender` to `postRender`, and a +signal carries `gpuMs` of the newest frame whose timing has come back (a +frame or more late; a disjoint timing is dropped). Without the extension it +answers `gpuTiming: 'none'` and lists no capability. The check +`quality.signals.gpuTiming` pins both. + +The Cesium port lists `modelAtmosphere`: Cesium scatters drawn models +through the atmosphere in the same stage as its distance fog, so models take +it while `globe.sky`'s `fog` is on. + +`weather` adds `globe.weather`: clouds, fog, haze, rain and snow drawn +around the view, each a strength from 0 to 1, with the wind they drift on. +`src/render/weather.js` (exported as `./render/weather`) keeps and clamps +them (`mergeWeather`), and `./weather/effects` +turns a weather observation into strengths (`deriveWeatherEffectProfile`). +The application sets none, and the Cesium port does not list it. The strengths say what +is observed (`clouds` is the fraction of the sky covered), not how it is +drawn: the renderer draws clouds, fog and haze its own way, with clouds +placed by scene time and the wind, and shading the ground under them where +the sun lights it. The checks `globe.weather`, `globe.weather.drawn` and +`globe.weather.sceneTime` (pixel checks) pin it. + +How the sky, atmosphere, haze, lighting and the frame's tone mapping and +exposure look is the renderer's own: `globe.sky` switches parts on and +off, and no check compares colours. With +`atmosphere`, `fog` and `lighting` off and clear weather a renderer applies +none of its look, so the checks that read an exact colour (`bareSky` in +`checks/ports.js`) set that sky first. The +reference images under `src/render/conformance/goldens/visual/` are the +Cesium renderer's own, for checking it against itself. + +The Cesium port lists `followAutodetect`: an `autodetect` follow is +Cesium's own AUTODETECT tracking frame, east-north-up on a still or slow +target and an orbit frame (x along the inertial motion, z up) on a fast +one. The stub's is a frame along the ground track, so an autodetect +`viewFrom` reads differently on each; the check `camera.follow.autodetect` +pins what both share (the range kept, north-up when still, the frame on the +target standing up). + +A follow target's `transitionS` makes the first framing a move instead of a +jump: from its first frame the eye is in the target's frame, and over +`transitionS` seconds of wall time it goes from where it stood to +`viewFrom`, by the one rule in `src/render/camera/followTransition.js` +(its offset and its view each turned and eased with smoothstep, the view +ending on the target with no roll). The Cesium port, the stub and a camera +controller import that rule rather than restating it. The tracked aircraft +and followed trains use it with a `viewFrom` taken from the camera +at the click: the eye's own view direction at its own range from the target, +so neither changes and only the eye's place moves, sliding the target to the +centre. The check `camera.follow.transition` pins it. + +The Cesium port draws clamped shapes of every kind. A clamped outline is a +draped line (a ground polyline a ring, under the shape's pick id; an outlined +clamped shape is rebuilt on any change; a pulsing one pulses through its line's +material, as an image fill pulses through its image material's colour). What +a ground primitive cannot drape stands on the surface unclamped, the surface +read when the set is built: an extruded shape from the lowest surface height +under it up to its `extrudeHeight`, a wall with its foot on the surface under +each position and its heights above it, and an image fill where the scene +cannot drape materials (no depth textures). The check `draw.shapes.clamped` +draws each. + +The Cesium port takes every kind of `ImageRef` wherever an image is drawn +(icons on billboards and on the GPU, line patterns, shape fills, quads and +raster shells): a URL, SVG, a blob (by an object URL made once per blob, +revoked once the blob itself has been collected; a material drawing a blob, +a quad's among them, holds it while it lives, since a material loads its image +on its first draw, even after the atlas slot it came from has a new one; a +quad given another source lets the old blob go with its old material, once the +frame has drawn), a +keyed canvas, and an atlas slot as the image it holds (an icon waits for an +unregistered slot; anything else refuses it). The check `draw.icons.images` +draws each kind on still icons and in a set that recedes. + +Icon sets with `cluster` (`ClusterSpec`) cluster the same way on every +renderer: `clusterScreenPoints` (`src/geo/screenCluster.js`) over the shown +icons in front of the eye and above the horizon, in the set's order, boxed at +their drawn size, the last pass's clusters kept. A cluster draws one icon at +the mean of its members' positions in place of its members (`icon(count)`, +else a default badge with the count, at the seed's size). A pick on it +answers one hit a member, seed first, each with the member's own `set`, `id` +and `meta` and the cluster's position, so `pick` gives the seed and +`drillPick` every member. Clusters are made again in the frames drawn after +the camera moves or the set changes, never on a timer. The Cesium port draws +a set's cluster icons in a billboard collection of their own and hides the +members' billboards. A set on the GPU (`columns`, a set that recedes, or moving, +proxy-picked or level-of-detail icons) clusters its rows where their segments +(and ground) put them at the frame's motion-clock time, hiding the members' +rows; while rows still move it clusters again every frame. The checks +`draw.icons.cluster` and `draw.motion.cluster` (members coming to rest on +their segments) draw a cluster, pick it, and part it by moving in. + +Icon sets on the Cesium GPU path draw what its billboards draw: pixel offsets, `bottom` and `top` anchors, screen and axis +rotations (turned as Cesium's billboards turn), `fadeByDistance`, +`displayRange`, and `clampGround` / `relativeGround` heights. Each row reads +these from a float texture by instance, so the 16 vertex attributes hold; +WebGL 1 has no such fetch and refuses them. A clamped row stands on the +ground taken between the heights under its segment's two ends, sampled after +a frame draws, 256 ends a frame across the port's sets: loaded terrain first, +then (but for `clampTo: 'terrain'`) the drawn surface, eight a frame. They are +sampled again when the globe's tiles finish loading and, clamped to more than +terrain, every 5 s. The check `draw.motion.look` draws each on a moving icon. + +A set's `blend` holds for every kind of set: omitted, opaque parts draw +opaque with depth writes and translucent ones blend without; `opaque` draws +every item opaque, its alpha ignored, with depth writes; `translucent` blends +every item without depth writes, even at alpha 1; `additive` adds each item's +colour times its alpha, without depth writes and still depth-tested. It +changes live (`setOptions`, from the next frame; models do not load again). +The Cesium port builds billboards and points in Cesium's blend options, and +turns every set's draw commands to its blend each frame before the scene +sorts them (`src/render/cesium/setBlend.js`): additive ones draw after every +opaque command and before the translucent pass, which blends +order-independently and would undo the addition; ground commands keep their +pass and stencil and only blend differently. The checks `draw.sets.blend` +(points, icons, lines, shapes) and `draw.models.blend` read the pixels. + +A model item may bring its glTF bytes (`gltf`): the renderer builds it from +them and never fetches its `url`, which stays the model's identity, so a +model set loaded up front (the procedural fleet models, GLBs compressed with +`EXT_meshopt_compression` and `KHR_mesh_quantization`) is never fetched +mid-session. `axisScale` stretches a model along its own glTF axes on top of +`scale` (a hull drawn at its reported beam), `maskColor` paints a colour +where the model's `_TINT` vertex attribute marks it (a vehicle in its route's +colour), and `clip: 'belowOrigin'` draws only what is above the horizontal +plane through its position (a hull above its waterline). Each changes live. +The Cesium port passes the bytes as the model's `gltf` with its url as the +base path, scales its model matrix along the axes Cesium's glTF axis +correction turns them to, paints the mask in a custom shader per colour +(unlit under `unlit` shading, left out under `thermal`), and clips with a +clipping plane through the model's origin. The checks `draw.models.bytes` +and `draw.models.fleet` cover them. + +The Cesium port draws timed imagery (`imageryFrames`): a layer given a timed +source hides its own imagery and draws each frame its clock shows as a Cesium +imagery layer just above it (in `blend` mode the later frame over the earlier +at its share of the way, as a layer's `alpha` blends), with the next +`prefetch` frames (1 by default) loading unseen at alpha 0. A video source is +seen every 250 ms of each segment (at most 1,200 times a segment), each tile +the video its URL names for it (or one video over the layer's rectangle for a +`single-image` layer), seeked to the time's share of its length. A layer +keeps its 48 most recently seen tile videos; a tile waiting on one it lets +go, or on a seek that takes over 10 s (60 s for the seek past its end that +learns the length of a video that does not state it), fails rather than +waiting. A video whose seek did not end is let go, so the next tile loads a +fresh one; one that failed to load (or to say how long it is) fails its tiles +at once for 3 minutes, then loads again. `frameReady` +names the nearest frame's time once every globe tile drawn shows that +frame's own imagery (`src/render/cesium/imageryFrames.js`). The checks +`globe.imagery.frames` and `globe.imagery.video` cover both. + +Every Cesium draw set takes `setColumns` (`columns`): icon sets on the GPU, +any other as the rows the columns make over the items it holds, each row the +item of that id with the columns' fields over it, replacing every item as +`set` does (`columnRows` in `src/render/cesium/draw.js`, as the stub does). +`renderer.shape` holds on Cesium. + +The Cesium port also draws `pattern` line styles (the image repeated +`repeat` times along the line, in the translucent pass; draped too), lines in the +`inertial` frame (turned each frame by the set's motion clock, a depth-fail +style included; never batched; a draped one is draped where the sky is, +turned into the fixed frame, and draped again each second of its clock), +segment colours and shows +on lines of every mode and style (a draped solid line as ground instances, +any other as a primitive a segment with a material of its own, recoloured +and shown in place; an arrow's head on its last segment, a pattern keeping +its image; the check `draw.lines.segmentStyles`), and image fills on clamped ellipses, cut finely so a +round image (the launch pad zone's rim) runs round. A clamped colour fill +whose geometry alone changes (an annotation's target ring, resized as the +camera climbs) is drawn alone where it now is, in the same frame. A hidden +line that cannot settle into a static batch leaves its polyline collection +until it shows again, since the collection draws every line it holds. + +The renderer itself (`renderer.d.ts`) adds capture, pixel reads, settling, +resize, context loss and `destroy`. `common.d.ts` holds the shared shapes +(ECEF positions, colours, listener semantics) and the capability list. + +The rules that hold everywhere: + +- **The application keeps its own records.** It never reads a renderer to learn its own + state, only what the renderer measures: picks, depth, heights and + readiness. +- **Capabilities.** An optional member (`?`) exists only with the capability + its documentation names first. A required member that names a capability + always exists, and without the capability it answers null or empty. + Quality support is listed by `quality.knobs()`, not by capabilities. +- **Picks see the scene before effects.** A style that moves pixels does not + move what is picked, so the application maps a pointer through its own + style first + (`src/input/sensorPick.js`). A bounded `drillPick` (`limit`) also bounds + its work: it looks through at most `max(limit, 16)` things under the + pointer. +- **Heights are physical.** All heights are metres above the ellipsoid, + unexaggerated. Only drawing follows exaggerated terrain. +- **Listeners** run in subscription order. A listener removed during + delivery does not run; one added during delivery runs from the next event. + A listener that throws is reported to the renderer's `error` event, or to + the platform's `reportError` when nothing listens for errors. The other + listeners, and the frame, still run. +- **The frame order is fixed:** camera flight → input → camera `changed` → + follow → `preUpdate` → move detection → `preRender` → render → + `postRender`, the default renderer's own. A camera move made by follow or + in `preUpdate` is reported by `changed` on the next frame. +- **Destroy ends everything.** After `destroy()`, every handle does + nothing: a set's or field's methods neither draw nor throw, and a set or + field asked for afterwards is such a handle. The same holds for one handle + after its own `dispose()`. `frame.renderOnce()` and `capture()` reject + with a "renderer destroyed" error, and a `renderOnce` still waiting at + destroy rejects rather than hang. +- **Results are read-only.** `camera.matrices()` and `followFrame()` may + hand the same arrays again while they hold, and hand new ones once they + change, so one kept from an earlier frame stays as it was. +- **Reading the frame.** `capture()` and `readPixels()` read the last + presented frame; neither draws one of its own when the frame is kept. + Whether to keep the drawing buffer is the renderer's own business, not a + creation option. The creation options a renderer takes are `msaa`, `sky` + and `time`, set before the first frame, and `clock`, which its frame + ticks, the camera's `moveEnd` wait, its input and its flights read, and + its inertia where the renderer times that itself: on Cesium, inertia + keeps Cesium's own timing. +- **Leases:** a tool takes the pointer with `claimPointer`. With `grab`, it + takes only the presses it grabs on `down`; the rest, and wheel and pinch, + stay with the camera and everyone else. The newest claim takes over: it + ends the previous lease, whose `onLost` is called once, after the new lease + holds the pointer, so that tool turns itself off. A lease its holder + releases is never told, and an ended lease's release frees nothing. + The application's own tools (Draw, the imagery box, Directions) claim through + `src/data/inputOwnership.js`, which the input dispatcher bridges onto the + port, so a claim on either takes over from the other. The bridge's lease + grabs no press: the dispatcher decides who hears each event when it + arrives, and the renderer's stock select and double-click follow run + unless a tool holds them off. + +`src/render/contract/index.js` lists every member of every port in `PORTS`, +along with `CAPABILITIES`, `FRAME_STEPS` and `QUALITY_KEYS`. +`checkRendererShape(renderer)` names each required member that is missing, +and each capability member present without its capability. +`contract.test.mjs` type-checks the contract under strict TypeScript, and +fails when `PORTS` and the types disagree on a single member. + +### The vector base painter + +`vectorBase` (`BaseSpec.vector = { styleUrl }`) draws a MapLibre style +document's vector tiles as the globe's base. They are painted in shared, +Cesium-free code, `src/render/vectorBase/`, which the renderer draws as +imagery: + +- `loadVectorStyle(styleUrl, fetch)` fetches the style and the TileJSON its + vector sources name (a source's `url`; inline `tiles` are used as given, + resolved against the style), compiles every layer, and returns the + sources (tile templates, `minzoom`, `maxzoom`, `xyz` or `tms`), the layers + it draws, the background, the sources' attributions, and `skipped`: each + layer it does not draw, with why. +- `paintVectorTile(style, z, x, y, { size, fetch, signal, canvas })` paints + one Web Mercator tile on a canvas at style zoom `z + log2(size / 512)` (at + least 0). A source past its `maxzoom` is drawn from its deepest tile, + overzoomed; below its `minzoom` it draws nothing. Decoded source tiles + (gzipped ones inflated) are kept per style, the last 128. + +What it draws of the style specification: + +- Layers: `background` (`background-color`, `background-opacity`); `fill` + (`fill-color`, `fill-opacity`, `fill-outline-color`); `line` + (`line-color`, `line-width`, `line-opacity`, `line-dasharray`, + `line-cap`, `line-join`, and `line-gap-width` drawn as one line the full + cased width); `circle` (`circle-radius`, `circle-color`, + `circle-opacity`, `circle-stroke-width`, `circle-stroke-color`, + `circle-stroke-opacity`); `symbol` text only (`text-field` as an + expression or with `{name}` tokens, `text-size`, `text-font` as the + system's sans-serif or serif in bold or italic as its name says, + `text-color`, `text-opacity`, `text-halo-color`, `text-halo-width`, + `text-transform`, `text-anchor`, `text-offset`, `text-max-width`). + Layer `minzoom`, `maxzoom`, `filter` and `visibility` hold. +- Labels are painted into the tiles: top layer first (within a layer, its + features in their order in the tile), each clear of those placed before + it and wholly inside its tile (one across a tile edge is + left out). A point labels at itself, a line halfway along it (level, not + along the line), a polygon at its outer ring's bounding-box centre. +- Filters in both syntaxes (legacy, with `$type` and `$id`, and + expressions). Legacy `{stops, base, property, type}` functions + (exponential, interval, categorical, identity; not zoom-and-property); + one without a `type` is exponential on a property that interpolates (a + number or colour) and interval on any other (`line-cap`, `line-join`, + `text-font`, `text-transform`, `text-anchor`, ...), as the specification + says. `has`, `get` and legacy filters see a feature's own properties only. +- Expressions: `literal`, `get`, `has`, `id`, `geometry-type`, `zoom`, + `properties`, `!`, `all`, `any`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, + `case`, `match`, `coalesce`, `step`, `interpolate` (`linear` and + `exponential`; `-hcl` and `-lab` blend in RGB), `to-string`, + `to-number`, `to-boolean`, `to-color`, `number`, `string`, `boolean`, + `rgb`, `rgba`, `concat`, `format` (its text), `upcase`, `downcase`, + `length`, `at`, and arithmetic (`+ - * / % ^`, `min`, `max`, `abs`, + `floor`, `ceil`, `round`, `sqrt`, `ln`, `log10`, `log2`). +- Skipped whole: `fill-extrusion`, `raster`, `hillshade`, `heatmap` and + `sky` layers; layers on raster sources; layers setting a pattern + (`fill-pattern`, `line-pattern`, `background-pattern`), `line-offset`, + `line-gradient` or a translation; layers whose values use an expression + not listed (or are malformed). As MapLibre does, a paint or layout value + that cannot be evaluated for a feature (a type that does not fit, a + `step` or `interpolate` over what is not a number) or is not of the + property's kind (null; not a finite number, a string included, where a + number is needed; not a colour `parseColor` reads, which takes the CSS + colour names; not one of the property's keywords) is the property's + default; a legacy function's miss is its `default`, else the property's. + A feature whose filter cannot be evaluated is left out. Nothing + unsupported throws. +- Ignored: icons (`icon-image`, sprites: a symbol layer draws its text + alone), text along lines (drawn level), `glyphs` (system fonts), and any + other paint or layout property not listed above. + +The Cesium port loads the style before the base changes (a style that fails +leaves the base as it was; a later `setBase`, or disposal, aborts the load and +the overtaken call changes nothing, resolving with `imagery: []` and +`settled: false`; `settled` is whether, when the call resolves, its base is +still the one drawn and has settled, so an earlier call that resolves while a +later call's style is still loading, or after that style fails, is settled, +and one that resolves after a later call changed the base is not), draws it as Web Mercator imagery under the +base's other imagery (`src/render/cesium/vectorBase.js`, 256 px tiles to +level 20, transparent where the style paints no opaque background; a tile +whose request is cancelled, its layer removed, is not painted), and credits each source's attribution as plain text. The stub +loads the style and paints nothing. The check `globe.base.vector` serves a +style and a tile from data URLs and reads the drawn fill. + +### What a renderer does, by role + +A renderer is more than a drawing surface: it is a whole globe engine. The +application keeps the data (providers, records, layers and their +behaviour). The renderer owns everything from a source spec or a draw set +down to the pixels. The ports follow the API's shape; `ROLES` in +`src/render/contract/index.js` names what the engine behind them does, and +puts every member of `PORTS` in exactly one role. It changes no member. + +| Role | What it does | Members | +| --------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `surface` | Streams, decodes and builds the globe from map sources: imagery, terrain, photoreal 3D tiles, draped layers | `globe`, `imageryLayer`, `credits` | +| `scene` | Draws the application's data as keyed, retained sets | `draw`, `drawSet` | +| `view` | Places and moves the camera, hands pointer input to the application | `camera`, `flight`, `input`, `lease` | +| `queries` | Picks, surface positions and heights, rays, projection, occlusion | `query` | +| `look` | Sky and atmosphere, surface shading, per-layer lighting, styles and screen effects | `effects`, `globe.sky`, `globe.weather`, `globe.setSurfaceShading`, `imageryLayer.lit` | +| `host` | Canvas and life cycle, the frame loop and scene time, quality, capture, settling | `renderer`, `frame`, `quality` | + +An entry is a port or a `port.member` prefix; the most specific one wins, so +`roleOf('globe', 'sky.set')` is `'look'` while `roleOf('globe', 'setBase')` +is `'surface'`. `contract.test.mjs` fails when a member has no role, when +two roles claim the same entry, or when an entry names no member. + +## Moving code onto the contract + +Two ratchet tests keep code that has moved onto the contract from drifting +back to Cesium. Both lists only ever shrink. + +- `src/render/cesiumAllowList.json` lists the files outside the Cesium + adapter (`src/render/cesium/`) that may still import or be handed Cesium + (`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list + when it no longer drives Cesium at all; nothing is added. The list is + empty: no file outside the adapter reaches Cesium. Two files name + the adapter by design and are not on it: the application scene + (`src/app/scene.js`), the composition root that picks the default renderer + when it is given none, may import `src/render/cesium/application.js` (only + then, so a page on the stub never loads Cesium) and nothing else of + the adapter; the conformance page (`dev/conformance/main.js`) may import the + adapter's harness and scene renderer. The test names both + (`ADAPTER_ENTRIES`), and that list is never grown. +- `src/render/viewerAccessAllowList.json` counts, per file off that list, + the Cesium-shaped accesses through the viewer it still makes (none: the + list is empty, so no file may make one) + (`src/render/viewerAccess.test.mjs`): the viewer's `entities`, + `dataSources`, `scene`, `camera`, `clock`, `imageryLayers`, + `terrainProvider`, `trackedEntity` and `canvas`, and the scene's + `primitives`, `pick`, `drillPick`, `pickPosition`, `globe`, `preRender`, + `postRender`, `preUpdate`, `postUpdate`, `canvas`, `requestRender` and + `camera`, written plainly, with `?.`, in brackets or destructured. + `viewer.container` is a DOM element and does not count; reach the canvas + through `canvasOf(viewer)`. Comments and tests do not count. + `src/testSupport/viewerAccess.mjs` is the matcher. + A file may not make more accesses than recorded (a file not listed may + make none), and a count higher than the file now needs fails too. So a + file that leaves the Cesium list must port its viewer accesses in the + same change: it cannot be added to the count. After + porting accesses away, run `node scripts/viewer-access-baseline.mjs` (or + `--check` to see what it would change): it lowers counts and drops + entries, and never adds or raises one. + +## The application and its renderer + +The application runs on a renderer with only the contract's required +members (the stub proves it below); nothing outside `src/render//` asks which renderer it runs +on (no `renderer.id`, no engine type, no engine object's presence). + +- **The scene object.** `createApplicationScene` (`src/app/scene.js`) takes a + `RendererPlugin`, or a promise of one (default: Cesium, imported only then; + `loadDefaultRenderer` starts that import as the standalone page starts), + creates the renderer in the page's container, and hands every layer and + tool the application's own scene object (`createSceneHost` in + `src/render/rendererOf.js`): the container and `isDestroyed()`, bound to + the renderer. Code reaches the renderer's + ports through it (`findCamera`, `drawOf`, `canvasOf`...). +- **What only the Cesium renderer needs at startup** is done in its + plugin's `create`: the free-look height limit and keyboard access to its + credits' expand link (`src/render/cesium/appRenderer.js`). +- **What a plugin may hand the application beside the contract** is its + `applicationHooks(renderer)` (`ApplicationHooks`, + `src/render/contract/renderer.d.ts`), asked once as the scene creates the + renderer and recorded for the application (`src/render/applicationHooks.js`): + a map engine of its own, stale command trimming, whether an entity is its + own, whether it shows its credits in a display of its own + (`ownCreditDisplay`; otherwise the application's own line, + `src/ui/creditsView.js`, shows the credits port's list), and what QA + scripts read from `window.__godsEyeView` (Cesium's viewer there, for the + scripts that drive it). Each is optional, none is a contract member, and + a renderer without them runs the application without that behaviour. +- **What the renderer should do is in the ports**, each through the + application's own code: outward zooms stop at a whole-Earth view that + stays framed (`camera.controls.keepEarthFramed`, which the scene turns + on; Cesium's is `src/render/cesium/zoomOutGuard.js`); the detection + overlay leaves out street vehicles something stands in front of through + `query.occlusionTest()` under the `occlusionTest` capability (the GPU + probe is `src/render/occlusion/depthProbe.js`, which Cesium's + `src/render/cesium/sceneOcclusionProbe.js` feeds; without it every such + vehicle's bracket shows); and an inline panel whose host stops animation + frames keeps running through `resize` and `frame.renderNow({ifDue: true})` + (`src/app/panelRendering.js`), so flights, input and the clock go on as + in the renderer's own loop, stopping at a frame that throws. +- **The map stacks** switch through the renderer's own map engine when its + plugin hands one, else through its globe port (`src/maps/globeEngine.js`); + see `docs/CURRENT-STATE.md` § Map source factories and coordination. +- **The proof.** `npm run qa:stub-boot` (`scripts/qa-stub-boot.mjs`) serves + the application's page with `dev/stub-app/main.js` as its entry: the whole + application on the stub with no capability at all. It fails when the page + requests any Cesium module or asset, when the credits line is not shown + with its data credits, on a page or console error, or when a + data layer (flights, military aircraft, transit, traffic, CCTV, vessels, + weather, wind, satellites, FIRMS, wildlife, shipwrecks, news) fails to + turn on or off; `--strict` also fails + a layer that draws nothing on the stub (it needs the live feeds). + `src/app/scene.test.mjs` runs the scene itself on the stub in Node. + +## The stub renderer + +`createStubRenderer({ capabilities, viewport, time, container })` implements +every port in memory and draws nothing. Given a `container` (in a page), its +canvas is a real canvas filling it, which `resize()` follows; otherwise a +stand-in that takes event listeners. `createStubRendererPlugin(options, +onCreate)` is the stub as a `RendererPlugin`. It has: + +- the default camera's exact maths: views, `lookAt`, flights with their + height arc and easing, `changed` thresholds and follows; +- picks against what was drawn, or a scripted table; +- scripted heights; +- a virtual clock that nothing advances on its own; +- models that load at once, but for urls under `stub-fail:` + (`STUB_FAILING_MODEL_SCHEME`), which fire `loadFailed` instead of `ready` + (they are still picked where they are). + +`renderer.testing` drives it with `tick()`, `advance(ms)`, `pointer(type, x, y)`, +`scriptPicks`, `setHeights` and `cacheHeight`, and records its calls. +`testing.drawnPosition({ set, id }, aheadMs)` is where it draws an item now +(or `aheadMs` from now), so a +camera controller over the stub can follow drawn items there. +A listener that throws with nothing subscribed to `error` goes to +`reportError`; Node has none, so the stub rethrows it on a microtask and +`node:test` fails the running test. A test that expects a throw subscribes +to `error`. +The stub passes the whole conformance suite (`src/render/stub/stub.test.mjs`). + +## Conformance suite + +`runConformance(harness)` runs every check against the Cesium renderer or +the stub through the contract alone and reports each one as passed, failed or skipped. It runs in +Node and in a browser page. A harness tells the suite how to drive the +renderer under test: + +- `create({ viewport, capabilities })`; +- `frame(r)`: one frame, 1/60 s on a virtual clock; +- `now(r)` and `toEcef(p)`; +- `tolerance` and `flightPaths`. + +Optional members widen what is checked: `pointer` for synthetic input, +`cameraInput` (the camera answers that input: the drag and wheel traces +run), `scriptHeights`, `resizeContainer` (sizes the element the renderer +fills, for the `resize` check, which skips without it), `assets.model`, and +`assets.missingModel` (a model url that fails to load, for the `loadFailed` +check). `pixels: false` says +the renderer draws nothing but models into its pixels, as the stub: the +checks that read drawn icons, lines and fields then skip. Without it they +run, and the renderer fails them if it draws nothing there. + +There are two layers of checks. + +**Logic checks** run in CI. They cover: + +- the shape check; +- listener semantics and the frame loop; +- draw-set bookkeeping, picks and the `meta` round-trip; +- projection, rays and heights; +- leases and click picks; +- imagery order, sky, styles, credits and quality knobs; +- the camera traces. + +**Camera traces.** `cameraScripts.js` lists camera scripts in the contract's +terms. `scripts/record-camera-goldens.mjs` runs them on Cesium's own +`Camera`, headless, on a virtual clock, and writes +`src/render/conformance/goldens/camera.json`. A renderer under test must +match each recorded pose: + +- within 1 mm in position, 1e-9 in unit vectors and angles, and 1e-3 px on + screen; +- with every flight ending within one frame of the recording. + +Some scripts move the camera by user input: left, middle, Shift and Ctrl +drags, and wheels in pixel and line mode. The recorder runs those on +Cesium's own `ScreenSpaceCameraController`, fed the DOM events the script +describes, with `Date` on the virtual clock too (its coasting reads it). A +renderer under test gets them through its harness's `pointer`, a wheel as +the input port's lines. Only a harness with `cameraInput` runs them: the +stub's camera takes no gestures, so it skips them; a camera controller +over the stub would run them. `cameraPort.test.mjs` runs them on Cesium's +controls under the Cesium camera port, each wheel sent back as lines. + +A wheel's `delta` is lines as Cesium counts them: a pixel-mode wheel at +40 px a line and a page at 3 lines (`src/render/input/wheel.js`). Turning +lines back into pixels at 40 px a line gives Cesium's own wheel in every +mode, so a controller that does that zooms as Cesium does in Chrome (pixel +mode) and Firefox (line mode) alike. + +`src/render/cesium/cameraGoldens.test.mjs` fails when the installed Cesium +no longer records the committed traces. After a Cesium upgrade or a script +change, run `node scripts/record-camera-goldens.mjs` and review the diff. + +**Visual checks** run in the browser. The reference scenes +(`src/render/conformance/scenes.js`) are built from contract calls only: + +- one scene per primitive family; +- a city scene; +- a calibration path from orbit down to the street. + +The scenes load nothing from the network. + +`npm run dev`, then open `/dev/conformance/`. The page can: + +- **Run logic suite (stub)** runs the logic checks in the browser. +- **Record references** draws every scene the chosen renderer supports. + It saves each view to `src/render/conformance/goldens/visual/`, through a + dev-server-only endpoint. +- **Check scenes** draws the scenes again and compares each capture with its + reference. Pixels are compared as pixelmatch compares them: by YIQ + difference (threshold 0.1), with antialiasing in either image excused. A + capture matches when at most 250 pixels are unexcused and at most 2 are + solid (a differing pixel whose four neighbours differ too). Between them + the two catch a dropped 4 px point, a dropped 2 px line and a 1 px shift + of the view, and pass any MSAA setting. A change nowhere 3 px thick (a + thin line gone, an item moved a pixel or two) that covers at most 250 px + passes. `visual.js` has the measurements. + The page shows the capture, the reference and the difference side by side. + +`window.conformance.runScenes()` and `runLogic()` do the same from a script. + +`npm run qa:conformance` runs the logic checks on the Cesium renderer in +headless Chromium (software WebGL, no GPU needed). It starts its own Vite +server unless given `--url`; `--only id,id` runs just those checks and +`--json path` writes the report. It fails on any failed check and on any +skip it does not expect (`query.heights`, which needs scripted heights, is +the one it expects). CI runs it in the `street-level-browser` job. +Browser checks use the chrome-devtools MCP against a page in its own window. + +The Cesium scene renderer (`src/render/cesium/sceneRenderer.js`) draws +every scene (icons, points, lines, shapes, models, quads, meshes, fields +and the city), and the references were recorded with it, on a GPU: a +software rasterizer such as SwiftShader draws the glow line differently. +It has only the members the scenes need. + +Some behaviour is only drawn, so the logic checks cannot see it: course +easing (`courseGlide`), and a hidden row keeping its eased +course. The stub keeps no drawn course. These wait for scenes that capture +an icon mid-turn. Height queries that count a set +(`includeInHeightQueries`) are not checked either: the stub's heights are +scripted, so it does not model them. Nor are video frames (a check needs a +video) or `fetchTile` (the stub fetches nothing). diff --git a/docs/SHARE-LINK-FORMAT.md b/docs/SHARE-LINK-FORMAT.md index 4c3254a99a..3b76eb04e1 100644 --- a/docs/SHARE-LINK-FORMAT.md +++ b/docs/SHARE-LINK-FORMAT.md @@ -148,6 +148,7 @@ probability of about 255 in 256 (many of them already fail as base64url). | 27 | `styleParams` | LEN | style | packed `(token, value × 100)` pairs | | 28 | `worldTime` | epoch | none (live) | zigzag seconds since 2026-01-01T00:00:00Z | | 29 | `library` | LEN | none | Data Library ledger tokens, two base-36 characters each, concatenated | +| 30 | `scopeOpacityPct` | uint | 100 | 0–100, how strongly the scope mask shows | Field 1 absent means `thing` when field 13 is present and `place` otherwise, so v1 never writes it; a later view kind writes its code. @@ -170,6 +171,10 @@ tokens in `src/library/ledger.json` (the long form's `lib=ab.cd`). A share without it switches no library entry on; the recipient's added entries stay in their panel, off. Tokens this build does not know are skipped. +Field 30 is how strongly the scope mask shows, from the Visual panel's +Opacity slider (the long form's `sco`). It is written only below 100, so a +link made before it, which opens at full opacity, keeps its code. + Flag bits (field 9): 0 `bloom`, 1 `sharpen`, 2 `hudVisible`, 3 `celestialRing` (each defaulting by style), 4 `scopeEnabled` (default on). diff --git a/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index 3dcd7f63ba..91a9d42288 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -153,9 +153,9 @@ a feature supplying only its accent. `t()`, which follows the locale as the view renders; the views carry no `data-i18n*` markers, which `npm run i18n` rejects in a template. Shared builders become components first and keep their imperative entry points until their owners are components: - the rail cards, card blocks and timeline (`src/ui/rail/`) render through - Vue's synchronous `render()` behind `createRailCards()`, - `createRailCardBlocks()` and `createRailTimeline()`. Order: Scenes (done: `SceneOptions` and + the rail cards and card blocks (`src/ui/rail/`) render through + Vue's synchronous `render()` behind `createRailCards()` and + `createRailCardBlocks()`. Order: Scenes (done: `SceneOptions` and `SceneShotList` over the `gev-scenes` store; the panel's buttons, status line, progress bar and the runtime chip render the panel SceneControls presents there, and the buttons and file chooser call its actions), Weather (done: the owner diff --git a/docs/media/01-style-sweep.gif b/docs/media/01-style-sweep.gif deleted file mode 100644 index e568e3e856..0000000000 Binary files a/docs/media/01-style-sweep.gif and /dev/null differ diff --git a/docs/media/01-voice-annotate-zilker.gif b/docs/media/01-voice-annotate-zilker.gif deleted file mode 100644 index c5a5b71c52..0000000000 Binary files a/docs/media/01-voice-annotate-zilker.gif and /dev/null differ diff --git a/docs/media/03-austin-cctv.gif b/docs/media/03-austin-cctv.gif deleted file mode 100644 index 942cb8f155..0000000000 Binary files a/docs/media/03-austin-cctv.gif and /dev/null differ diff --git a/docs/media/04-airport-distance.gif b/docs/media/04-airport-distance.gif deleted file mode 100644 index 3e0579af55..0000000000 Binary files a/docs/media/04-airport-distance.gif and /dev/null differ diff --git a/docs/media/05-traffic-to-cctv.gif b/docs/media/05-traffic-to-cctv.gif deleted file mode 100644 index 86c4768543..0000000000 Binary files a/docs/media/05-traffic-to-cctv.gif and /dev/null differ diff --git a/docs/media/06-cockpit-ar.gif b/docs/media/06-cockpit-ar.gif deleted file mode 100644 index ace7354837..0000000000 Binary files a/docs/media/06-cockpit-ar.gif and /dev/null differ diff --git a/docs/media/07-helicopter-loops.gif b/docs/media/07-helicopter-loops.gif deleted file mode 100644 index e9c8646c8b..0000000000 Binary files a/docs/media/07-helicopter-loops.gif and /dev/null differ diff --git a/docs/media/08-boneyard.gif b/docs/media/08-boneyard.gif deleted file mode 100644 index 6deb246166..0000000000 Binary files a/docs/media/08-boneyard.gif and /dev/null differ diff --git a/docs/media/08-falcon9-replay.gif b/docs/media/08-falcon9-replay.gif deleted file mode 100644 index f73259d6e2..0000000000 Binary files a/docs/media/08-falcon9-replay.gif and /dev/null differ diff --git a/docs/media/09-undersea-cables.gif b/docs/media/09-undersea-cables.gif deleted file mode 100644 index 1d9b00f5a1..0000000000 Binary files a/docs/media/09-undersea-cables.gif and /dev/null differ diff --git a/docs/media/10-walking-route-flythrough.gif b/docs/media/10-walking-route-flythrough.gif deleted file mode 100644 index 03b44f75b9..0000000000 Binary files a/docs/media/10-walking-route-flythrough.gif and /dev/null differ diff --git a/docs/media/12-switch-aircraft-cockpit.gif b/docs/media/12-switch-aircraft-cockpit.gif deleted file mode 100644 index 7aea557cff..0000000000 Binary files a/docs/media/12-switch-aircraft-cockpit.gif and /dev/null differ diff --git a/docs/media/14-iss-over-ukraine.gif b/docs/media/14-iss-over-ukraine.gif deleted file mode 100644 index 12f09a2295..0000000000 Binary files a/docs/media/14-iss-over-ukraine.gif and /dev/null differ diff --git a/docs/media/15-global-radio-layer.gif b/docs/media/15-global-radio-layer.gif deleted file mode 100644 index 849e61e2a6..0000000000 Binary files a/docs/media/15-global-radio-layer.gif and /dev/null differ diff --git a/docs/media/README.md b/docs/media/README.md index 6e0fc8bc74..894407adf5 100644 --- a/docs/media/README.md +++ b/docs/media/README.md @@ -1,39 +1,36 @@ # README media provenance -## Capture GIFs +## Site clips -Bilawal Sidhu created and owns the following 17 GIFs and has authorized their inclusion and redistribution as part of this public repository and its project documentation. Any appearance by Bilawal Sidhu in these captures is included with his permission. +The following animated images in `site/` are the clips shown on [godseyeview.ai](https://godseyeview.ai), converted to animated WebP for the README. Bilawal Sidhu and Halfpixel, Inc. created them and have authorized their inclusion and redistribution as part of this public repository and its project documentation. -- `hero-open-source-reveal.gif` -- `06-cockpit-ar.gif` -- `start-here/airport-ground-traffic-google-3d.gif` -- `03-austin-cctv.gif` -- `14-iss-over-ukraine.gif` -- `01-style-sweep.gif` -- `12-switch-aircraft-cockpit.gif` -- `start-here/military-cockpit-dense-google-3d.gif` -- `01-voice-annotate-zilker.gif` -- `04-airport-distance.gif` -- `15-global-radio-layer.gif` -- `08-falcon9-replay.gif` -- `09-undersea-cables.gif` -- `07-helicopter-loops.gif` -- `10-walking-route-flythrough.gif` -- `08-boneyard.gif` -- `05-traffic-to-cctv.gif` +- `site/hero.webp` +- `site/voice.webp` +- `site/flights.webp` +- `site/satellites.webp` +- `site/cameras.webp` +- `site/cockpit.webp` +- `site/weather.webp` +- `site/imagery.webp` +- `site/transit.webp` +- `site/sdr.webp` +- `site/radio.webp` +- `site/mcp.webp` +- `site/director.webp` -Copyright © Bilawal Sidhu. These files are not covered by the project's MIT License. Permission is limited to their inclusion and redistribution with this repository and its project documentation. No permission is granted for standalone reuse or modification. Commercial reuse outside this repository requires separate permission. No share-alike license applies. +Copyright © Bilawal Sidhu and Halfpixel, Inc. These files are not covered by the project's MIT License. Permission is limited to their inclusion and redistribution with this repository and its project documentation. No permission is granted for standalone reuse or modification. Commercial reuse outside this repository requires separate permission. No share-alike license applies. -The GIFs are promotional captures of God's Eye View. They include Google Photorealistic 3D Tiles and public or third-party data layers with in-frame attribution. Bilawal Sidhu's ownership and permission cover the captures and his likeness; they do not replace the terms of Google Maps Platform or any displayed data provider. Keep the visible attribution intact. +The clips are promotional captures and renders of God's Eye View. Some include Google Photorealistic 3D Tiles and public or third-party data layers with in-frame attribution. The permission above covers the clips; it does not replace the terms of Google Maps Platform or any displayed data provider. Keep the visible attribution intact. + +The launch-era capture GIFs that this page listed before were removed from the README and from the repository in November 2026. They remain in the Git history under the terms stated for them at the time. ## Public README PNGs -Bilawal Sidhu published the following PNGs in the existing public `bilawalsidhu/gods-eye-view` repository and authorized their continued inclusion and redistribution with this repository and its project documentation: +Bilawal Sidhu published the following PNG in the existing public `bilawalsidhu/gods-eye-view` repository and authorized their continued inclusion and redistribution with this repository and its project documentation: -- `youtube-popular-videos.png` - `open-source-survey.png` -Source: [`assets/youtube-popular-videos.png`](https://github.com/bilawalsidhu/gods-eye-view/blob/7afb3beefb2dd39110ed117c8f06825e9ca2ada4/assets/youtube-popular-videos.png) and [`assets/open-source-survey.png`](https://github.com/bilawalsidhu/gods-eye-view/blob/7afb3beefb2dd39110ed117c8f06825e9ca2ada4/assets/open-source-survey.png) in public repository commit [`7afb3beefb2dd39110ed117c8f06825e9ca2ada4`](https://github.com/bilawalsidhu/gods-eye-view/commit/7afb3beefb2dd39110ed117c8f06825e9ca2ada4). The localized files preserve the source bytes unchanged. +Source: [`assets/open-source-survey.png`](https://github.com/bilawalsidhu/gods-eye-view/blob/7afb3beefb2dd39110ed117c8f06825e9ca2ada4/assets/open-source-survey.png) in public repository commit [`7afb3beefb2dd39110ed117c8f06825e9ca2ada4`](https://github.com/bilawalsidhu/gods-eye-view/commit/7afb3beefb2dd39110ed117c8f06825e9ca2ada4). The localized files preserve the source bytes unchanged. These files are not covered by the project's MIT License. No permission is granted for standalone reuse or modification. Commercial reuse outside this repository requires separate permission. No share-alike license applies. diff --git a/docs/media/hero-open-source-reveal.gif b/docs/media/hero-open-source-reveal.gif deleted file mode 100644 index 0e9e6a5c47..0000000000 Binary files a/docs/media/hero-open-source-reveal.gif and /dev/null differ diff --git a/docs/media/site/cameras.webp b/docs/media/site/cameras.webp new file mode 100644 index 0000000000..730b6589e6 Binary files /dev/null and b/docs/media/site/cameras.webp differ diff --git a/docs/media/site/cockpit.webp b/docs/media/site/cockpit.webp new file mode 100644 index 0000000000..3aae9977ea Binary files /dev/null and b/docs/media/site/cockpit.webp differ diff --git a/docs/media/site/director.webp b/docs/media/site/director.webp new file mode 100644 index 0000000000..41eecabf9a Binary files /dev/null and b/docs/media/site/director.webp differ diff --git a/docs/media/site/flights.webp b/docs/media/site/flights.webp new file mode 100644 index 0000000000..cb7d1704fb Binary files /dev/null and b/docs/media/site/flights.webp differ diff --git a/docs/media/site/hero.webp b/docs/media/site/hero.webp new file mode 100644 index 0000000000..4e8eb4e52d Binary files /dev/null and b/docs/media/site/hero.webp differ diff --git a/docs/media/site/imagery.webp b/docs/media/site/imagery.webp new file mode 100644 index 0000000000..1762ebeea0 Binary files /dev/null and b/docs/media/site/imagery.webp differ diff --git a/docs/media/site/mcp.webp b/docs/media/site/mcp.webp new file mode 100644 index 0000000000..88d3b0813b Binary files /dev/null and b/docs/media/site/mcp.webp differ diff --git a/docs/media/site/radio.webp b/docs/media/site/radio.webp new file mode 100644 index 0000000000..9df9e96bcb Binary files /dev/null and b/docs/media/site/radio.webp differ diff --git a/docs/media/site/satellites.webp b/docs/media/site/satellites.webp new file mode 100644 index 0000000000..9cf0469d97 Binary files /dev/null and b/docs/media/site/satellites.webp differ diff --git a/docs/media/site/sdr.webp b/docs/media/site/sdr.webp new file mode 100644 index 0000000000..65cd145950 Binary files /dev/null and b/docs/media/site/sdr.webp differ diff --git a/docs/media/site/transit.webp b/docs/media/site/transit.webp new file mode 100644 index 0000000000..fd72061f96 Binary files /dev/null and b/docs/media/site/transit.webp differ diff --git a/docs/media/site/voice.webp b/docs/media/site/voice.webp new file mode 100644 index 0000000000..ee755b68aa Binary files /dev/null and b/docs/media/site/voice.webp differ diff --git a/docs/media/site/weather.webp b/docs/media/site/weather.webp new file mode 100644 index 0000000000..58434a0a26 Binary files /dev/null and b/docs/media/site/weather.webp differ diff --git a/docs/media/start-here/airport-ground-traffic-google-3d.gif b/docs/media/start-here/airport-ground-traffic-google-3d.gif deleted file mode 100644 index 74fb28cc93..0000000000 Binary files a/docs/media/start-here/airport-ground-traffic-google-3d.gif and /dev/null differ diff --git a/docs/media/start-here/military-cockpit-dense-google-3d.gif b/docs/media/start-here/military-cockpit-dense-google-3d.gif deleted file mode 100644 index a6432b35d7..0000000000 Binary files a/docs/media/start-here/military-cockpit-dense-google-3d.gif and /dev/null differ diff --git a/docs/media/youtube-popular-videos.png b/docs/media/youtube-popular-videos.png deleted file mode 100644 index 6454f88f15..0000000000 Binary files a/docs/media/youtube-popular-videos.png and /dev/null differ diff --git a/index.html b/index.html index f3057f742e..2341db1c72 100644 --- a/index.html +++ b/index.html @@ -26,7 +26,7 @@ with the sources: src/materialSymbolsSubset.test.mjs fails when a source names a glyph this list is missing, because a missing glyph does not draw a box — the ligature never forms and the element renders the literal word. --> - +
diff --git a/package-lock.json b/package-lock.json index df28aba4b9..af748fcd3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,8 +16,10 @@ "cesium": "^1.124.0", "egm96-universal": "^1.1.1", "fzstd": "0.1.1", + "h3-js": "^4.4.0", "hls.js": "^1.7.3", "hyparquet": "1.31.2", + "kdbush": "^4.0.2", "mapillary-js": "^4.1.2", "mgrs": "^2.1.0", "pbf": "^5.1.2", @@ -35,6 +37,7 @@ "prettier": "3.9.6", "puppeteer": "^25.16.0", "sharp": "^0.35.4", + "typescript": "5.9.3", "vite": "^6.4.4", "vite-plugin-cesium": "^1.2.23", "ws": "^8.21.0" @@ -2532,6 +2535,17 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "license": "MIT" }, + "node_modules/h3-js": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/h3-js/-/h3-js-4.4.0.tgz", + "integrity": "sha512-DvJh07MhGgY2KcC4OeZc8SSyA+ZXpdvoh6uCzGpoKvWtZxJB+g6VXXC1+eWYkaMIsLz7J/ErhOalHCpcs1KYog==", + "license": "Apache-2.0", + "engines": { + "node": ">=4", + "npm": ">=3", + "yarn": ">=1.3.0" + } + }, "node_modules/happy-dom": { "version": "20.14.6", "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.6.tgz", @@ -3567,6 +3581,20 @@ "dev": true, "license": "MIT" }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", diff --git a/package.json b/package.json index c1476342d8..1a7f64a6dc 100644 --- a/package.json +++ b/package.json @@ -2,11 +2,11 @@ "name": "gods-eye-view", "private": true, "version": "0.3.0", - "description": "A real-time intelligence console for planet Earth \u2014 photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", + "description": "A real-time intelligence console for planet Earth — photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", "type": "module", "license": "MIT", "author": "Bilawal Sidhu", - "homepage": "https://github.com/bilawalsidhu/gods-eye-view#readme", + "homepage": "https://godseyeview.ai", "repository": { "type": "git", "url": "https://github.com/bilawalsidhu/gods-eye-view.git" @@ -53,6 +53,8 @@ "test": "node scripts/run-unit-tests.mjs", "test:perf": "node scripts/run-perf-tests.mjs", "test:track": "node scripts/track-regression.mjs", + "qa:stub-boot": "node scripts/qa-stub-boot.mjs", + "qa:conformance": "node scripts/qa-conformance.mjs", "qa:map-source-tray": "node scripts/qa-map-source-tray.mjs", "qa:street-level": "node scripts/qa-street-level.mjs", "qa:street-level:fixtures": "node scripts/qa-street-level.mjs --fixtures", @@ -69,8 +71,10 @@ "cesium": "^1.124.0", "egm96-universal": "^1.1.1", "fzstd": "0.1.1", + "h3-js": "^4.4.0", "hls.js": "^1.7.3", "hyparquet": "1.31.2", + "kdbush": "^4.0.2", "mapillary-js": "^4.1.2", "mgrs": "^2.1.0", "pbf": "^5.1.2", @@ -88,6 +92,7 @@ "prettier": "3.9.6", "puppeteer": "^25.16.0", "sharp": "^0.35.4", + "typescript": "5.9.3", "vite": "^6.4.4", "vite-plugin-cesium": "^1.2.23", "ws": "^8.21.0" @@ -97,7 +102,7 @@ "./infrastructure/geojson": "./src/data/localGeojsonCore.js", "./infrastructure/lod": "./src/data/localGeojsonLod.js", "./application": "./src/app/application.js", - "./application/viewer": "./src/app/viewer.js", + "./application/viewer": "./src/render/cesium/applicationViewer.js", "./time": "./src/time/worldClock.js", "./i18n": "./src/i18n/page.js", "./build/vite": { @@ -161,6 +166,7 @@ "./ui/layout": "./src/ui/panelRails.js", "./ui/input": "./src/ui/visualInput.js", "./ui/display": "./src/ui/displayControls.js", + "./ui/display/groups": "./src/ui/displayGroups.js", "./ui/effects": "./src/ui/effects.js", "./ui/effects/bloom": "./src/bloom.js", "./ui/maps": "./src/ui/mapSource.js", @@ -212,9 +218,9 @@ "./geography/neighborhoods": "./src/data/neighborhoodPolygons.js", "./maps/controller": "./src/maps/controller.js", "./maps/catalog": "./src/maps/catalog.js", - "./maps/imagery": "./src/maps/imagery.js", - "./maps/terrain": "./src/maps/terrain.js", - "./maps/3d": "./src/maps/google3d.js", + "./maps/imagery": "./src/render/cesium/mapImagery.js", + "./maps/terrain": "./src/render/cesium/mapTerrain.js", + "./maps/3d": "./src/render/cesium/google3d.js", "./maps/defaults": "./src/maps/defaultSources.js", "./voice/controller": "./src/voice/realtimeController.js", "./voice/control": "./src/voice/control.js", @@ -243,6 +249,9 @@ "./standalone/catalog": "./src/standalone/catalog.js", "./application/layers": "./src/app/constructCatalog.js", "./application/operations": "./src/app/operations.js", + "./data/entity-records": "./src/data/entityRecords.js", + "./input": "./src/input/dispatcher.js", + "./queries/heights": "./src/queries/heights.js", "./data/lifecycle": "./src/data/lifecycle.js", "./ui/navigation": "./src/ui/navigationController.js", "./ui/share-restoration": "./src/ui/shareRestoration.js", @@ -298,6 +307,7 @@ }, "./sources/rail-service": "./src/sources/railService.js", "./layers/rail/source": "./src/layers/rail/source.js", + "./layers/rail/paths": "./src/data/railPaths.js", "./sources/map-features": "./src/sources/overpassFeatures.js", "./server/providers/mapillary": { "node": "./server/providers/mapillary.js" @@ -314,6 +324,28 @@ "./tools/services": "./src/tools/services.js", "./view": "./src/view/index.js", "./agent/world-packet": "./src/agent/worldPacket.js", + "./geo": "./src/geo/index.js", + "./sky": "./src/sky/index.js", + "./render/contract": "./src/render/contract/index.js", + "./render/stub": "./src/render/stub/index.js", + "./render/occlusion": "./src/render/occlusion/index.js", + "./render/camera/events": "./src/render/camera/events.js", + "./render/camera/followTransition": "./src/render/camera/followTransition.js", + "./render/cesium/plugin": "./src/render/cesium/plugin.js", + "./render/cesium/unbound": "./src/render/cesium/unbound.js", + "./render/conformance": "./src/render/conformance/index.js", + "./render/input/router": "./src/render/input/router.js", + "./render/stub/camera": "./src/render/stub/camera.js", + "./render/stub/viewRectangle": "./src/render/stub/viewRectangle.js", + "./render/stub/harness": "./src/render/stub/harness.js", + "./render/motion": "./src/render/motion/iconMotion.js", + "./render/vectorBase": "./src/render/vectorBase/index.js", + "./render/iconSegment": "./src/data/iconSegment.js", + "./render/recession": "./src/render/recession.js", + "./render/windStreamlines": "./src/layers/wind/streamlines.js", + "./render/weather": "./src/render/weather.js", + "./weather/effects": "./src/weatherEffectsMath.js", + "./geo/screenCluster": "./src/geo/screenCluster.js", "./layers/wildlife-sightings": "./src/layers/wildlifeSightings/index.js", "./layers/wildlife-sightings/source": "./src/layers/wildlifeSightings/source.js" } diff --git a/public/models/README.md b/public/models/README.md index aa7f40fbd9..3f97820d37 100644 --- a/public/models/README.md +++ b/public/models/README.md @@ -1,20 +1,39 @@ -# Bundled 3D Model Attribution +# Bundled 3D Models -The model files in this directory are third-party visual assets. They are not -covered by the repository's MIT source-code license; each remains available -under the license listed below. +Every 3D model shipped in this directory is one of the project's procedural +fleet models under [`fleet/`](fleet/): aircraft, helicopters, ships, buoys, +transit and rail vehicles, and a few other airborne and ground objects. They +are generated from code by the project maintainers, contain no third-party +artwork, and are covered by the repository's [MIT license](../../LICENSE) +like the source code. -| File | Original work and creator | Source | License | Project modifications | -|---|---|---|---|---| -| `airplane.glb` | “boeing 747” by [zairiq-123](https://sketchfab.com/zairiq-123) | [Sketchfab model](https://sketchfab.com/3d-models/boeing-747-9b16672038ba48f98e6d80a159044ed9) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Substantially modified and optimized for God's Eye View, including geometry/material simplification and coordinate/orientation preparation. The former 24× runtime calibration is baked into the mesh; location, rotation, and scale are applied; the bounding-box centre is at the origin; and the model uses glTF +Y-up with its nose toward local −X. Geometry remains uncompressed so the aircraft asset does not compete with photogrammetry for Draco worker capacity. | -| `jet.glb` | “Private Jet” by [Nick the Name](https://sketchfab.com/Nick_The_Name) | [Sketchfab model](https://sketchfab.com/3d-models/private-jet-cbdd1de6ced9461e950eafaa302cc82b) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Repackaged as a glTF binary for the project's military-flight visualization. Imported hierarchy transforms are baked into the meshes; location, rotation, and scale are applied; the bounding-box centre is at the origin; and the model uses meter scale, glTF +Y-up, and the shared nose −X convention. Existing materials are preserved. | -| `bell206.glb` | “Bell 206 JetRanger” by [terran4627](https://sketchfab.com/terran4627) | [Sketchfab model](https://sketchfab.com/3d-models/bell-206-jetranger-d2f7ba1d671549d4b26aaf834139a1dd) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Optimized for God's Eye View: geometry/material simplification, textures resized to 256 px WebP, orientation/scale vertex-baked to real-world meters (Y-up, nose −X), origin centered. | -| `c172.glb` | “Cessna 172” by [e737](https://sketchfab.com/e0057537) | [Sketchfab model](https://sketchfab.com/3d-models/cessna-172-64cddaee5aff470682659a8c08525046) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Optimized for God's Eye View: geometry/material simplification, textures resized to 256 px WebP, orientation/scale vertex-baked to real-world meters (Y-up, nose −X), origin centered. | -| `citation2.glb` | “1990 Cessna Citation, Texture Detailed, Exterior” by [BlenderCommunityHead](https://sketchfab.com/aboodgoudagad) | [Sketchfab model](https://sketchfab.com/3d-models/1990-cessna-citation-texture-detailed-exterior-a78839624fe64900a8352cb23462350a) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Optimized for God's Eye View: geometry/material simplification, textures resized to 256 px WebP, orientation/scale vertex-baked to real-world meters (Y-up, nose −X), origin centered. | -| `mq9.glb` | “MQ-9” by [IProZenoN](https://sketchfab.com/IProZenoN) | [Sketchfab model](https://sketchfab.com/3d-models/mq-9-fabe963feb354c5584b51f9c470c3f7e) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Optimized for God's Eye View: geometry/material simplification, textures resized to 256 px WebP, orientation/scale vertex-baked to real-world meters (Y-up, nose −X), origin centered. | -| `b789.glb` | “Boeing 787-9” by [Nobilis 2](https://sketchfab.com/nobilishornet2) | [Sketchfab model](https://sketchfab.com/3d-models/boeing-787-9-b6711e2e698e4e469675c1154a50b7a3) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Optimized for God's Eye View: geometry/material simplification, textures resized to 256 px WebP, orientation/scale vertex-baked to real-world meters (Y-up, nose −X), origin centered. | -| `atr72.glb` | “ATR 72 - 600” by [Oyan3D](https://sketchfab.com/oyan3D) | [Sketchfab model](https://sketchfab.com/3d-models/atr-72-600-1e1a7186f7444d288675262fcee44744) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | Optimized for God's Eye View: geometry/material simplification, textures removed with dominant material colors baked into PBR factors (flat “abstracted” style), orientation/scale vertex-baked to real-world meters (Y-up, nose −X), origin centered. | +| Path | What it holds | +|---|---| +| `fleet/catalog.json` | Every model by name: its file, category, built length, beam and bounds (metres, in Cesium's Z-up model frame: x along the length with the nose toward −X, y across the beam, z up), the clearance below its origin, and its 2D icon class. | +| `fleet/types.json` | Which model draws which vehicle, and at what length: ICAO aircraft and helicopter type codes, ADS-B emitter categories, AIS ship-type and length ranges, GTFS route types, transit modes and rail categories, with the defaults. | +| `fleet/aircraft/`, `fleet/helicopters/`, `fleet/ships/`, `fleet/buoys/`, `fleet/transit/`, `fleet/other/` | The models, one GLB each (EXT_meshopt_compression and KHR_mesh_quantization, vertex colours, no textures). | -CC BY 4.0 permits sharing and adaptation, including commercial use, provided -appropriate credit is retained, the license is linked, and modifications are -identified. These credits do not imply endorsement by the original creators. +How the layers use them: + +- Each layer draws a vehicle with the model its type selects, scaled to the + type's published length (a vessel to its reported AIS length and beam), so + every model is drawn life size. Ground objects, balloons and obstacles in + the `other` category are drawn at the size they are built. +- An aid to navigation (a vessel record whose type names a buoy, beacon, IALA + mark, RACON or light, or whose MMSI is an aid station's `99MIDxxxx`) is + drawn as the `buoys` model of its mark (cardinal north, east, south or west, + port or starboard hand, safe water, isolated danger, special mark), a red + can when its type names no mark, at its built size and with no heading + (`vesselModelSpec`, `aidToNavigationModel`). +- An aircraft model's origin is its axis; it stands that model's scaled + clearance above the ground. A ship's origin is its waterline, and a transit + or rail vehicle's the road or rail top (a monorail or gondola is raised by + its `transit.elevation` entry, for a source that names those modes). +- Transit and rail models carry a `_TINT` vertex attribute that marks where + the route or category colour is painted. +- The whole set loads once, up front, when a layer that draws it starts; no + model is fetched while a session runs. + +`src/data/fleetModels.js` reads the set and chooses each vehicle's model; +`src/data/fleetModels.test.mjs` checks that every model `types.json` names is +in the catalog and on disk, and that no GLB exceeds 3 MB. diff --git a/public/models/airplane.glb b/public/models/airplane.glb deleted file mode 100644 index 016a56f1dc..0000000000 Binary files a/public/models/airplane.glb and /dev/null differ diff --git a/public/models/atr72.glb b/public/models/atr72.glb deleted file mode 100644 index 8946dc39c5..0000000000 Binary files a/public/models/atr72.glb and /dev/null differ diff --git a/public/models/b789.glb b/public/models/b789.glb deleted file mode 100644 index be9849d742..0000000000 Binary files a/public/models/b789.glb and /dev/null differ diff --git a/public/models/bell206.glb b/public/models/bell206.glb deleted file mode 100644 index 029fe13398..0000000000 Binary files a/public/models/bell206.glb and /dev/null differ diff --git a/public/models/c172.glb b/public/models/c172.glb deleted file mode 100644 index 3c51554336..0000000000 Binary files a/public/models/c172.glb and /dev/null differ diff --git a/public/models/citation2.glb b/public/models/citation2.glb deleted file mode 100644 index 2ec47d6dcd..0000000000 Binary files a/public/models/citation2.glb and /dev/null differ diff --git a/public/models/fleet/aircraft/a320.glb b/public/models/fleet/aircraft/a320.glb new file mode 100644 index 0000000000..017d8ed2c3 Binary files /dev/null and b/public/models/fleet/aircraft/a320.glb differ diff --git a/public/models/fleet/aircraft/a333.glb b/public/models/fleet/aircraft/a333.glb new file mode 100644 index 0000000000..7daeb83199 Binary files /dev/null and b/public/models/fleet/aircraft/a333.glb differ diff --git a/public/models/fleet/aircraft/a343.glb b/public/models/fleet/aircraft/a343.glb new file mode 100644 index 0000000000..a850cea4a9 Binary files /dev/null and b/public/models/fleet/aircraft/a343.glb differ diff --git a/public/models/fleet/aircraft/a359.glb b/public/models/fleet/aircraft/a359.glb new file mode 100644 index 0000000000..745681b277 Binary files /dev/null and b/public/models/fleet/aircraft/a359.glb differ diff --git a/public/models/fleet/aircraft/a388.glb b/public/models/fleet/aircraft/a388.glb new file mode 100644 index 0000000000..58e04f2d00 Binary files /dev/null and b/public/models/fleet/aircraft/a388.glb differ diff --git a/public/models/fleet/aircraft/at72.glb b/public/models/fleet/aircraft/at72.glb new file mode 100644 index 0000000000..bbe129d7ed Binary files /dev/null and b/public/models/fleet/aircraft/at72.glb differ diff --git a/public/models/fleet/aircraft/b738.glb b/public/models/fleet/aircraft/b738.glb new file mode 100644 index 0000000000..6e4a94a383 Binary files /dev/null and b/public/models/fleet/aircraft/b738.glb differ diff --git a/public/models/fleet/aircraft/b744.glb b/public/models/fleet/aircraft/b744.glb new file mode 100644 index 0000000000..f5f9e421d8 Binary files /dev/null and b/public/models/fleet/aircraft/b744.glb differ diff --git a/public/models/fleet/aircraft/b763.glb b/public/models/fleet/aircraft/b763.glb new file mode 100644 index 0000000000..34c59a9125 Binary files /dev/null and b/public/models/fleet/aircraft/b763.glb differ diff --git a/public/models/fleet/aircraft/b77w.glb b/public/models/fleet/aircraft/b77w.glb new file mode 100644 index 0000000000..a190513002 Binary files /dev/null and b/public/models/fleet/aircraft/b77w.glb differ diff --git a/public/models/fleet/aircraft/b789.glb b/public/models/fleet/aircraft/b789.glb new file mode 100644 index 0000000000..5474a55a4a Binary files /dev/null and b/public/models/fleet/aircraft/b789.glb differ diff --git a/public/models/fleet/aircraft/bcs3.glb b/public/models/fleet/aircraft/bcs3.glb new file mode 100644 index 0000000000..422ebe7008 Binary files /dev/null and b/public/models/fleet/aircraft/bcs3.glb differ diff --git a/public/models/fleet/aircraft/be20.glb b/public/models/fleet/aircraft/be20.glb new file mode 100644 index 0000000000..d1a2c4dfda Binary files /dev/null and b/public/models/fleet/aircraft/be20.glb differ diff --git a/public/models/fleet/aircraft/c17.glb b/public/models/fleet/aircraft/c17.glb new file mode 100644 index 0000000000..19c51a523b Binary files /dev/null and b/public/models/fleet/aircraft/c17.glb differ diff --git a/public/models/fleet/aircraft/c172.glb b/public/models/fleet/aircraft/c172.glb new file mode 100644 index 0000000000..9a5b7d73f9 Binary files /dev/null and b/public/models/fleet/aircraft/c172.glb differ diff --git a/public/models/fleet/aircraft/c30j.glb b/public/models/fleet/aircraft/c30j.glb new file mode 100644 index 0000000000..b5d4a7122b Binary files /dev/null and b/public/models/fleet/aircraft/c30j.glb differ diff --git a/public/models/fleet/aircraft/c56x.glb b/public/models/fleet/aircraft/c56x.glb new file mode 100644 index 0000000000..2185dfe795 Binary files /dev/null and b/public/models/fleet/aircraft/c56x.glb differ diff --git a/public/models/fleet/aircraft/cl35.glb b/public/models/fleet/aircraft/cl35.glb new file mode 100644 index 0000000000..f2df5f86b9 Binary files /dev/null and b/public/models/fleet/aircraft/cl35.glb differ diff --git a/public/models/fleet/aircraft/crj9.glb b/public/models/fleet/aircraft/crj9.glb new file mode 100644 index 0000000000..24e6448b66 Binary files /dev/null and b/public/models/fleet/aircraft/crj9.glb differ diff --git a/public/models/fleet/aircraft/dh8d.glb b/public/models/fleet/aircraft/dh8d.glb new file mode 100644 index 0000000000..f763fec213 Binary files /dev/null and b/public/models/fleet/aircraft/dh8d.glb differ diff --git a/public/models/fleet/aircraft/e175.glb b/public/models/fleet/aircraft/e175.glb new file mode 100644 index 0000000000..acdc5230ea Binary files /dev/null and b/public/models/fleet/aircraft/e175.glb differ diff --git a/public/models/fleet/aircraft/e55p.glb b/public/models/fleet/aircraft/e55p.glb new file mode 100644 index 0000000000..b130d2a9ea Binary files /dev/null and b/public/models/fleet/aircraft/e55p.glb differ diff --git a/public/models/fleet/aircraft/generic_plane.glb b/public/models/fleet/aircraft/generic_plane.glb new file mode 100644 index 0000000000..a126c8b267 Binary files /dev/null and b/public/models/fleet/aircraft/generic_plane.glb differ diff --git a/public/models/fleet/aircraft/glf4.glb b/public/models/fleet/aircraft/glf4.glb new file mode 100644 index 0000000000..31ddd2c74e Binary files /dev/null and b/public/models/fleet/aircraft/glf4.glb differ diff --git a/public/models/fleet/aircraft/glider.glb b/public/models/fleet/aircraft/glider.glb new file mode 100644 index 0000000000..60b722726a Binary files /dev/null and b/public/models/fleet/aircraft/glider.glb differ diff --git a/public/models/fleet/aircraft/k35r.glb b/public/models/fleet/aircraft/k35r.glb new file mode 100644 index 0000000000..7a7cfbe735 Binary files /dev/null and b/public/models/fleet/aircraft/k35r.glb differ diff --git a/public/models/fleet/aircraft/md11.glb b/public/models/fleet/aircraft/md11.glb new file mode 100644 index 0000000000..885a816243 Binary files /dev/null and b/public/models/fleet/aircraft/md11.glb differ diff --git a/public/models/fleet/aircraft/mq9.glb b/public/models/fleet/aircraft/mq9.glb new file mode 100644 index 0000000000..737912fc3d Binary files /dev/null and b/public/models/fleet/aircraft/mq9.glb differ diff --git a/public/models/fleet/aircraft/p28a.glb b/public/models/fleet/aircraft/p28a.glb new file mode 100644 index 0000000000..ca47aec1a6 Binary files /dev/null and b/public/models/fleet/aircraft/p28a.glb differ diff --git a/public/models/fleet/aircraft/pc12.glb b/public/models/fleet/aircraft/pc12.glb new file mode 100644 index 0000000000..2b2666a0a2 Binary files /dev/null and b/public/models/fleet/aircraft/pc12.glb differ diff --git a/public/models/fleet/aircraft/sr22.glb b/public/models/fleet/aircraft/sr22.glb new file mode 100644 index 0000000000..7c2d66fe6f Binary files /dev/null and b/public/models/fleet/aircraft/sr22.glb differ diff --git a/public/models/fleet/aircraft/t38.glb b/public/models/fleet/aircraft/t38.glb new file mode 100644 index 0000000000..b9c8cd9ee4 Binary files /dev/null and b/public/models/fleet/aircraft/t38.glb differ diff --git a/public/models/fleet/aircraft/tex2.glb b/public/models/fleet/aircraft/tex2.glb new file mode 100644 index 0000000000..8a3ec3e00a Binary files /dev/null and b/public/models/fleet/aircraft/tex2.glb differ diff --git a/public/models/fleet/aircraft/ultralight.glb b/public/models/fleet/aircraft/ultralight.glb new file mode 100644 index 0000000000..965d9cdddd Binary files /dev/null and b/public/models/fleet/aircraft/ultralight.glb differ diff --git a/public/models/fleet/aircraft/v22.glb b/public/models/fleet/aircraft/v22.glb new file mode 100644 index 0000000000..01021ca2d8 Binary files /dev/null and b/public/models/fleet/aircraft/v22.glb differ diff --git a/public/models/fleet/buoys/barrel_yellow.glb b/public/models/fleet/buoys/barrel_yellow.glb new file mode 100644 index 0000000000..d2fb0e0179 Binary files /dev/null and b/public/models/fleet/buoys/barrel_yellow.glb differ diff --git a/public/models/fleet/buoys/buoy_cardinal_east.glb b/public/models/fleet/buoys/buoy_cardinal_east.glb new file mode 100644 index 0000000000..a0053edb04 Binary files /dev/null and b/public/models/fleet/buoys/buoy_cardinal_east.glb differ diff --git a/public/models/fleet/buoys/buoy_cardinal_north.glb b/public/models/fleet/buoys/buoy_cardinal_north.glb new file mode 100644 index 0000000000..adac99ccbc Binary files /dev/null and b/public/models/fleet/buoys/buoy_cardinal_north.glb differ diff --git a/public/models/fleet/buoys/buoy_cardinal_south.glb b/public/models/fleet/buoys/buoy_cardinal_south.glb new file mode 100644 index 0000000000..b84b392f24 Binary files /dev/null and b/public/models/fleet/buoys/buoy_cardinal_south.glb differ diff --git a/public/models/fleet/buoys/buoy_cardinal_west.glb b/public/models/fleet/buoys/buoy_cardinal_west.glb new file mode 100644 index 0000000000..d9891b2533 Binary files /dev/null and b/public/models/fleet/buoys/buoy_cardinal_west.glb differ diff --git a/public/models/fleet/buoys/buoy_isolated_danger.glb b/public/models/fleet/buoys/buoy_isolated_danger.glb new file mode 100644 index 0000000000..e27187ac1f Binary files /dev/null and b/public/models/fleet/buoys/buoy_isolated_danger.glb differ diff --git a/public/models/fleet/buoys/buoy_lateral_port.glb b/public/models/fleet/buoys/buoy_lateral_port.glb new file mode 100644 index 0000000000..dcc6bf1c1e Binary files /dev/null and b/public/models/fleet/buoys/buoy_lateral_port.glb differ diff --git a/public/models/fleet/buoys/buoy_lateral_starboard.glb b/public/models/fleet/buoys/buoy_lateral_starboard.glb new file mode 100644 index 0000000000..c025c8cb39 Binary files /dev/null and b/public/models/fleet/buoys/buoy_lateral_starboard.glb differ diff --git a/public/models/fleet/buoys/buoy_safe_water.glb b/public/models/fleet/buoys/buoy_safe_water.glb new file mode 100644 index 0000000000..47fbc56021 Binary files /dev/null and b/public/models/fleet/buoys/buoy_safe_water.glb differ diff --git a/public/models/fleet/buoys/buoy_special.glb b/public/models/fleet/buoys/buoy_special.glb new file mode 100644 index 0000000000..faee377406 Binary files /dev/null and b/public/models/fleet/buoys/buoy_special.glb differ diff --git a/public/models/fleet/buoys/can_red.glb b/public/models/fleet/buoys/can_red.glb new file mode 100644 index 0000000000..97beeffa72 Binary files /dev/null and b/public/models/fleet/buoys/can_red.glb differ diff --git a/public/models/fleet/buoys/can_red_cylinder.glb b/public/models/fleet/buoys/can_red_cylinder.glb new file mode 100644 index 0000000000..bd87b55f4b Binary files /dev/null and b/public/models/fleet/buoys/can_red_cylinder.glb differ diff --git a/public/models/fleet/buoys/conical_green.glb b/public/models/fleet/buoys/conical_green.glb new file mode 100644 index 0000000000..36eb6729c8 Binary files /dev/null and b/public/models/fleet/buoys/conical_green.glb differ diff --git a/public/models/fleet/buoys/conical_green_cone.glb b/public/models/fleet/buoys/conical_green_cone.glb new file mode 100644 index 0000000000..c5a6b4476c Binary files /dev/null and b/public/models/fleet/buoys/conical_green_cone.glb differ diff --git a/public/models/fleet/buoys/pile_green_cone.glb b/public/models/fleet/buoys/pile_green_cone.glb new file mode 100644 index 0000000000..6960071c92 Binary files /dev/null and b/public/models/fleet/buoys/pile_green_cone.glb differ diff --git a/public/models/fleet/buoys/pile_red_cylinder.glb b/public/models/fleet/buoys/pile_red_cylinder.glb new file mode 100644 index 0000000000..a613366022 Binary files /dev/null and b/public/models/fleet/buoys/pile_red_cylinder.glb differ diff --git a/public/models/fleet/buoys/spar_lateral_port.glb b/public/models/fleet/buoys/spar_lateral_port.glb new file mode 100644 index 0000000000..1152dd9284 Binary files /dev/null and b/public/models/fleet/buoys/spar_lateral_port.glb differ diff --git a/public/models/fleet/buoys/spar_lateral_starboard.glb b/public/models/fleet/buoys/spar_lateral_starboard.glb new file mode 100644 index 0000000000..193882ac88 Binary files /dev/null and b/public/models/fleet/buoys/spar_lateral_starboard.glb differ diff --git a/public/models/fleet/buoys/spherical_green.glb b/public/models/fleet/buoys/spherical_green.glb new file mode 100644 index 0000000000..fc06b79209 Binary files /dev/null and b/public/models/fleet/buoys/spherical_green.glb differ diff --git a/public/models/fleet/buoys/spherical_yellow.glb b/public/models/fleet/buoys/spherical_yellow.glb new file mode 100644 index 0000000000..d8b660b7cf Binary files /dev/null and b/public/models/fleet/buoys/spherical_yellow.glb differ diff --git a/public/models/fleet/buoys/spherical_yellow_x.glb b/public/models/fleet/buoys/spherical_yellow_x.glb new file mode 100644 index 0000000000..2ebbee87c8 Binary files /dev/null and b/public/models/fleet/buoys/spherical_yellow_x.glb differ diff --git a/public/models/fleet/buoys/stake_green_cone.glb b/public/models/fleet/buoys/stake_green_cone.glb new file mode 100644 index 0000000000..25fc6758bc Binary files /dev/null and b/public/models/fleet/buoys/stake_green_cone.glb differ diff --git a/public/models/fleet/buoys/stake_red_cylinder.glb b/public/models/fleet/buoys/stake_red_cylinder.glb new file mode 100644 index 0000000000..31164848d7 Binary files /dev/null and b/public/models/fleet/buoys/stake_red_cylinder.glb differ diff --git a/public/models/fleet/buoys/stake_yellow_x.glb b/public/models/fleet/buoys/stake_yellow_x.glb new file mode 100644 index 0000000000..cdd756643b Binary files /dev/null and b/public/models/fleet/buoys/stake_yellow_x.glb differ diff --git a/public/models/fleet/catalog.json b/public/models/fleet/catalog.json new file mode 100644 index 0000000000..91fbc5acdb --- /dev/null +++ b/public/models/fleet/catalog.json @@ -0,0 +1,2320 @@ +{ + "a139": { + "category": "helicopters", + "file": "helicopters/a139.glb", + "min": [ + -8.045, + -6.626, + -1.575 + ], + "max": [ + 7.638, + 6.626, + 2.979 + ], + "length": 15.683, + "beam": 13.253, + "clearance": 1.575, + "tris": 1464, + "icon": "heli" + }, + "a320": { + "category": "aircraft", + "file": "aircraft/a320.glb", + "min": [ + -18.785, + -17.806, + -3.063 + ], + "max": [ + 18.785, + 17.806, + 7.56 + ], + "length": 37.57, + "beam": 35.611, + "clearance": 3.063, + "tris": 2338, + "icon": "jet" + }, + "a333": { + "category": "aircraft", + "file": "aircraft/a333.glb", + "min": [ + -31.845, + -29.842, + -4.251 + ], + "max": [ + 31.845, + 29.842, + 10.854 + ], + "length": 63.69, + "beam": 59.684, + "clearance": 4.251, + "tris": 2338, + "icon": "widebody" + }, + "a343": { + "category": "aircraft", + "file": "aircraft/a343.glb", + "min": [ + -31.845, + -29.842, + -3.343 + ], + "max": [ + 31.845, + 29.842, + 10.854 + ], + "length": 63.69, + "beam": 59.684, + "clearance": 3.343, + "tris": 2638, + "icon": "quad" + }, + "a359": { + "category": "aircraft", + "file": "aircraft/a359.glb", + "min": [ + -33.4, + -32.106, + -4.83 + ], + "max": [ + 33.4, + 32.106, + 11.233 + ], + "length": 66.8, + "beam": 64.212, + "clearance": 4.83, + "tris": 2338, + "icon": "widebody" + }, + "a388": { + "category": "aircraft", + "file": "aircraft/a388.glb", + "min": [ + -36.36, + -39.291, + -4.827 + ], + "max": [ + 37.527, + 39.291, + 14.899 + ], + "length": 73.887, + "beam": 78.582, + "clearance": 4.827, + "tris": 2658, + "icon": "quad" + }, + "articulated_bus": { + "category": "transit", + "file": "transit/articulated_bus.glb", + "min": [ + -9.05, + -1.32, + -0.0 + ], + "max": [ + 9.05, + 1.355, + 3.33 + ], + "length": 18.1, + "beam": 2.675, + "clearance": 0.0, + "tris": 604, + "icon": "bus" + }, + "as50": { + "category": "helicopters", + "file": "helicopters/as50.glb", + "min": [ + -5.465, + -4.709, + -1.365 + ], + "max": [ + 6.023, + 4.709, + 2.267 + ], + "length": 11.488, + "beam": 9.418, + "clearance": 1.365, + "tris": 1488, + "icon": "heli" + }, + "at72": { + "category": "aircraft", + "file": "aircraft/at72.glb", + "min": [ + -13.585, + -13.255, + -1.402 + ], + "max": [ + 13.585, + 13.255, + 5.503 + ], + "length": 27.17, + "beam": 26.509, + "clearance": 1.402, + "tris": 2300, + "icon": "turboprop" + }, + "b06": { + "category": "helicopters", + "file": "helicopters/b06.glb", + "min": [ + -6.695, + -1.029, + -1.265 + ], + "max": [ + 5.294, + 1.029, + 1.91 + ], + "length": 11.989, + "beam": 2.057, + "clearance": 1.265, + "tris": 1476, + "icon": "heli" + }, + "b407": { + "category": "helicopters", + "file": "helicopters/b407.glb", + "min": [ + -7.137, + -5.335, + -1.315 + ], + "max": [ + 5.83, + 5.335, + 2.128 + ], + "length": 12.967, + "beam": 10.67, + "clearance": 1.315, + "tris": 1500, + "icon": "heli" + }, + "b738": { + "category": "aircraft", + "file": "aircraft/b738.glb", + "min": [ + -19.735, + -17.802, + -2.528 + ], + "max": [ + 19.735, + 17.802, + 8.122 + ], + "length": 39.47, + "beam": 35.603, + "clearance": 2.528, + "tris": 2350, + "icon": "jet" + }, + "b744": { + "category": "aircraft", + "file": "aircraft/b744.glb", + "min": [ + -35.33, + -31.777, + -3.786 + ], + "max": [ + 35.809, + 31.777, + 12.595 + ], + "length": 71.139, + "beam": 63.554, + "clearance": 3.786, + "tris": 2910, + "icon": "quad" + }, + "b763": { + "category": "aircraft", + "file": "aircraft/b763.glb", + "min": [ + -27.45, + -23.692, + -3.852 + ], + "max": [ + 27.45, + 23.692, + 10.008 + ], + "length": 54.9, + "beam": 47.385, + "clearance": 3.852, + "tris": 2338, + "icon": "widebody" + }, + "b77w": { + "category": "aircraft", + "file": "aircraft/b77w.glb", + "min": [ + -36.95, + -31.752, + -5.444 + ], + "max": [ + 36.95, + 31.752, + 11.469 + ], + "length": 73.9, + "beam": 63.504, + "clearance": 5.444, + "tris": 2186, + "icon": "widebody" + }, + "b789": { + "category": "aircraft", + "file": "aircraft/b789.glb", + "min": [ + -31.4, + -29.449, + -4.769 + ], + "max": [ + 31.4, + 29.449, + 10.973 + ], + "length": 62.8, + "beam": 58.898, + "clearance": 4.769, + "tris": 2186, + "icon": "widebody" + }, + "balloon": { + "category": "other", + "file": "other/balloon.glb", + "min": [ + -8.5, + -8.5, + -5.95 + ], + "max": [ + 8.5, + 8.5, + 19.55 + ], + "length": 16.999, + "beam": 16.999, + "clearance": 5.95, + "tris": 504, + "icon": "balloon" + }, + "barrel_yellow": { + "category": "buoys", + "file": "buoys/barrel_yellow.glb", + "min": [ + -0.85, + -0.5, + -0.3 + ], + "max": [ + 0.85, + 0.5, + 0.85 + ], + "length": 1.7, + "beam": 1.0, + "clearance": 0.3, + "tris": 80, + "icon": "buoy" + }, + "bcs3": { + "category": "aircraft", + "file": "aircraft/bcs3.glb", + "min": [ + -19.35, + -17.439, + -3.196 + ], + "max": [ + 19.35, + 17.439, + 7.086 + ], + "length": 38.7, + "beam": 34.879, + "clearance": 3.196, + "tris": 2338, + "icon": "jet" + }, + "be20": { + "category": "aircraft", + "file": "aircraft/be20.glb", + "min": [ + -6.67, + -8.139, + -0.871 + ], + "max": [ + 7.162, + 8.139, + 3.351 + ], + "length": 13.832, + "beam": 16.278, + "clearance": 0.871, + "tris": 2386, + "icon": "turboprop" + }, + "blimp": { + "category": "other", + "file": "other/blimp.glb", + "min": [ + -37.5, + -8.427, + -10.6 + ], + "max": [ + 37.5, + 8.427, + 8.427 + ], + "length": 75.0, + "beam": 16.855, + "clearance": 10.6, + "tris": 1044, + "icon": "balloon" + }, + "bulk_carrier": { + "category": "ships", + "file": "ships/bulk_carrier.glb", + "min": [ + -98.8, + -16.0, + -10.88 + ], + "max": [ + 95.0, + 16.0, + 30.76 + ], + "length": 193.8, + "beam": 32.0, + "clearance": 10.88, + "tris": 3121, + "icon": "ship" + }, + "buoy_cardinal_east": { + "category": "buoys", + "file": "buoys/buoy_cardinal_east.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 5.7 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 654, + "icon": "buoy" + }, + "buoy_cardinal_north": { + "category": "buoys", + "file": "buoys/buoy_cardinal_north.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 5.7 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 606, + "icon": "buoy" + }, + "buoy_cardinal_south": { + "category": "buoys", + "file": "buoys/buoy_cardinal_south.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 5.7 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 606, + "icon": "buoy" + }, + "buoy_cardinal_west": { + "category": "buoys", + "file": "buoys/buoy_cardinal_west.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 5.7 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 654, + "icon": "buoy" + }, + "buoy_isolated_danger": { + "category": "buoys", + "file": "buoys/buoy_isolated_danger.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 5.65 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 986, + "icon": "buoy" + }, + "buoy_lateral_port": { + "category": "buoys", + "file": "buoys/buoy_lateral_port.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 4.95 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 558, + "icon": "buoy" + }, + "buoy_lateral_starboard": { + "category": "buoys", + "file": "buoys/buoy_lateral_starboard.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 4.95 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 528, + "icon": "buoy" + }, + "buoy_safe_water": { + "category": "buoys", + "file": "buoys/buoy_safe_water.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 4.95 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 694, + "icon": "buoy" + }, + "buoy_special": { + "category": "buoys", + "file": "buoys/buoy_special.glb", + "min": [ + -1.56, + -1.56, + -3.2 + ], + "max": [ + 1.56, + 1.56, + 5.202 + ], + "length": 3.12, + "beam": 3.12, + "clearance": 3.2, + "tris": 514, + "icon": "buoy" + }, + "c17": { + "category": "aircraft", + "file": "aircraft/c17.glb", + "min": [ + -26.52, + -25.688, + -3.467 + ], + "max": [ + 28.899, + 25.688, + 11.893 + ], + "length": 55.419, + "beam": 51.377, + "clearance": 3.467, + "tris": 2768, + "icon": "widebody" + }, + "c172": { + "category": "aircraft", + "file": "aircraft/c172.glb", + "min": [ + -4.416, + -5.39, + -1.49 + ], + "max": [ + 4.548, + 5.39, + 1.97 + ], + "length": 8.964, + "beam": 10.78, + "clearance": 1.49, + "tris": 2162, + "icon": "light" + }, + "c30j": { + "category": "aircraft", + "file": "aircraft/c30j.glb", + "min": [ + -14.895, + -19.801, + -2.328 + ], + "max": [ + 15.001, + 19.801, + 9.051 + ], + "length": 29.896, + "beam": 39.602, + "clearance": 2.328, + "tris": 2800, + "icon": "turboprop" + }, + "c56x": { + "category": "aircraft", + "file": "aircraft/c56x.glb", + "min": [ + -7.895, + -8.413, + -0.911 + ], + "max": [ + 8.028, + 8.413, + 3.458 + ], + "length": 15.923, + "beam": 16.827, + "clearance": 0.911, + "tris": 2198, + "icon": "rear_jet" + }, + "cable_tram": { + "category": "transit", + "file": "transit/cable_tram.glb", + "min": [ + -4.3, + -1.445, + -0.0 + ], + "max": [ + 4.3, + 1.445, + 3.13 + ], + "length": 8.6, + "beam": 2.89, + "clearance": 0.0, + "tris": 384, + "icon": "tram" + }, + "can_red": { + "category": "buoys", + "file": "buoys/can_red.glb", + "min": [ + -0.8, + -0.8, + -0.6 + ], + "max": [ + 0.8, + 0.8, + 1.18 + ], + "length": 1.6, + "beam": 1.6, + "clearance": 0.6, + "tris": 228, + "icon": "buoy" + }, + "can_red_cylinder": { + "category": "buoys", + "file": "buoys/can_red_cylinder.glb", + "min": [ + -0.8, + -0.8, + -0.6 + ], + "max": [ + 0.8, + 0.8, + 1.9 + ], + "length": 1.6, + "beam": 1.6, + "clearance": 0.6, + "tris": 308, + "icon": "buoy" + }, + "car": { + "category": "other", + "file": "other/car.glb", + "min": [ + -2.31, + -1.075, + 0.018 + ], + "max": [ + 2.31, + 1.075, + 1.84 + ], + "length": 4.62, + "beam": 2.15, + "clearance": 0.0, + "tris": 736, + "icon": "vehicle" + }, + "car_carrier": { + "category": "ships", + "file": "ships/car_carrier.glb", + "min": [ + -101.0, + -16.0, + -8.96 + ], + "max": [ + 100.0, + 18.315, + 38.525 + ], + "length": 201.0, + "beam": 34.315, + "clearance": 8.96, + "tris": 3949, + "icon": "ship" + }, + "city_bus": { + "category": "transit", + "file": "transit/city_bus.glb", + "min": [ + -6.05, + -1.32, + -0.0 + ], + "max": [ + 6.05, + 1.355, + 3.33 + ], + "length": 12.1, + "beam": 2.675, + "clearance": 0.0, + "tris": 432, + "icon": "bus" + }, + "cl35": { + "category": "aircraft", + "file": "aircraft/cl35.glb", + "min": [ + -10.46, + -10.446, + -1.189 + ], + "max": [ + 12.27, + 10.446, + 4.351 + ], + "length": 22.73, + "beam": 20.892, + "clearance": 1.189, + "tris": 2434, + "icon": "rear_jet" + }, + "coach": { + "category": "transit", + "file": "transit/coach.glb", + "min": [ + -6.51, + -1.32, + -0.0 + ], + "max": [ + 6.5, + 1.355, + 3.739 + ], + "length": 13.01, + "beam": 2.675, + "clearance": 0.0, + "tris": 474, + "icon": "bus" + }, + "commuter_emu": { + "category": "transit", + "file": "transit/commuter_emu.glb", + "min": [ + -49.05, + -1.53, + -0.0 + ], + "max": [ + 49.05, + 1.53, + 5.733 + ], + "length": 98.1, + "beam": 3.06, + "clearance": 0.0, + "tris": 1570, + "icon": "rail" + }, + "conical_green": { + "category": "buoys", + "file": "buoys/conical_green.glb", + "min": [ + -0.85, + -0.85, + -0.6 + ], + "max": [ + 0.85, + 0.85, + 1.7 + ], + "length": 1.7, + "beam": 1.7, + "clearance": 0.6, + "tris": 172, + "icon": "buoy" + }, + "conical_green_cone": { + "category": "buoys", + "file": "buoys/conical_green_cone.glb", + "min": [ + -0.85, + -0.85, + -0.6 + ], + "max": [ + 0.85, + 0.85, + 2.42 + ], + "length": 1.7, + "beam": 1.7, + "clearance": 0.6, + "tris": 222, + "icon": "buoy" + }, + "container_ship": { + "category": "ships", + "file": "ships/container_ship.glb", + "min": [ + -159.9, + -24.0, + -13.92 + ], + "max": [ + 150.0, + 24.0, + 47.94 + ], + "length": 309.9, + "beam": 48.0, + "clearance": 13.92, + "tris": 14337, + "icon": "ship" + }, + "crj9": { + "category": "aircraft", + "file": "aircraft/crj9.glb", + "min": [ + -18.1, + -12.347, + -1.339 + ], + "max": [ + 18.396, + 12.347, + 5.684 + ], + "length": 36.496, + "beam": 24.694, + "clearance": 1.339, + "tris": 2334, + "icon": "rear_jet" + }, + "cruise_ship": { + "category": "ships", + "file": "ships/cruise_ship.glb", + "min": [ + -168.0, + -22.5, + -8.4 + ], + "max": [ + 150.0, + 22.5, + 67.55 + ], + "length": 318.0, + "beam": 45.0, + "clearance": 8.4, + "tris": 3759, + "icon": "passenger" + }, + "dh8d": { + "category": "aircraft", + "file": "aircraft/dh8d.glb", + "min": [ + -16.4, + -13.916, + -1.339 + ], + "max": [ + 16.4, + 13.916, + 5.709 + ], + "length": 32.8, + "beam": 27.832, + "clearance": 1.339, + "tris": 2364, + "icon": "turboprop" + }, + "double_decker": { + "category": "transit", + "file": "transit/double_decker.glb", + "min": [ + -5.55, + -1.32, + -0.0 + ], + "max": [ + 5.55, + 1.355, + 4.387 + ], + "length": 11.1, + "beam": 2.675, + "clearance": 0.0, + "tris": 442, + "icon": "bus" + }, + "dredger": { + "category": "ships", + "file": "ships/dredger.glb", + "min": [ + -53.0, + -10.06, + -7.0 + ], + "max": [ + 50.0, + 11.0, + 17.955 + ], + "length": 103.0, + "beam": 21.06, + "clearance": 7.0, + "tris": 2597, + "icon": "ship" + }, + "e175": { + "category": "aircraft", + "file": "aircraft/e175.glb", + "min": [ + -15.84, + -12.917, + -2.427 + ], + "max": [ + 15.84, + 12.917, + 5.818 + ], + "length": 31.68, + "beam": 25.835, + "clearance": 2.427, + "tris": 2338, + "icon": "jet" + }, + "e55p": { + "category": "aircraft", + "file": "aircraft/e55p.glb", + "min": [ + -7.95, + -8.042, + -0.896 + ], + "max": [ + 8.222, + 8.042, + 3.469 + ], + "length": 16.172, + "beam": 16.084, + "clearance": 0.896, + "tris": 2414, + "icon": "rear_jet" + }, + "ec35": { + "category": "helicopters", + "file": "helicopters/ec35.glb", + "min": [ + -6.834, + -5.1, + -1.365 + ], + "max": [ + 5.304, + 5.1, + 2.0 + ], + "length": 12.138, + "beam": 10.2, + "clearance": 1.365, + "tris": 1420, + "icon": "heli" + }, + "ec45": { + "category": "helicopters", + "file": "helicopters/ec45.glb", + "min": [ + -7.472, + -5.5, + -1.54 + ], + "max": [ + 6.032, + 5.5, + 2.65 + ], + "length": 13.504, + "beam": 11.0, + "clearance": 1.54, + "tris": 1420, + "icon": "heli" + }, + "fast_ferry": { + "category": "ships", + "file": "ships/fast_ferry.glb", + "min": [ + -22.4, + -5.56, + -1.32 + ], + "max": [ + 20.0, + 5.56, + 8.3 + ], + "length": 42.4, + "beam": 11.12, + "clearance": 1.32, + "tris": 4754, + "icon": "passenger" + }, + "feeder": { + "category": "ships", + "file": "ships/feeder.glb", + "min": [ + -79.95, + -11.5, + -6.67 + ], + "max": [ + 75.0, + 11.5, + 28.09 + ], + "length": 154.95, + "beam": 23.0, + "clearance": 6.67, + "tris": 3519, + "icon": "ship" + }, + "ferry": { + "category": "ships", + "file": "ships/ferry.glb", + "min": [ + -70.2, + -12.9, + -5.28 + ], + "max": [ + 65.05, + 12.9, + 31.575 + ], + "length": 135.25, + "beam": 25.8, + "clearance": 5.28, + "tris": 3157, + "icon": "passenger" + }, + "fire_truck": { + "category": "other", + "file": "other/fire_truck.glb", + "min": [ + -6.408, + -1.507, + 0.029 + ], + "max": [ + 5.51, + 1.507, + 3.64 + ], + "length": 11.918, + "beam": 3.014, + "clearance": 0.0, + "tris": 1016, + "icon": "vehicle" + }, + "fishing_boat": { + "category": "ships", + "file": "ships/fishing_boat.glb", + "min": [ + -7.2, + -2.0, + -1.2 + ], + "max": [ + 6.0, + 2.0, + 5.753 + ], + "length": 13.2, + "beam": 4.0, + "clearance": 1.2, + "tris": 2839, + "icon": "boat" + }, + "funicular": { + "category": "transit", + "file": "transit/funicular.glb", + "min": [ + -7.05, + -1.345, + -0.0 + ], + "max": [ + 7.05, + 1.345, + 5.43 + ], + "length": 14.1, + "beam": 2.69, + "clearance": 0.0, + "tris": 308, + "icon": "rail" + }, + "general_cargo": { + "category": "ships", + "file": "ships/general_cargo.glb", + "min": [ + -47.7, + -7.0, + -5.32 + ], + "max": [ + 45.0, + 7.0, + 18.846 + ], + "length": 92.7, + "beam": 14.0, + "clearance": 5.32, + "tris": 2797, + "icon": "ship" + }, + "generic_heli": { + "category": "helicopters", + "file": "helicopters/generic_heli.glb", + "min": [ + -7.37, + -5.5, + -1.365 + ], + "max": [ + 5.927, + 5.5, + 2.28 + ], + "length": 13.297, + "beam": 11.0, + "clearance": 1.365, + "tris": 1272, + "icon": "heli" + }, + "generic_plane": { + "category": "aircraft", + "file": "aircraft/generic_plane.glb", + "min": [ + -18.0, + -16.66, + -2.906 + ], + "max": [ + 18.0, + 16.66, + 7.373 + ], + "length": 36.0, + "beam": 33.32, + "clearance": 2.906, + "tris": 2166, + "icon": "jet" + }, + "generic_vessel": { + "category": "ships", + "file": "ships/generic_vessel.glb", + "min": [ + -21.6, + -4.5, + -2.7 + ], + "max": [ + 20.0, + 4.5, + 11.6 + ], + "length": 41.6, + "beam": 9.0, + "clearance": 2.7, + "tris": 2389, + "icon": "ship" + }, + "glf4": { + "category": "aircraft", + "file": "aircraft/glf4.glb", + "min": [ + -13.46, + -11.79, + -1.189 + ], + "max": [ + 15.73, + 11.79, + 5.022 + ], + "length": 29.19, + "beam": 23.58, + "clearance": 1.189, + "tris": 2474, + "icon": "rear_jet" + }, + "glider": { + "category": "aircraft", + "file": "aircraft/glider.glb", + "min": [ + -3.4, + -7.396, + -0.398 + ], + "max": [ + 3.561, + 7.396, + 1.384 + ], + "length": 6.961, + "beam": 14.793, + "clearance": 0.398, + "tris": 2314, + "icon": "light" + }, + "gondola": { + "category": "transit", + "file": "transit/gondola.glb", + "min": [ + -1.05, + -0.938, + 0.014 + ], + "max": [ + 1.05, + 0.938, + 4.6 + ], + "length": 2.1, + "beam": 1.876, + "clearance": 0.0, + "tris": 282, + "icon": "unknown" + }, + "h47": { + "category": "helicopters", + "file": "helicopters/h47.glb", + "min": [ + -10.3, + -9.151, + -2.588 + ], + "max": [ + 13.921, + 8.103, + 4.78 + ], + "length": 24.221, + "beam": 17.254, + "clearance": 2.588, + "tris": 1430, + "icon": "heli_tandem" + }, + "h60": { + "category": "helicopters", + "file": "helicopters/h60.glb", + "min": [ + -10.774, + -8.18, + -1.765 + ], + "max": [ + 9.13, + 8.18, + 3.265 + ], + "length": 19.904, + "beam": 16.36, + "clearance": 1.765, + "tris": 1560, + "icon": "heli" + }, + "h64": { + "category": "helicopters", + "file": "helicopters/h64.glb", + "min": [ + -9.875, + -7.315, + -1.475 + ], + "max": [ + 8.545, + 7.315, + 2.742 + ], + "length": 18.42, + "beam": 14.63, + "clearance": 1.475, + "tris": 2040, + "icon": "heli" + }, + "high_speed": { + "category": "transit", + "file": "transit/high_speed.glb", + "min": [ + -103.1, + -1.555, + -0.0 + ], + "max": [ + 103.1, + 1.555, + 5.285 + ], + "length": 206.2, + "beam": 3.11, + "clearance": 0.0, + "tris": 2844, + "icon": "rail" + }, + "inland_cargo": { + "category": "ships", + "file": "ships/inland_cargo.glb", + "min": [ + -56.32, + -5.725, + -3.0 + ], + "max": [ + 55.0, + 5.725, + 9.995 + ], + "length": 111.32, + "beam": 11.45, + "clearance": 3.0, + "tris": 3277, + "icon": "ship" + }, + "inland_tanker": { + "category": "ships", + "file": "ships/inland_tanker.glb", + "min": [ + -56.32, + -5.725, + -3.2 + ], + "max": [ + 55.0, + 5.725, + 7.5 + ], + "length": 111.32, + "beam": 11.45, + "clearance": 3.2, + "tris": 2709, + "icon": "tanker" + }, + "intercity": { + "category": "transit", + "file": "transit/intercity.glb", + "min": [ + -91.4, + -1.545, + -0.0 + ], + "max": [ + 91.45, + 1.545, + 5.933 + ], + "length": 182.85, + "beam": 3.09, + "clearance": 0.0, + "tris": 3168, + "icon": "rail" + }, + "k35r": { + "category": "aircraft", + "file": "aircraft/k35r.glb", + "min": [ + -20.765, + -19.541, + -2.478 + ], + "max": [ + 28.186, + 19.541, + 8.482 + ], + "length": 48.951, + "beam": 39.082, + "clearance": 2.478, + "tris": 2626, + "icon": "jet" + }, + "light_rail": { + "category": "transit", + "file": "transit/light_rail.glb", + "min": [ + -14.1, + -1.405, + -0.0 + ], + "max": [ + 14.1, + 1.405, + 5.641 + ], + "length": 28.2, + "beam": 2.81, + "clearance": 0.0, + "tris": 760, + "icon": "tram" + }, + "lng_carrier": { + "category": "ships", + "file": "ships/lng_carrier.glb", + "min": [ + -152.25, + -23.0, + -11.5 + ], + "max": [ + 145.0, + 23.0, + 45.38 + ], + "length": 297.25, + "beam": 46.0, + "clearance": 11.5, + "tris": 2951, + "icon": "tanker" + }, + "md11": { + "category": "aircraft", + "file": "aircraft/md11.glb", + "min": [ + -30.8, + -25.74, + -4.162 + ], + "max": [ + 33.345, + 25.74, + 10.88 + ], + "length": 64.145, + "beam": 51.48, + "clearance": 4.162, + "tris": 2476, + "icon": "widebody" + }, + "metro": { + "category": "transit", + "file": "transit/metro.glb", + "min": [ + -57.55, + -1.53, + -0.0 + ], + "max": [ + 57.55, + 1.53, + 3.691 + ], + "length": 115.1, + "beam": 3.06, + "clearance": 0.0, + "tris": 2226, + "icon": "subway" + }, + "monorail": { + "category": "transit", + "file": "transit/monorail.glb", + "min": [ + -27.75, + -1.53, + 0.0 + ], + "max": [ + 27.75, + 1.53, + 3.587 + ], + "length": 55.5, + "beam": 3.06, + "clearance": 0.0, + "tris": 814, + "icon": "subway" + }, + "motor_yacht": { + "category": "ships", + "file": "ships/motor_yacht.glb", + "min": [ + -9.92, + -2.3, + -1.15 + ], + "max": [ + 9.2, + 2.3, + 5.46 + ], + "length": 19.12, + "beam": 4.6, + "clearance": 1.15, + "tris": 2477, + "icon": "boat" + }, + "mq9": { + "category": "aircraft", + "file": "aircraft/mq9.glb", + "min": [ + -5.5, + -9.8, + -1.616 + ], + "max": [ + 5.85, + 9.8, + 1.582 + ], + "length": 11.35, + "beam": 19.6, + "clearance": 1.616, + "tris": 1936, + "icon": "light" + }, + "p28a": { + "category": "aircraft", + "file": "aircraft/p28a.glb", + "min": [ + -3.901, + -5.228, + -1.341 + ], + "max": [ + 3.877, + 5.228, + 1.801 + ], + "length": 7.778, + "beam": 10.457, + "clearance": 1.341, + "tris": 2136, + "icon": "light" + }, + "patrol": { + "category": "ships", + "file": "ships/patrol.glb", + "min": [ + -36.0, + -4.5, + -2.7 + ], + "max": [ + 30.0, + 4.5, + 19.6 + ], + "length": 66.0, + "beam": 9.0, + "clearance": 2.7, + "tris": 2587, + "icon": "ship" + }, + "pc12": { + "category": "aircraft", + "file": "aircraft/pc12.glb", + "min": [ + -7.62, + -8.053, + -1.435 + ], + "max": [ + 7.3, + 8.053, + 3.396 + ], + "length": 14.92, + "beam": 16.106, + "clearance": 1.435, + "tris": 2292, + "icon": "turboprop" + }, + "pile_green_cone": { + "category": "buoys", + "file": "buoys/pile_green_cone.glb", + "min": [ + -0.35, + -0.35, + -1.5 + ], + "max": [ + 0.35, + 0.35, + 4.72 + ], + "length": 0.7, + "beam": 0.7, + "clearance": 1.5, + "tris": 138, + "icon": "buoy" + }, + "pile_red_cylinder": { + "category": "buoys", + "file": "buoys/pile_red_cylinder.glb", + "min": [ + -0.35, + -0.35, + -1.5 + ], + "max": [ + 0.35, + 0.35, + 4.72 + ], + "length": 0.7, + "beam": 0.7, + "clearance": 1.5, + "tris": 168, + "icon": "buoy" + }, + "pilot_boat": { + "category": "ships", + "file": "ships/pilot_boat.glb", + "min": [ + -10.54, + -2.88, + -1.3 + ], + "max": [ + 8.5, + 2.88, + 8.716 + ], + "length": 19.04, + "beam": 5.76, + "clearance": 1.3, + "tris": 2985, + "icon": "boat" + }, + "product_tanker": { + "category": "ships", + "file": "ships/product_tanker.glb", + "min": [ + -58.76, + -9.5, + -6.46 + ], + "max": [ + 56.5, + 9.5, + 25.672 + ], + "length": 115.26, + "beam": 19.0, + "clearance": 6.46, + "tris": 2995, + "icon": "tanker" + }, + "psv": { + "category": "ships", + "file": "ships/psv.glb", + "min": [ + -45.05, + -9.5, + -6.27 + ], + "max": [ + 42.5, + 9.5, + 24.119 + ], + "length": 87.55, + "beam": 19.0, + "clearance": 6.27, + "tris": 3059, + "icon": "ship" + }, + "pushback": { + "category": "other", + "file": "other/pushback.glb", + "min": [ + -3.45, + -1.398, + 0.025 + ], + "max": [ + 3.05, + 1.398, + 2.14 + ], + "length": 6.5, + "beam": 2.795, + "clearance": 0.0, + "tris": 490, + "icon": "vehicle" + }, + "r44": { + "category": "helicopters", + "file": "helicopters/r44.glb", + "min": [ + -7.116, + -0.744, + -1.14 + ], + "max": [ + 5.079, + 0.744, + 2.03 + ], + "length": 12.195, + "beam": 1.488, + "clearance": 1.14, + "tris": 1172, + "icon": "heli" + }, + "radio_mast": { + "category": "other", + "file": "other/radio_mast.glb", + "min": [ + -0.7, + -0.815, + 0.0 + ], + "max": [ + 1.2, + 0.815, + 11.8 + ], + "length": 1.9, + "beam": 1.63, + "clearance": 0.0, + "tris": 940, + "icon": "vehicle" + }, + "regional_dmu": { + "category": "transit", + "file": "transit/regional_dmu.glb", + "min": [ + -24.75, + -1.53, + -0.0 + ], + "max": [ + 24.75, + 1.53, + 4.36 + ], + "length": 49.5, + "beam": 3.06, + "clearance": 0.0, + "tris": 770, + "icon": "rail" + }, + "river_cruise": { + "category": "ships", + "file": "ships/river_cruise.glb", + "min": [ + -69.12, + -5.7, + -1.8 + ], + "max": [ + 67.5, + 5.7, + 9.9 + ], + "length": 136.62, + "beam": 11.4, + "clearance": 1.8, + "tris": 2675, + "icon": "passenger" + }, + "s76": { + "category": "helicopters", + "file": "helicopters/s76.glb", + "min": [ + -8.949, + -6.705, + -1.525 + ], + "max": [ + 7.428, + 6.705, + 2.776 + ], + "length": 16.377, + "beam": 13.41, + "clearance": 1.525, + "tris": 1356, + "icon": "heli" + }, + "sailboat": { + "category": "ships", + "file": "ships/sailboat.glb", + "min": [ + -7.8, + -2.05, + -2.695 + ], + "max": [ + 6.5, + 2.05, + 18.698 + ], + "length": 14.3, + "beam": 4.1, + "clearance": 2.695, + "tris": 2421, + "icon": "sail" + }, + "spar_lateral_port": { + "category": "buoys", + "file": "buoys/spar_lateral_port.glb", + "min": [ + -0.47, + -0.47, + -1.5 + ], + "max": [ + 0.47, + 0.47, + 3.36 + ], + "length": 0.94, + "beam": 0.94, + "clearance": 1.5, + "tris": 290, + "icon": "buoy" + }, + "spar_lateral_starboard": { + "category": "buoys", + "file": "buoys/spar_lateral_starboard.glb", + "min": [ + -0.47, + -0.47, + -1.5 + ], + "max": [ + 0.47, + 0.47, + 3.36 + ], + "length": 0.94, + "beam": 0.94, + "clearance": 1.5, + "tris": 262, + "icon": "buoy" + }, + "speedboat": { + "category": "ships", + "file": "ships/speedboat.glb", + "min": [ + -4.96, + -1.3, + -0.55 + ], + "max": [ + 4.45, + 1.3, + 2.03 + ], + "length": 9.41, + "beam": 2.6, + "clearance": 0.55, + "tris": 2369, + "icon": "boat" + }, + "spherical_green": { + "category": "buoys", + "file": "buoys/spherical_green.glb", + "min": [ + -0.75, + -0.739, + -0.4 + ], + "max": [ + 0.75, + 0.739, + 1.25 + ], + "length": 1.5, + "beam": 1.477, + "clearance": 0.4, + "tris": 344, + "icon": "buoy" + }, + "spherical_yellow": { + "category": "buoys", + "file": "buoys/spherical_yellow.glb", + "min": [ + -0.75, + -0.739, + -0.4 + ], + "max": [ + 0.75, + 0.739, + 1.25 + ], + "length": 1.5, + "beam": 1.477, + "clearance": 0.4, + "tris": 344, + "icon": "buoy" + }, + "spherical_yellow_x": { + "category": "buoys", + "file": "buoys/spherical_yellow_x.glb", + "min": [ + -0.75, + -0.739, + -0.4 + ], + "max": [ + 0.75, + 0.739, + 2.019 + ], + "length": 1.5, + "beam": 1.477, + "clearance": 0.4, + "tris": 380, + "icon": "buoy" + }, + "sr22": { + "category": "aircraft", + "file": "aircraft/sr22.glb", + "min": [ + -4.3, + -5.723, + -1.325 + ], + "max": [ + 4.124, + 5.723, + 1.765 + ], + "length": 8.424, + "beam": 11.446, + "clearance": 1.325, + "tris": 2428, + "icon": "light" + }, + "stake_green_cone": { + "category": "buoys", + "file": "buoys/stake_green_cone.glb", + "min": [ + -0.198, + -0.198, + -1.5 + ], + "max": [ + 0.198, + 0.198, + 3.63 + ], + "length": 0.396, + "beam": 0.396, + "clearance": 1.5, + "tris": 78, + "icon": "buoy" + }, + "stake_red_cylinder": { + "category": "buoys", + "file": "buoys/stake_red_cylinder.glb", + "min": [ + -0.154, + -0.154, + -1.5 + ], + "max": [ + 0.154, + 0.154, + 3.63 + ], + "length": 0.308, + "beam": 0.308, + "clearance": 1.5, + "tris": 108, + "icon": "buoy" + }, + "stake_yellow_x": { + "category": "buoys", + "file": "buoys/stake_yellow_x.glb", + "min": [ + -0.08, + -0.232, + -1.5 + ], + "max": [ + 0.08, + 0.232, + 3.769 + ], + "length": 0.16, + "beam": 0.463, + "clearance": 1.5, + "tris": 64, + "icon": "buoy" + }, + "superyacht": { + "category": "ships", + "file": "ships/superyacht.glb", + "min": [ + -36.0, + -5.25, + -3.15 + ], + "max": [ + 30.0, + 5.25, + 17.565 + ], + "length": 66.0, + "beam": 10.5, + "clearance": 3.15, + "tris": 2689, + "icon": "passenger" + }, + "t38": { + "category": "aircraft", + "file": "aircraft/t38.glb", + "min": [ + -7.07, + -3.773, + -0.746 + ], + "max": [ + 7.074, + 3.773, + 2.592 + ], + "length": 14.144, + "beam": 7.546, + "clearance": 0.746, + "tris": 2246, + "icon": "fighter" + }, + "tanker": { + "category": "ships", + "file": "ships/tanker.glb", + "min": [ + -130.0, + -22.0, + -14.96 + ], + "max": [ + 125.0, + 22.0, + 35.608 + ], + "length": 255.0, + "beam": 44.0, + "clearance": 14.96, + "tris": 3393, + "icon": "tanker" + }, + "tex2": { + "category": "aircraft", + "file": "aircraft/tex2.glb", + "min": [ + -5.452, + -4.993, + -1.293 + ], + "max": [ + 5.134, + 4.993, + 2.168 + ], + "length": 10.586, + "beam": 9.986, + "clearance": 1.293, + "tris": 2380, + "icon": "turboprop" + }, + "tour_boat": { + "category": "ships", + "file": "ships/tour_boat.glb", + "min": [ + -14.5, + -3.0, + -1.68 + ], + "max": [ + 12.5, + 3.0, + 5.57 + ], + "length": 27.0, + "beam": 6.0, + "clearance": 1.68, + "tris": 2449, + "icon": "boat" + }, + "tower": { + "category": "other", + "file": "other/tower.glb", + "min": [ + -0.696, + -1.135, + -0.016 + ], + "max": [ + 1.296, + 1.135, + 60.6 + ], + "length": 1.992, + "beam": 2.27, + "clearance": 0.016, + "tris": 568, + "icon": "vehicle" + }, + "tram": { + "category": "transit", + "file": "transit/tram.glb", + "min": [ + -15.0, + -1.28, + -0.0 + ], + "max": [ + 15.0, + 1.28, + 5.241 + ], + "length": 30.0, + "beam": 2.56, + "clearance": 0.0, + "tris": 1004, + "icon": "tram" + }, + "trawler": { + "category": "ships", + "file": "ships/trawler.glb", + "min": [ + -12.1, + -6.338, + -2.8 + ], + "max": [ + 11.0, + 6.338, + 12.529 + ], + "length": 23.1, + "beam": 12.676, + "clearance": 2.8, + "tris": 3121, + "icon": "ship" + }, + "trolleybus": { + "category": "transit", + "file": "transit/trolleybus.glb", + "min": [ + -6.05, + -1.32, + -0.0 + ], + "max": [ + 6.05, + 1.355, + 5.656 + ], + "length": 12.1, + "beam": 2.675, + "clearance": 0.0, + "tris": 458, + "icon": "bus" + }, + "tug": { + "category": "ships", + "file": "ships/tug.glb", + "min": [ + -15.8, + -5.35, + -3.7 + ], + "max": [ + 14.4, + 5.35, + 14.1 + ], + "length": 30.2, + "beam": 10.7, + "clearance": 3.7, + "tris": 3661, + "icon": "ship" + }, + "ultralight": { + "category": "aircraft", + "file": "aircraft/ultralight.glb", + "min": [ + -3.51, + -5.243, + -1.217 + ], + "max": [ + 3.6, + 5.243, + 1.644 + ], + "length": 7.11, + "beam": 10.486, + "clearance": 1.217, + "tris": 2068, + "icon": "light" + }, + "v22": { + "category": "aircraft", + "file": "aircraft/v22.glb", + "min": [ + -8.74, + -11.647, + -1.468 + ], + "max": [ + 8.74, + 11.647, + 4.569 + ], + "length": 17.48, + "beam": 23.294, + "clearance": 1.468, + "tris": 2250, + "icon": "turboprop" + }, + "van": { + "category": "other", + "file": "other/van.glb", + "min": [ + -2.76, + -1.22, + 0.018 + ], + "max": [ + 2.76, + 1.22, + 2.56 + ], + "length": 5.52, + "beam": 2.44, + "clearance": 0.0, + "tris": 736, + "icon": "vehicle" + } +} diff --git a/public/models/fleet/helicopters/a139.glb b/public/models/fleet/helicopters/a139.glb new file mode 100644 index 0000000000..f61975dfb6 Binary files /dev/null and b/public/models/fleet/helicopters/a139.glb differ diff --git a/public/models/fleet/helicopters/as50.glb b/public/models/fleet/helicopters/as50.glb new file mode 100644 index 0000000000..597d916e91 Binary files /dev/null and b/public/models/fleet/helicopters/as50.glb differ diff --git a/public/models/fleet/helicopters/b06.glb b/public/models/fleet/helicopters/b06.glb new file mode 100644 index 0000000000..25baa7fa49 Binary files /dev/null and b/public/models/fleet/helicopters/b06.glb differ diff --git a/public/models/fleet/helicopters/b407.glb b/public/models/fleet/helicopters/b407.glb new file mode 100644 index 0000000000..09d67e67e1 Binary files /dev/null and b/public/models/fleet/helicopters/b407.glb differ diff --git a/public/models/fleet/helicopters/ec35.glb b/public/models/fleet/helicopters/ec35.glb new file mode 100644 index 0000000000..c52f3d156e Binary files /dev/null and b/public/models/fleet/helicopters/ec35.glb differ diff --git a/public/models/fleet/helicopters/ec45.glb b/public/models/fleet/helicopters/ec45.glb new file mode 100644 index 0000000000..b9e5cb27ef Binary files /dev/null and b/public/models/fleet/helicopters/ec45.glb differ diff --git a/public/models/fleet/helicopters/generic_heli.glb b/public/models/fleet/helicopters/generic_heli.glb new file mode 100644 index 0000000000..bc8f1a239c Binary files /dev/null and b/public/models/fleet/helicopters/generic_heli.glb differ diff --git a/public/models/fleet/helicopters/h47.glb b/public/models/fleet/helicopters/h47.glb new file mode 100644 index 0000000000..bb2f714261 Binary files /dev/null and b/public/models/fleet/helicopters/h47.glb differ diff --git a/public/models/fleet/helicopters/h60.glb b/public/models/fleet/helicopters/h60.glb new file mode 100644 index 0000000000..45f79180de Binary files /dev/null and b/public/models/fleet/helicopters/h60.glb differ diff --git a/public/models/fleet/helicopters/h64.glb b/public/models/fleet/helicopters/h64.glb new file mode 100644 index 0000000000..3a44d8e50b Binary files /dev/null and b/public/models/fleet/helicopters/h64.glb differ diff --git a/public/models/fleet/helicopters/r44.glb b/public/models/fleet/helicopters/r44.glb new file mode 100644 index 0000000000..845727936a Binary files /dev/null and b/public/models/fleet/helicopters/r44.glb differ diff --git a/public/models/fleet/helicopters/s76.glb b/public/models/fleet/helicopters/s76.glb new file mode 100644 index 0000000000..a773aba73f Binary files /dev/null and b/public/models/fleet/helicopters/s76.glb differ diff --git a/public/models/fleet/other/balloon.glb b/public/models/fleet/other/balloon.glb new file mode 100644 index 0000000000..016ad0719b Binary files /dev/null and b/public/models/fleet/other/balloon.glb differ diff --git a/public/models/fleet/other/blimp.glb b/public/models/fleet/other/blimp.glb new file mode 100644 index 0000000000..3aba8e86ba Binary files /dev/null and b/public/models/fleet/other/blimp.glb differ diff --git a/public/models/fleet/other/car.glb b/public/models/fleet/other/car.glb new file mode 100644 index 0000000000..80f50d967c Binary files /dev/null and b/public/models/fleet/other/car.glb differ diff --git a/public/models/fleet/other/fire_truck.glb b/public/models/fleet/other/fire_truck.glb new file mode 100644 index 0000000000..47cb6d2459 Binary files /dev/null and b/public/models/fleet/other/fire_truck.glb differ diff --git a/public/models/fleet/other/pushback.glb b/public/models/fleet/other/pushback.glb new file mode 100644 index 0000000000..565ce426c2 Binary files /dev/null and b/public/models/fleet/other/pushback.glb differ diff --git a/public/models/fleet/other/radio_mast.glb b/public/models/fleet/other/radio_mast.glb new file mode 100644 index 0000000000..1242c7d411 Binary files /dev/null and b/public/models/fleet/other/radio_mast.glb differ diff --git a/public/models/fleet/other/tower.glb b/public/models/fleet/other/tower.glb new file mode 100644 index 0000000000..39ff5c990a Binary files /dev/null and b/public/models/fleet/other/tower.glb differ diff --git a/public/models/fleet/other/van.glb b/public/models/fleet/other/van.glb new file mode 100644 index 0000000000..0b79e1db6f Binary files /dev/null and b/public/models/fleet/other/van.glb differ diff --git a/public/models/fleet/ships/bulk_carrier.glb b/public/models/fleet/ships/bulk_carrier.glb new file mode 100644 index 0000000000..3fe73d3bfb Binary files /dev/null and b/public/models/fleet/ships/bulk_carrier.glb differ diff --git a/public/models/fleet/ships/car_carrier.glb b/public/models/fleet/ships/car_carrier.glb new file mode 100644 index 0000000000..04ad3e7790 Binary files /dev/null and b/public/models/fleet/ships/car_carrier.glb differ diff --git a/public/models/fleet/ships/container_ship.glb b/public/models/fleet/ships/container_ship.glb new file mode 100644 index 0000000000..f8686176b2 Binary files /dev/null and b/public/models/fleet/ships/container_ship.glb differ diff --git a/public/models/fleet/ships/cruise_ship.glb b/public/models/fleet/ships/cruise_ship.glb new file mode 100644 index 0000000000..d2dcfd88e8 Binary files /dev/null and b/public/models/fleet/ships/cruise_ship.glb differ diff --git a/public/models/fleet/ships/dredger.glb b/public/models/fleet/ships/dredger.glb new file mode 100644 index 0000000000..4d9ab52647 Binary files /dev/null and b/public/models/fleet/ships/dredger.glb differ diff --git a/public/models/fleet/ships/fast_ferry.glb b/public/models/fleet/ships/fast_ferry.glb new file mode 100644 index 0000000000..65b008200c Binary files /dev/null and b/public/models/fleet/ships/fast_ferry.glb differ diff --git a/public/models/fleet/ships/feeder.glb b/public/models/fleet/ships/feeder.glb new file mode 100644 index 0000000000..1c40203bf6 Binary files /dev/null and b/public/models/fleet/ships/feeder.glb differ diff --git a/public/models/fleet/ships/ferry.glb b/public/models/fleet/ships/ferry.glb new file mode 100644 index 0000000000..fcaa48abcc Binary files /dev/null and b/public/models/fleet/ships/ferry.glb differ diff --git a/public/models/fleet/ships/fishing_boat.glb b/public/models/fleet/ships/fishing_boat.glb new file mode 100644 index 0000000000..084f5dd3b6 Binary files /dev/null and b/public/models/fleet/ships/fishing_boat.glb differ diff --git a/public/models/fleet/ships/general_cargo.glb b/public/models/fleet/ships/general_cargo.glb new file mode 100644 index 0000000000..0cd1cd4cd4 Binary files /dev/null and b/public/models/fleet/ships/general_cargo.glb differ diff --git a/public/models/fleet/ships/generic_vessel.glb b/public/models/fleet/ships/generic_vessel.glb new file mode 100644 index 0000000000..e8c7485445 Binary files /dev/null and b/public/models/fleet/ships/generic_vessel.glb differ diff --git a/public/models/fleet/ships/inland_cargo.glb b/public/models/fleet/ships/inland_cargo.glb new file mode 100644 index 0000000000..9f9facc4ab Binary files /dev/null and b/public/models/fleet/ships/inland_cargo.glb differ diff --git a/public/models/fleet/ships/inland_tanker.glb b/public/models/fleet/ships/inland_tanker.glb new file mode 100644 index 0000000000..db46c2476b Binary files /dev/null and b/public/models/fleet/ships/inland_tanker.glb differ diff --git a/public/models/fleet/ships/lng_carrier.glb b/public/models/fleet/ships/lng_carrier.glb new file mode 100644 index 0000000000..d06330645d Binary files /dev/null and b/public/models/fleet/ships/lng_carrier.glb differ diff --git a/public/models/fleet/ships/motor_yacht.glb b/public/models/fleet/ships/motor_yacht.glb new file mode 100644 index 0000000000..d7283750a0 Binary files /dev/null and b/public/models/fleet/ships/motor_yacht.glb differ diff --git a/public/models/fleet/ships/patrol.glb b/public/models/fleet/ships/patrol.glb new file mode 100644 index 0000000000..6b3352e111 Binary files /dev/null and b/public/models/fleet/ships/patrol.glb differ diff --git a/public/models/fleet/ships/pilot_boat.glb b/public/models/fleet/ships/pilot_boat.glb new file mode 100644 index 0000000000..f4197ab0fb Binary files /dev/null and b/public/models/fleet/ships/pilot_boat.glb differ diff --git a/public/models/fleet/ships/product_tanker.glb b/public/models/fleet/ships/product_tanker.glb new file mode 100644 index 0000000000..6e31083d35 Binary files /dev/null and b/public/models/fleet/ships/product_tanker.glb differ diff --git a/public/models/fleet/ships/psv.glb b/public/models/fleet/ships/psv.glb new file mode 100644 index 0000000000..d943978ec2 Binary files /dev/null and b/public/models/fleet/ships/psv.glb differ diff --git a/public/models/fleet/ships/river_cruise.glb b/public/models/fleet/ships/river_cruise.glb new file mode 100644 index 0000000000..2da8589f0a Binary files /dev/null and b/public/models/fleet/ships/river_cruise.glb differ diff --git a/public/models/fleet/ships/sailboat.glb b/public/models/fleet/ships/sailboat.glb new file mode 100644 index 0000000000..51ae8818f0 Binary files /dev/null and b/public/models/fleet/ships/sailboat.glb differ diff --git a/public/models/fleet/ships/speedboat.glb b/public/models/fleet/ships/speedboat.glb new file mode 100644 index 0000000000..eda10fb84b Binary files /dev/null and b/public/models/fleet/ships/speedboat.glb differ diff --git a/public/models/fleet/ships/superyacht.glb b/public/models/fleet/ships/superyacht.glb new file mode 100644 index 0000000000..012e69dd38 Binary files /dev/null and b/public/models/fleet/ships/superyacht.glb differ diff --git a/public/models/fleet/ships/tanker.glb b/public/models/fleet/ships/tanker.glb new file mode 100644 index 0000000000..68de5a0013 Binary files /dev/null and b/public/models/fleet/ships/tanker.glb differ diff --git a/public/models/fleet/ships/tour_boat.glb b/public/models/fleet/ships/tour_boat.glb new file mode 100644 index 0000000000..22ee9cb430 Binary files /dev/null and b/public/models/fleet/ships/tour_boat.glb differ diff --git a/public/models/fleet/ships/trawler.glb b/public/models/fleet/ships/trawler.glb new file mode 100644 index 0000000000..bb8651f2cb Binary files /dev/null and b/public/models/fleet/ships/trawler.glb differ diff --git a/public/models/fleet/ships/tug.glb b/public/models/fleet/ships/tug.glb new file mode 100644 index 0000000000..f20e72b6b4 Binary files /dev/null and b/public/models/fleet/ships/tug.glb differ diff --git a/public/models/fleet/transit/articulated_bus.glb b/public/models/fleet/transit/articulated_bus.glb new file mode 100644 index 0000000000..4b10d2ef07 Binary files /dev/null and b/public/models/fleet/transit/articulated_bus.glb differ diff --git a/public/models/fleet/transit/cable_tram.glb b/public/models/fleet/transit/cable_tram.glb new file mode 100644 index 0000000000..10b12a3eec Binary files /dev/null and b/public/models/fleet/transit/cable_tram.glb differ diff --git a/public/models/fleet/transit/city_bus.glb b/public/models/fleet/transit/city_bus.glb new file mode 100644 index 0000000000..4e2b1dc8a9 Binary files /dev/null and b/public/models/fleet/transit/city_bus.glb differ diff --git a/public/models/fleet/transit/coach.glb b/public/models/fleet/transit/coach.glb new file mode 100644 index 0000000000..00e23f7f5d Binary files /dev/null and b/public/models/fleet/transit/coach.glb differ diff --git a/public/models/fleet/transit/commuter_emu.glb b/public/models/fleet/transit/commuter_emu.glb new file mode 100644 index 0000000000..e53f0a1bee Binary files /dev/null and b/public/models/fleet/transit/commuter_emu.glb differ diff --git a/public/models/fleet/transit/double_decker.glb b/public/models/fleet/transit/double_decker.glb new file mode 100644 index 0000000000..416bd2cbcf Binary files /dev/null and b/public/models/fleet/transit/double_decker.glb differ diff --git a/public/models/fleet/transit/funicular.glb b/public/models/fleet/transit/funicular.glb new file mode 100644 index 0000000000..4b14d66225 Binary files /dev/null and b/public/models/fleet/transit/funicular.glb differ diff --git a/public/models/fleet/transit/gondola.glb b/public/models/fleet/transit/gondola.glb new file mode 100644 index 0000000000..530ccb4485 Binary files /dev/null and b/public/models/fleet/transit/gondola.glb differ diff --git a/public/models/fleet/transit/high_speed.glb b/public/models/fleet/transit/high_speed.glb new file mode 100644 index 0000000000..c3f09d0948 Binary files /dev/null and b/public/models/fleet/transit/high_speed.glb differ diff --git a/public/models/fleet/transit/intercity.glb b/public/models/fleet/transit/intercity.glb new file mode 100644 index 0000000000..2845594ec9 Binary files /dev/null and b/public/models/fleet/transit/intercity.glb differ diff --git a/public/models/fleet/transit/light_rail.glb b/public/models/fleet/transit/light_rail.glb new file mode 100644 index 0000000000..22f80d1970 Binary files /dev/null and b/public/models/fleet/transit/light_rail.glb differ diff --git a/public/models/fleet/transit/metro.glb b/public/models/fleet/transit/metro.glb new file mode 100644 index 0000000000..6154049b95 Binary files /dev/null and b/public/models/fleet/transit/metro.glb differ diff --git a/public/models/fleet/transit/monorail.glb b/public/models/fleet/transit/monorail.glb new file mode 100644 index 0000000000..a8dab0f07f Binary files /dev/null and b/public/models/fleet/transit/monorail.glb differ diff --git a/public/models/fleet/transit/regional_dmu.glb b/public/models/fleet/transit/regional_dmu.glb new file mode 100644 index 0000000000..1a091e2d60 Binary files /dev/null and b/public/models/fleet/transit/regional_dmu.glb differ diff --git a/public/models/fleet/transit/tram.glb b/public/models/fleet/transit/tram.glb new file mode 100644 index 0000000000..514cff4360 Binary files /dev/null and b/public/models/fleet/transit/tram.glb differ diff --git a/public/models/fleet/transit/trolleybus.glb b/public/models/fleet/transit/trolleybus.glb new file mode 100644 index 0000000000..a7691b71e7 Binary files /dev/null and b/public/models/fleet/transit/trolleybus.glb differ diff --git a/public/models/fleet/types.json b/public/models/fleet/types.json new file mode 100644 index 0000000000..2b2388bb19 --- /dev/null +++ b/public/models/fleet/types.json @@ -0,0 +1,2037 @@ +{ + "aircraft": { + "A320": [ + "a320", + 37.57 + ], + "A20N": [ + "a320", + 37.57 + ], + "A319": [ + "a320", + 33.84 + ], + "A19N": [ + "a320", + 33.84 + ], + "A321": [ + "a320", + 44.51 + ], + "A21N": [ + "a320", + 44.51 + ], + "A318": [ + "a320", + 31.44 + ], + "B738": [ + "b738", + 39.47 + ], + "B38M": [ + "b738", + 39.52 + ], + "B737": [ + "b738", + 33.63 + ], + "B37M": [ + "b738", + 35.56 + ], + "B739": [ + "b738", + 42.11 + ], + "B39M": [ + "b738", + 42.16 + ], + "B736": [ + "b738", + 31.24 + ], + "B733": [ + "b738", + 33.4 + ], + "B734": [ + "b738", + 36.4 + ], + "B735": [ + "b738", + 31.0 + ], + "B752": [ + "b738", + 47.32 + ], + "B753": [ + "b738", + 54.4 + ], + "P8": [ + "b738", + 39.47 + ], + "BCS3": [ + "bcs3", + 38.7 + ], + "BCS1": [ + "bcs3", + 35.0 + ], + "E75L": [ + "e175", + 31.68 + ], + "E75S": [ + "e175", + 31.68 + ], + "E170": [ + "e175", + 29.9 + ], + "E190": [ + "e175", + 36.24 + ], + "E195": [ + "e175", + 38.65 + ], + "E290": [ + "e175", + 36.2 + ], + "E295": [ + "e175", + 41.5 + ], + "CRJ9": [ + "crj9", + 36.2 + ], + "CRJ7": [ + "crj9", + 32.5 + ], + "CRJ2": [ + "crj9", + 26.77 + ], + "CRJX": [ + "crj9", + 39.1 + ], + "E145": [ + "crj9", + 29.87 + ], + "E135": [ + "crj9", + 26.33 + ], + "E35L": [ + "crj9", + 26.33 + ], + "B789": [ + "b789", + 62.8 + ], + "B788": [ + "b789", + 56.7 + ], + "B78X": [ + "b789", + 68.3 + ], + "A359": [ + "a359", + 66.8 + ], + "A35K": [ + "a359", + 73.8 + ], + "B77W": [ + "b77w", + 73.9 + ], + "B77L": [ + "b77w", + 63.7 + ], + "B772": [ + "b77w", + 63.7 + ], + "B773": [ + "b77w", + 73.9 + ], + "B778": [ + "b77w", + 70.9 + ], + "B779": [ + "b77w", + 76.7 + ], + "B763": [ + "b763", + 54.9 + ], + "B762": [ + "b763", + 48.5 + ], + "B764": [ + "b763", + 61.4 + ], + "A333": [ + "a333", + 63.69 + ], + "A332": [ + "a333", + 58.82 + ], + "A339": [ + "a333", + 63.66 + ], + "A338": [ + "a333", + 58.82 + ], + "DH8D": [ + "dh8d", + 32.8 + ], + "DH8C": [ + "dh8d", + 25.7 + ], + "DH8A": [ + "dh8d", + 22.25 + ], + "DH8B": [ + "dh8d", + 22.25 + ], + "AT72": [ + "at72", + 27.17 + ], + "AT76": [ + "at72", + 27.17 + ], + "AT75": [ + "at72", + 27.17 + ], + "AT45": [ + "at72", + 22.67 + ], + "AT43": [ + "at72", + 22.67 + ], + "AT46": [ + "at72", + 22.67 + ], + "E55P": [ + "e55p", + 15.9 + ], + "E545": [ + "e55p", + 19.7 + ], + "E550": [ + "e55p", + 20.7 + ], + "E50P": [ + "e55p", + 12.8 + ], + "LJ45": [ + "e55p", + 17.7 + ], + "LJ75": [ + "e55p", + 17.7 + ], + "LJ35": [ + "e55p", + 14.83 + ], + "LJ60": [ + "e55p", + 17.9 + ], + "C25B": [ + "e55p", + 15.6 + ], + "C25A": [ + "e55p", + 14.5 + ], + "C525": [ + "e55p", + 13.0 + ], + "C25C": [ + "e55p", + 16.3 + ], + "C680": [ + "e55p", + 19.4 + ], + "C68A": [ + "e55p", + 19.7 + ], + "C700": [ + "e55p", + 22.3 + ], + "HDJT": [ + "e55p", + 13.0 + ], + "PC24": [ + "e55p", + 16.85 + ], + "C56X": [ + "c56x", + 15.79 + ], + "C560": [ + "c56x", + 14.9 + ], + "C550": [ + "c56x", + 14.4 + ], + "C510": [ + "c56x", + 12.4 + ], + "C750": [ + "c56x", + 22.0 + ], + "C501": [ + "c56x", + 13.3 + ], + "CL35": [ + "cl35", + 20.92 + ], + "CL30": [ + "cl35", + 20.92 + ], + "CL60": [ + "cl35", + 20.85 + ], + "F2TH": [ + "cl35", + 20.2 + ], + "FA50": [ + "cl35", + 18.5 + ], + "F900": [ + "cl35", + 20.2 + ], + "FA7X": [ + "cl35", + 23.2 + ], + "FA8X": [ + "cl35", + 24.5 + ], + "G280": [ + "cl35", + 20.3 + ], + "H25B": [ + "cl35", + 15.6 + ], + "GLF4": [ + "glf4", + 26.92 + ], + "GLF5": [ + "glf4", + 29.4 + ], + "GLF6": [ + "glf4", + 30.4 + ], + "GLEX": [ + "glf4", + 30.3 + ], + "GL5T": [ + "glf4", + 29.5 + ], + "GL7T": [ + "glf4", + 33.8 + ], + "GA6C": [ + "glf4", + 30.4 + ], + "C172": [ + "c172", + 8.28 + ], + "C182": [ + "c172", + 8.84 + ], + "C152": [ + "c172", + 7.34 + ], + "C150": [ + "c172", + 7.29 + ], + "C72R": [ + "c172", + 8.28 + ], + "C206": [ + "c172", + 8.61 + ], + "C210": [ + "c172", + 8.59 + ], + "C208": [ + "c172", + 11.46 + ], + "C170": [ + "c172", + 7.6 + ], + "C180": [ + "c172", + 7.8 + ], + "C177": [ + "c172", + 8.4 + ], + "P28A": [ + "p28a", + 7.25 + ], + "P28R": [ + "p28a", + 7.5 + ], + "P28B": [ + "p28a", + 7.5 + ], + "PA46": [ + "p28a", + 8.8 + ], + "DA40": [ + "p28a", + 8.06 + ], + "BE36": [ + "p28a", + 8.38 + ], + "BE35": [ + "p28a", + 8.0 + ], + "M20P": [ + "p28a", + 7.52 + ], + "M20T": [ + "p28a", + 8.15 + ], + "P32R": [ + "p28a", + 8.4 + ], + "BE33": [ + "p28a", + 7.7 + ], + "RV7": [ + "p28a", + 6.2 + ], + "RV8": [ + "p28a", + 6.3 + ], + "GLAS": [ + "p28a", + 6.0 + ], + "PA18": [ + "p28a", + 6.9 + ], + "SR22": [ + "sr22", + 7.92 + ], + "SR20": [ + "sr22", + 7.92 + ], + "S22T": [ + "sr22", + 7.92 + ], + "COL4": [ + "sr22", + 7.7 + ], + "DA20": [ + "sr22", + 7.2 + ], + "PC12": [ + "pc12", + 14.4 + ], + "TBM7": [ + "pc12", + 10.7 + ], + "TBM8": [ + "pc12", + 10.7 + ], + "TBM9": [ + "pc12", + 10.7 + ], + "P46T": [ + "pc12", + 9.0 + ], + "BE20": [ + "be20", + 13.34 + ], + "BE9L": [ + "be20", + 10.82 + ], + "B350": [ + "be20", + 14.22 + ], + "BE30": [ + "be20", + 13.34 + ], + "PA31": [ + "be20", + 10.55 + ], + "BE58": [ + "be20", + 9.09 + ], + "PA44": [ + "be20", + 8.41 + ], + "DA42": [ + "be20", + 8.56 + ], + "PA34": [ + "be20", + 8.72 + ], + "C414": [ + "be20", + 11.1 + ], + "C421": [ + "be20", + 11.1 + ], + "C310": [ + "be20", + 9.7 + ], + "BE55": [ + "be20", + 8.5 + ], + "P180": [ + "be20", + 14.4 + ], + "TEX2": [ + "tex2", + 10.16 + ], + "PC21": [ + "tex2", + 11.2 + ], + "PC9": [ + "tex2", + 10.1 + ], + "PC7": [ + "tex2", + 9.8 + ], + "T6": [ + "tex2", + 8.8 + ], + "T38": [ + "t38", + 14.14 + ], + "HAWK": [ + "t38", + 12.43 + ], + "F16": [ + "t38", + 15.06 + ], + "F18": [ + "t38", + 17.1 + ], + "F18S": [ + "t38", + 18.31 + ], + "F35": [ + "t38", + 15.7 + ], + "F15": [ + "t38", + 19.43 + ], + "EUFI": [ + "t38", + 15.96 + ], + "F22": [ + "t38", + 18.9 + ], + "T45": [ + "t38", + 11.99 + ], + "M346": [ + "t38", + 11.49 + ], + "C30J": [ + "c30j", + 34.36 + ], + "C130": [ + "c30j", + 29.79 + ], + "A400": [ + "c30j", + 45.1 + ], + "C17": [ + "c17", + 53.04 + ], + "K35R": [ + "k35r", + 41.53 + ], + "E3TF": [ + "k35r", + 46.61 + ], + "E3CF": [ + "k35r", + 46.61 + ], + "B744": [ + "b744", + 70.66 + ], + "B748": [ + "b744", + 76.3 + ], + "B742": [ + "b744", + 70.66 + ], + "B74S": [ + "b744", + 56.3 + ], + "A388": [ + "a388", + 72.72 + ], + "B712": [ + "crj9", + 37.8 + ], + "MD82": [ + "crj9", + 45.0 + ], + "MD83": [ + "crj9", + 45.0 + ], + "MD88": [ + "crj9", + 45.0 + ], + "MD87": [ + "crj9", + 39.75 + ], + "A306": [ + "a333", + 54.08 + ], + "A310": [ + "a333", + 46.66 + ], + "T206": [ + "c172", + 8.61 + ], + "C82T": [ + "c172", + 8.84 + ], + "C82S": [ + "c172", + 8.84 + ], + "C82R": [ + "c172", + 8.84 + ], + "DV20": [ + "sr22", + 7.3 + ], + "PA32": [ + "p28a", + 8.2 + ], + "PA24": [ + "p28a", + 7.6 + ], + "AA5": [ + "p28a", + 6.7 + ], + "RV12": [ + "p28a", + 6.2 + ], + "EPIC": [ + "pc12", + 10.8 + ], + "C402": [ + "be20", + 11.1 + ], + "BE95": [ + "be20", + 7.8 + ], + "PA30": [ + "be20", + 7.7 + ], + "SF34": [ + "at72", + 19.73 + ], + "BE40": [ + "e55p", + 14.8 + ], + "GALX": [ + "cl35", + 18.97 + ], + "GA5C": [ + "p28a", + 6.7 + ], + "MD11": [ + "md11", + 61.6 + ], + "DC10": [ + "md11", + 55.5 + ], + "L101": [ + "md11", + 54.2 + ], + "A343": [ + "a343", + 63.69 + ], + "A346": [ + "a343", + 75.36 + ], + "A342": [ + "a343", + 59.4 + ], + "A345": [ + "a343", + 67.9 + ], + "GLID": [ + "glider", + 6.8 + ], + "GLIM": [ + "glider", + 7.0 + ], + "DRON": [ + "mq9", + 11.0 + ], + "Q9": [ + "mq9", + 11.0 + ], + "Q4": [ + "mq9", + 14.5 + ], + "Q1": [ + "mq9", + 8.2 + ], + "PIAT": [ + "ultralight", + 6.5 + ], + "PIVI": [ + "ultralight", + 6.5 + ], + "ULAC": [ + "ultralight", + 6.0 + ], + "E45X": [ + "crj9", + 29.87 + ], + "SB20": [ + "at72", + 27.28 + ], + "C500": [ + "c56x", + 13.26 + ], + "BE50": [ + "be20", + 9.6 + ], + "AC68": [ + "be20", + 13.1 + ], + "B190": [ + "be20", + 17.63 + ], + "FA6X": [ + "cl35", + 25.7 + ], + "FA20": [ + "cl35", + 17.15 + ], + "T204": [ + "b738", + 46.1 + ], + "GA7": [ + "be20", + 9.1 + ], + "C320": [ + "be20", + 10.0 + ], + "SLG4": [ + "glider", + 6.5 + ], + "SLG2": [ + "glider", + 6.5 + ], + "SF50": [ + "sr22", + 9.4 + ], + "T210": [ + "c172", + 8.6 + ], + "PA23": [ + "be20", + 8.8 + ], + "BE23": [ + "p28a", + 7.8 + ], + "RV6": [ + "p28a", + 6.1 + ], + "CH7B": [ + "ultralight", + 6.6 + ], + "BT7": [ + "tex2", + 9.6 + ], + "TB30": [ + "tex2", + 7.6 + ], + "IL62": [ + "md11", + 53.1 + ], + "BALL": [ + "balloon", + 17.0 + ], + "SHIP": [ + "blimp", + 75.0 + ], + "ZVEH": [ + "car", + 4.61 + ], + "GRND": [ + "radio_mast", + 1.9 + ] + }, + "helicopters": { + "R44": [ + "r44", + 9.07 + ], + "R22": [ + "r44", + 6.3 + ], + "R66": [ + "r44", + 9.2 + ], + "H500": [ + "r44", + 7.0 + ], + "H269": [ + "r44", + 6.8 + ], + "B06": [ + "b06", + 9.5 + ], + "B505": [ + "b06", + 9.6 + ], + "B206": [ + "b06", + 9.5 + ], + "B407": [ + "b407", + 10.6 + ], + "B212": [ + "b407", + 12.9 + ], + "B412": [ + "b407", + 12.9 + ], + "UH1": [ + "b407", + 12.8 + ], + "AS50": [ + "as50", + 10.93 + ], + "EC30": [ + "as50", + 10.68 + ], + "A119": [ + "as50", + 11.1 + ], + "AS55": [ + "as50", + 10.93 + ], + "EC35": [ + "ec35", + 10.2 + ], + "B429": [ + "ec35", + 11.3 + ], + "EC45": [ + "ec45", + 11.6 + ], + "B105": [ + "ec45", + 8.8 + ], + "A139": [ + "a139", + 13.77 + ], + "A169": [ + "a139", + 12.1 + ], + "A109": [ + "a139", + 11.4 + ], + "A189": [ + "a139", + 14.6 + ], + "S76": [ + "s76", + 13.2 + ], + "AS65": [ + "s76", + 11.6 + ], + "EC55": [ + "s76", + 12.1 + ], + "LYNX": [ + "s76", + 12.0 + ], + "EC75": [ + "s76", + 13.7 + ], + "H60": [ + "h60", + 15.26 + ], + "S92": [ + "h60", + 17.1 + ], + "EH10": [ + "h60", + 19.5 + ], + "NH90": [ + "h60", + 16.1 + ], + "H47": [ + "h47", + 15.46 + ], + "H64": [ + "h64", + 15.06 + ], + "H1": [ + "h64", + 13.6 + ], + "TIGR": [ + "h64", + 14.0 + ], + "V22": [ + "v22", + 17.48 + ], + "GYRO": [ + "r44", + 5.0 + ] + }, + "aircraft_callsign": { + "ZVEH": [ + { + "prefixes": [ + "FIRE" + ], + "model": "fire_truck", + "length": 11.01 + }, + { + "prefixes": [ + "PUSH", + "TUG" + ], + "model": "pushback", + "length": 6.0 + }, + { + "prefixes": [ + "DEICER", + "SQUID", + "SQB" + ], + "model": "van", + "length": 5.51 + } + ] + }, + "vessels": [ + { + "types": [ + 70, + 79 + ], + "typical_len": 300, + "rules": [ + { + "min_len": 70, + "max_len": 140, + "max_bl": 0.12, + "model": "inland_cargo" + }, + { + "name_re": "\\b(LEADER|HIGHWAY|ACE|GLOVIS|HOEGH|SPIRIT OF)\\b", + "min_len": 150, + "model": "car_carrier" + }, + { + "min_len": 250, + "model": "container_ship" + }, + { + "min_len": 160, + "max_bl": 0.145, + "model": "container_ship" + }, + { + "min_len": 160, + "model": "bulk_carrier" + }, + { + "min_len": 120, + "model": "feeder" + }, + { + "model": "general_cargo" + } + ] + }, + { + "types": [ + 80, + 89 + ], + "typical_len": 250, + "rules": [ + { + "name_re": "\\bLNG\\b|\\bGAS\\b", + "min_len": 150, + "model": "lng_carrier" + }, + { + "min_len": 70, + "max_len": 140, + "max_bl": 0.12, + "model": "inland_tanker" + }, + { + "min_len": 180, + "model": "tanker" + }, + { + "model": "product_tanker" + } + ] + }, + { + "types": [ + 60, + 69 + ], + "typical_len": 140, + "rules": [ + { + "min_len": 70, + "max_len": 140, + "max_bl": 0.12, + "model": "river_cruise" + }, + { + "min_len": 200, + "model": "cruise_ship" + }, + { + "min_len": 40, + "model": "ferry" + }, + { + "min_len": 15, + "model": "tour_boat" + }, + { + "model": "speedboat" + } + ] + }, + { + "types": [ + 37, + 37 + ], + "typical_len": 19, + "rules": [ + { + "min_len": 35, + "model": "superyacht" + }, + { + "min_len": 12, + "model": "motor_yacht" + }, + { + "model": "speedboat" + } + ] + }, + { + "types": [ + 36, + 36 + ], + "rules": [ + { + "model": "sailboat" + } + ] + }, + { + "types": [ + 30, + 30 + ], + "typical_len": 24, + "rules": [ + { + "min_len": 15, + "model": "trawler" + }, + { + "model": "fishing_boat" + } + ] + }, + { + "types": [ + 31, + 32 + ], + "rules": [ + { + "model": "tug" + } + ] + }, + { + "types": [ + 52, + 52 + ], + "rules": [ + { + "model": "tug" + } + ] + }, + { + "types": [ + 50, + 51 + ], + "rules": [ + { + "model": "pilot_boat" + } + ] + }, + { + "types": [ + 53, + 54 + ], + "rules": [ + { + "model": "pilot_boat" + } + ] + }, + { + "types": [ + 35, + 35 + ], + "rules": [ + { + "model": "patrol" + } + ] + }, + { + "types": [ + 55, + 55 + ], + "typical_len": 40, + "rules": [ + { + "min_len": 25, + "model": "patrol" + }, + { + "model": "pilot_boat" + } + ] + }, + { + "types": [ + 40, + 49 + ], + "typical_len": 40, + "rules": [ + { + "min_len": 20, + "model": "fast_ferry" + }, + { + "model": "speedboat" + } + ] + }, + { + "types": [ + 33, + 33 + ], + "typical_len": 100, + "rules": [ + { + "min_len": 50, + "model": "dredger" + }, + { + "model": "tug" + } + ] + }, + { + "types": [ + 0, + 99 + ], + "rules": [ + { + "min_len": 70, + "max_len": 140, + "max_bl": 0.12, + "model": "inland_cargo" + }, + { + "model": "generic_vessel" + } + ] + } + ], + "categories": { + "A1": [ + "c172", + 8.3 + ], + "A2": [ + "be20", + 14.0 + ], + "A3": [ + "a320", + 37.6 + ], + "A4": [ + "b738", + 47.3 + ], + "A5": [ + "b77w", + 70.0 + ], + "A6": [ + "t38", + 15.0 + ], + "A7": [ + "generic_heli", + 11.0 + ], + "B1": [ + "glider", + 6.8 + ], + "B2": [ + "balloon", + 17.0 + ], + "B3": [ + "ultralight", + 5.0 + ], + "B4": [ + "ultralight", + 6.5 + ], + "B6": [ + "mq9", + 11.0 + ], + "B7": [ + "ultralight", + 4.0 + ], + "C1": [ + "fire_truck", + 11.0 + ], + "C2": [ + "van", + 5.5 + ], + "C3": [ + "tower", + 60.0 + ], + "C4": [ + "tower", + 60.0 + ], + "C5": [ + "tower", + 60.0 + ], + "A0": [ + "generic_plane", + 36.0 + ] + }, + "default_aircraft": [ + "generic_plane", + 36.0 + ], + "default_vessel": "generic_vessel", + "transit": { + "modes": { + "bus": [ + "city_bus", + 12.0 + ], + "articulated_bus": [ + "articulated_bus", + 18.0 + ], + "double_decker": [ + "double_decker", + 11.0 + ], + "trolleybus": [ + "trolleybus", + 12.0 + ], + "coach": [ + "coach", + 13.0 + ], + "tram": [ + "tram", + 30.0 + ], + "light_rail": [ + "light_rail", + 28.2 + ], + "cable_tram": [ + "cable_tram", + 8.4 + ], + "subway": [ + "metro", + 115.0 + ], + "metro": [ + "metro", + 115.0 + ], + "monorail": [ + "monorail", + 55.5 + ], + "rail": [ + "commuter_emu", + 98.1 + ], + "commuter": [ + "commuter_emu", + 98.1 + ], + "regional": [ + "regional_dmu", + 49.5 + ], + "intercity": [ + "intercity", + 182.8 + ], + "high_speed": [ + "high_speed", + 206.2 + ], + "ferry": [ + "fast_ferry", + 40.0 + ], + "aerial_lift": [ + "gondola", + 2.1 + ], + "gondola": [ + "gondola", + 2.1 + ], + "funicular": [ + "funicular", + 14.0 + ] + }, + "route_types": { + "0": [ + "tram", + 30.0 + ], + "1": [ + "metro", + 115.0 + ], + "2": [ + "commuter_emu", + 98.1 + ], + "3": [ + "city_bus", + 12.0 + ], + "4": [ + "fast_ferry", + 40.0 + ], + "5": [ + "cable_tram", + 8.4 + ], + "6": [ + "gondola", + 2.1 + ], + "7": [ + "funicular", + 14.0 + ], + "11": [ + "trolleybus", + 12.0 + ], + "12": [ + "monorail", + 55.5 + ], + "100": [ + "intercity", + 182.8 + ], + "101": [ + "high_speed", + 206.2 + ], + "102": [ + "intercity", + 182.8 + ], + "103": [ + "intercity", + 182.8 + ], + "104": [ + "intercity", + 182.8 + ], + "105": [ + "intercity", + 182.8 + ], + "106": [ + "regional_dmu", + 49.5 + ], + "107": [ + "regional_dmu", + 49.5 + ], + "108": [ + "metro", + 115.0 + ], + "109": [ + "commuter_emu", + 98.1 + ], + "110": [ + "regional_dmu", + 49.5 + ], + "111": [ + "intercity", + 182.8 + ], + "112": [ + "intercity", + 182.8 + ], + "113": [ + "intercity", + 182.8 + ], + "114": [ + "intercity", + 182.8 + ], + "115": [ + "intercity", + 182.8 + ], + "116": [ + "regional_dmu", + 49.5 + ], + "117": [ + "intercity", + 182.8 + ], + "200": [ + "coach", + 13.0 + ], + "201": [ + "coach", + 13.0 + ], + "202": [ + "coach", + 13.0 + ], + "203": [ + "coach", + 13.0 + ], + "204": [ + "coach", + 13.0 + ], + "205": [ + "coach", + 13.0 + ], + "206": [ + "coach", + 13.0 + ], + "207": [ + "coach", + 13.0 + ], + "208": [ + "coach", + 13.0 + ], + "209": [ + "coach", + 13.0 + ], + "400": [ + "metro", + 115.0 + ], + "401": [ + "metro", + 115.0 + ], + "402": [ + "metro", + 115.0 + ], + "403": [ + "metro", + 115.0 + ], + "404": [ + "metro", + 115.0 + ], + "405": [ + "monorail", + 55.5 + ], + "700": [ + "city_bus", + 12.0 + ], + "701": [ + "coach", + 13.0 + ], + "702": [ + "coach", + 13.0 + ], + "703": [ + "city_bus", + 12.0 + ], + "704": [ + "city_bus", + 12.0 + ], + "705": [ + "city_bus", + 12.0 + ], + "706": [ + "coach", + 13.0 + ], + "707": [ + "city_bus", + 12.0 + ], + "708": [ + "city_bus", + 12.0 + ], + "709": [ + "city_bus", + 12.0 + ], + "710": [ + "double_decker", + 11.0 + ], + "711": [ + "city_bus", + 12.0 + ], + "712": [ + "city_bus", + 12.0 + ], + "713": [ + "city_bus", + 12.0 + ], + "714": [ + "coach", + 13.0 + ], + "715": [ + "van", + 5.5 + ], + "716": [ + "city_bus", + 12.0 + ], + "800": [ + "trolleybus", + 12.0 + ], + "900": [ + "tram", + 30.0 + ], + "901": [ + "tram", + 30.0 + ], + "902": [ + "tram", + 30.0 + ], + "903": [ + "light_rail", + 28.2 + ], + "904": [ + "tram", + 30.0 + ], + "905": [ + "tram", + 30.0 + ], + "906": [ + "tram", + 30.0 + ], + "1000": [ + "fast_ferry", + 40.0 + ], + "1200": [ + "fast_ferry", + 40.0 + ], + "1300": [ + "gondola", + 2.1 + ], + "1301": [ + "gondola", + 2.1 + ], + "1302": [ + "gondola", + 2.1 + ], + "1306": [ + "gondola", + 2.1 + ], + "1307": [ + "gondola", + 2.1 + ], + "1400": [ + "funicular", + 14.0 + ], + "1500": [ + "car", + 4.6 + ], + "1501": [ + "van", + 5.5 + ], + "1502": [ + "car", + 4.6 + ], + "1503": [ + "car", + 4.6 + ], + "1504": [ + "car", + 4.6 + ], + "1505": [ + "car", + 4.6 + ], + "1506": [ + "car", + 4.6 + ], + "1507": [ + "car", + 4.6 + ] + }, + "rail": { + "transit": { + "rail": [ + "commuter_emu", + 98.1 + ], + "metro": [ + "metro", + 115.0 + ], + "tram": [ + "tram", + 30.0 + ] + }, + "local": { + "rail": [ + "commuter_emu", + 98.1 + ], + "metro": [ + "metro", + 115.0 + ], + "tram": [ + "tram", + 30.0 + ] + }, + "regional": { + "rail": [ + "regional_dmu", + 49.5 + ], + "metro": [ + "metro", + 115.0 + ], + "tram": [ + "light_rail", + 28.2 + ] + }, + "national": { + "rail": [ + "intercity", + 182.8 + ], + "metro": [ + "metro", + 115.0 + ], + "tram": [ + "light_rail", + 28.2 + ] + }, + "international": { + "rail": [ + "high_speed", + 206.2 + ], + "metro": [ + "metro", + 115.0 + ], + "tram": [ + "light_rail", + 28.2 + ] + } + }, + "default": [ + "city_bus", + 12.0 + ], + "elevation": { + "monorail": 6.0, + "gondola": 20.0 + } + } +} \ No newline at end of file diff --git a/public/models/jet.glb b/public/models/jet.glb deleted file mode 100644 index bb2f99f9f0..0000000000 Binary files a/public/models/jet.glb and /dev/null differ diff --git a/public/models/mq9.glb b/public/models/mq9.glb deleted file mode 100644 index 47bc21f91b..0000000000 Binary files a/public/models/mq9.glb and /dev/null differ diff --git a/scripts/build-wikidata-cities.mjs b/scripts/build-wikidata-cities.mjs new file mode 100644 index 0000000000..5d49e4dff5 --- /dev/null +++ b/scripts/build-wikidata-cities.mjs @@ -0,0 +1,455 @@ +#!/usr/bin/env node +/** + * Build the bundled world cities pack read by `src/data/wikidataCities.js`: + * + * src/data/local_data/wikidata_cities/cities.json + * + * Source: Wikidata (CC0), read once from the public query service at build + * time. The app itself never calls Wikidata: it reads this file. + * + * What goes in: items that are a human settlement (an instance of any subclass + * of Q486972), have coordinates (P625) and a population (P1082) at or above + * the cut-off. Each row keeps the English label, coordinates to three + * decimals, the largest stated population, the ISO 3166-1 alpha-2 country + * code and the Wikidata id. Groupings of settlements (metropolitan areas, + * agglomerations, conurbations) and places that no longer stand are left out. + * + * The query service limits each query to 60 s, so the population range is + * read in bands without labels, the settlement test runs here against the + * class list, and labels and countries are read afterwards in batches. One + * request runs at a time, with a pause between requests, and a refusal's + * Retry-After is honoured. + * + * Usage: + * node scripts/build-wikidata-cities.mjs [--min-population 15000] + */ + +import { mkdir, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ENDPOINT = 'https://query.wikidata.org/sparql'; +const USER_AGENT = + 'gods-eye-view-places-builder/0.2 (offline data pack; one-off build; https://github.com/bilawalsidhu/gods-eye-view)'; +const SETTLEMENT = 'Q486972'; +const PAUSE_MS = 1500; +const LABEL_BATCH = 400; + +const args = process.argv.slice(2); +const flag = (name) => + args.includes(name) ? Number(args[args.indexOf(name) + 1]) : NaN; +const minPopulation = flag('--min-population') || 15000; +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const outDir = path.join(root, 'src/data/local_data/wikidata_cities'); + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const qid = (uri) => uri.slice(uri.lastIndexOf('/') + 1); + +/** The service ran out of time on a query: a smaller one may still answer. */ +class QueryTimeout extends Error {} + +async function sparql(query, attempt = 1) { + let response; + try { + response = await fetch(ENDPOINT, { + method: 'POST', + headers: { + 'User-Agent': USER_AGENT, + Accept: 'application/sparql-results+json', + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: `query=${encodeURIComponent(query)}`, + // The service stops a query at 60 s; past that the answer is lost. + signal: AbortSignal.timeout(90000), + }); + } catch (error) { + // Our own time limit: the query is too big, as with a 504. + if (error.name === 'TimeoutError' && attempt >= 2) + throw new QueryTimeout('Wikidata did not answer in time'); + if (attempt >= 4) throw error; + console.warn(` ${error.message}; waiting ${20 * attempt} s`); + await sleep(20000 * attempt); + return sparql(query, attempt + 1); + } + if (response.status === 504 && attempt >= 2) + throw new QueryTimeout('Wikidata answered 504'); + // A malformed query fails the same way every time. + if ( + response.status >= 400 && + response.status < 500 && + response.status !== 429 + ) + throw new Error( + `Wikidata answered ${response.status}: ${(await response.text()).slice(0, 300)}`, + ); + if (!response.ok) { + if (attempt >= 4) throw new Error(`Wikidata answered ${response.status}`); + const wait = + Number(response.headers.get('retry-after')) * 1000 || 20000 * attempt; + console.warn(` ${response.status}; waiting ${Math.round(wait / 1000)} s`); + await sleep(wait); + return sparql(query, attempt + 1); + } + // The service can stop a long answer partway; that arrives as broken JSON. + let rows; + try { + rows = JSON.parse(await response.text()).results.bindings; + } catch (error) { + // The service stops a query that runs too long partway through its answer. + if (attempt >= 2) + throw new QueryTimeout(`Wikidata answer was cut short: ${error.message}`); + console.warn(` answer cut short; waiting ${20 * attempt} s`); + await sleep(20000 * attempt); + return sparql(query, attempt + 1); + } + await sleep(PAUSE_MS); + return rows; +} + +/** + * Population bands, narrow where places are many, so each answer stays well + * under the service's 60 s limit (about 35,000 places a band). + */ +function bands(min, max) { + const stepAt = (pop) => + pop < 2000 + ? 200 + : pop < 5000 + ? 500 + : pop < 10000 + ? 1000 + : pop < 20000 + ? 2500 + : pop < 30000 + ? 10000 + : pop < 50000 + ? 20000 + : pop < 100000 + ? 50000 + : Infinity; + const list = []; + for (let low = min; low < max;) { + const high = Math.min(max, low + stepAt(low)); + list.push([low, high]); + low = high; + } + return list; +} + +console.log('Settlement classes…'); +const classes = new Set( + (await sparql(`SELECT ?c WHERE { ?c wdt:P279* wd:${SETTLEMENT} }`)).map( + (row) => qid(row.c.value), + ), +); +console.log(` ${classes.size} classes`); + +// Groupings of settlements (metropolitan areas, agglomerations, conurbations, +// capital regions) +// are settlements in Wikidata too, and are left out so a view is named after +// the city rather than the area around it. An item stated as one of these +// classes goes, whatever else it is ("New York metropolitan area" is also a +// megacity). An item of a narrower kind only goes when it is nothing else: +// Istanbul is a "metropolitan municipality in Turkey", a kind of +// metropolitan area, and a megacity, so it stays. +const GROUPING_TREES = [ + 'Q1907114', // metropolitan area + 'Q159313', // urban agglomeration + 'Q245260', // conurbation + 'Q1062177', // capital region + 'Q1768043', // metropolitan statistical area + 'Q3175539', // functional urban area +]; +// Left out as stated only: "city in the United States" is a subclass of +// these, so their subclasses must stay. +const GROUPING_CLASSES = [ + 'Q702492', // urban area + 'Q2342385', // urban area (statistical) + 'Q5951278', // urban area of the United States +]; +// Places that no longer stand as settlements (former entities, ghost towns, +// abandoned villages, archaeological sites) are settlements in Wikidata too. +// An item typed only as one of these, with every subclass, is left out; one +// that is also a living settlement (a city that is also a former capital) +// stays. +const HISTORICAL_TREES = [ + 'Q15893266', // former entity + 'Q19953632', // former administrative territorial entity + 'Q74047', // ghost town + 'Q350895', // abandoned village + 'Q839954', // archaeological site +]; +const former = new Set( + ( + await sparql( + `SELECT ?c WHERE { VALUES ?top { ${HISTORICAL_TREES.map((id) => `wd:${id}`).join(' ')} } ?c wdt:P279* ?top }`, + ) + ).map((row) => qid(row.c.value)), +); +console.log(` ${former.size} former-place classes`); +const groupings = new Set([ + ...( + await sparql( + `SELECT ?c WHERE { VALUES ?top { ${GROUPING_TREES.map((id) => `wd:${id}`).join(' ')} } ?c wdt:P279* ?top }`, + ) + ).map((row) => qid(row.c.value)), + ...GROUPING_CLASSES, +]); +console.log(` ${groupings.size} grouping classes left out`); +// A band's rows; one the service cannot answer in time is asked again in two +// halves. +async function bandRows(low, high) { + const range = Number.isFinite(high) + ? `?pop >= ${low} && ?pop < ${high}` + : `?pop >= ${low}`; + try { + return await sparql( + `SELECT ?item ?pop ?coord ?type WHERE { ?item wdt:P1082 ?pop . FILTER(${range}) ?item wdt:P625 ?coord ; wdt:P31 ?type . }`, + ); + } catch (error) { + const mid = Number.isFinite(high) ? Math.round((low + high) / 2) : low * 4; + if (!(error instanceof QueryTimeout) || mid <= low || mid === high) + throw error; + console.warn(` splitting ${low}–${high} at ${mid}`); + return [...(await bandRows(low, mid)), ...(await bandRows(mid, high))]; + } +} + +const GROUPING_STATED = new Set([...GROUPING_TREES, ...GROUPING_CLASSES]); +const living = new Set(); +const stated = new Set(); +const grouped = new Set(); +const settled = new Set(); + +const places = new Map(); +for (const [low, high] of bands(minPopulation, Infinity)) { + console.log(`Population ${low}–${Number.isFinite(high) ? high : '∞'}…`); + const rows = await bandRows(low, high); + let kept = 0; + for (const row of rows) { + const type = qid(row.type.value); + if (GROUPING_STATED.has(type)) stated.add(qid(row.item.value)); + if (groupings.has(type)) grouped.add(qid(row.item.value)); + if (!classes.has(type)) continue; + if (!groupings.has(type) && !former.has(type)) + settled.add(qid(row.item.value)); + if (!former.has(type)) living.add(qid(row.item.value)); + const match = /^Point\(([-\d.eE]+) ([-\d.eE]+)\)$/.exec(row.coord.value); + if (!match) continue; + const id = qid(row.item.value); + const pop = Math.round(Number(row.pop.value)); + const known = places.get(id); + if (known) { + known.pop = Math.max(known.pop, pop); + // Of several stated coordinates, the same one on every build. + const lon = Number(match[1]); + const lat = Number(match[2]); + if (lat < known.lat || (lat === known.lat && lon < known.lon)) { + known.lat = lat; + known.lon = lon; + } + continue; + } + places.set(id, { id, pop, lon: Number(match[1]), lat: Number(match[2]) }); + kept++; + } + console.log(` ${rows.length} rows, ${kept} new settlements`); +} + +let groupingsLeftOut = 0; +for (const id of grouped) { + if ((settled.has(id) && !stated.has(id)) || !places.delete(id)) continue; + groupingsLeftOut++; +} +console.log(`${groupingsLeftOut} groupings left out`); +// A place typed only as a former kind is held until its end date is known: a +// unit dissolved in a recent reform still stands (below). +for (const [id, place] of places) if (!living.has(id)) place.formerOnly = true; +const ids = [...places.keys()]; +console.log(`Labels and countries for ${ids.length} places…`); +for (let start = 0; start < ids.length; start += LABEL_BATCH) { + const values = ids + .slice(start, start + LABEL_BATCH) + .map((id) => `wd:${id}`) + .join(' '); + const rows = await sparql( + `SELECT ?item ?label ?iso ?ended WHERE { VALUES ?item { ${values} } OPTIONAL { ?item rdfs:label ?label . FILTER(LANG(?label) = "en") } OPTIONAL { ?item wdt:P17 ?country . ?country wdt:P297 ?iso } OPTIONAL { ?item wdt:P576 ?ended } }`, + ); + for (const row of rows) { + const place = places.get(qid(row.item.value)); + if (!place) continue; + if (row.label && !place.name) place.name = row.label.value; + // Of several stated countries, the same one on every build. + if (row.iso && (!place.cc || row.iso.value < place.cc)) + place.cc = row.iso.value; + // Dissolved, abolished or merged as a unit (P576), and when. + if (row.ended) { + place.ended = true; + const year = Number(/^-?\d+/.exec(row.ended.value)?.[0]); + if (Number.isFinite(year)) + place.endedYear = Math.max(place.endedYear ?? -Infinity, year); + } + } + if ((start / LABEL_BATCH) % 10 === 0) + console.log( + ` ${Math.min(start + LABEL_BATCH, ids.length)} / ${ids.length}`, + ); +} + +// A dissolved place goes only where another place still names the spot (a +// city merged into its neighbour, a former district inside its city). Where +// nothing else does, the town is still there under its name and stays: many +// of Vietnam's provincial cities ended as units in 2025, and with them their +// class, so they are typed only as a former kind. A place typed only as a +// former kind stays only that way: dissolved within the last ten years with +// nothing else near it. Ghost towns and ancient cities go. +const SUCCESSOR_KM = 15; +const RECENT_YEARS = 10; +const recent = new Date().getUTCFullYear() - RECENT_YEARS; +const standing = [...places.values()].filter( + (place) => place.name && !place.ended && !place.formerOnly, +); +const near = (a, b) => { + const rad = Math.PI / 180; + const h = + Math.sin(((b.lat - a.lat) * rad) / 2) ** 2 + + Math.cos(a.lat * rad) * + Math.cos(b.lat * rad) * + Math.sin(((b.lon - a.lon) * rad) / 2) ** 2; + return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(h))) <= SUCCESSOR_KM; +}; +const byCell = new Map(); +const cellOf = (lat, lon) => `${Math.floor(lat)},${Math.floor(lon)}`; +for (const place of standing) { + const key = cellOf(place.lat, place.lon); + if (!byCell.has(key)) byCell.set(key, []); + byCell.get(key).push(place); +} +let dissolved = 0; +let formerOnly = 0; +for (const [id, place] of places) { + if (place.formerOnly && !(place.ended && place.endedYear >= recent)) { + places.delete(id); + formerOnly++; + continue; + } + if (!place.ended) continue; + let succeeded = false; + for (let dLat = -1; dLat <= 1 && !succeeded; dLat++) + for (let dLon = -1; dLon <= 1 && !succeeded; dLon++) + succeeded = ( + byCell.get(cellOf(place.lat + dLat, place.lon + dLon)) || [] + ).some((other) => near(place, other)); + if (succeeded) dissolved++; + else place.ended = false; +} +console.log(`${formerOnly} former places left out`); +console.log(`${dissolved} dissolved places left out`); + +// A place whose stated country is a former one (no ISO code) takes the +// country of the area it lies in, one area level up at a time (a path of +// several levels in one query runs past the service's time limit). +const COUNTRY_BATCH = 50; +const countryless = () => + [...places.values()] + .filter((place) => place.name && !place.cc && !place.ended) + .map((place) => place.id); +for (const hops of [1, 2, 3]) { + const ids = countryless(); + if (!ids.length) break; + console.log(`Countries ${hops} area level(s) up for ${ids.length} places…`); + const pathToArea = Array.from({ length: hops }, () => 'wdt:P131').join('/'); + for (let start = 0; start < ids.length; start += COUNTRY_BATCH) { + const values = ids + .slice(start, start + COUNTRY_BATCH) + .map((id) => `wd:${id}`) + .join(' '); + const rows = await sparql( + `SELECT ?item ?iso WHERE { VALUES ?item { ${values} } ?item ${pathToArea} ?area . ?area wdt:P17 ?country . ?country wdt:P297 ?iso }`, + ); + for (const row of rows) { + const place = places.get(qid(row.item.value)); + if (!place || (place.cc && place.hops !== hops)) continue; + if (!place.cc || row.iso.value < place.cc) { + place.cc = row.iso.value; + place.hops = hops; + } + } + } +} +console.log(` ${countryless().length} places still without a country`); + +const rows = [...places.values()] + .filter( + (place) => + place.name && + !place.ended && + Math.abs(place.lat) <= 90 && + Math.abs(place.lon) <= 180, + ) + .sort((a, b) => b.pop - a.pop || a.id.localeCompare(b.id)) + .map((place) => [ + place.name, + Number(place.lat.toFixed(3)), + Number(place.lon.toFixed(3)), + place.pop, + place.cc || '', + place.id, + ]); + +// A filter that is too wide drops real cities without any error; these must +// survive, and no settlement grouping may. +const MUST_HAVE = { + Q1490: 'Tokyo', + Q84: 'London', + Q16559: 'Austin', + Q16555: 'Houston', + Q1355: 'Bengaluru', + Q3630: 'Jakarta', + Q174: 'São Paulo', + Q34600: 'Kyoto', + Q656: 'Saint Petersburg', + Q406: 'Istanbul', + Q8678: 'Rio de Janeiro', + Q1345: 'Philadelphia', + Q586: 'Bonn', + Q1449: 'Genoa', + Q1563: 'Havana', + // Provincial cities dissolved as units in 2025 that still stand. + Q19491: 'Nha Trang', + Q36081: 'Quy Nhon', +}; +// Groupings that are also typed as cities; none may get in. +const MUST_NOT = { + Q683705: 'New York metropolitan area', + Q665894: 'Greater Mexico City', + Q13580: 'Metro Manila', + Q3114019: 'Katowice urban area', +}; +const present = new Set(rows.map((row) => row[5])); +const missing = Object.entries(MUST_HAVE).filter(([id]) => !present.has(id)); +const intruders = Object.entries(MUST_NOT).filter(([id]) => present.has(id)); +if (intruders.length) { + throw new Error( + `Groupings got in: ${intruders.map(([id, name]) => `${name} (${id})`).join(', ')}`, + ); +} +if (missing.length) { + throw new Error( + `Expected cities are missing: ${missing.map(([id, name]) => `${name} (${id})`).join(', ')}`, + ); +} + +const meta = { + source: 'Wikidata (https://www.wikidata.org), via the Wikidata Query Service', + license: 'CC0 1.0', + built: new Date().toISOString(), + minPopulation, + count: rows.length, + columns: ['name', 'lat', 'lon', 'population', 'country', 'wikidata'], +}; + +await mkdir(outDir, { recursive: true }); +const file = path.join(outDir, 'cities.json'); +await writeFile(file, `${JSON.stringify({ meta, rows })}\n`); +console.log(`Wrote ${rows.length} places to ${path.relative(root, file)}`); diff --git a/scripts/check-import-directions.mjs b/scripts/check-import-directions.mjs index b6d8dba673..3cbbcbbe35 100644 --- a/scripts/check-import-directions.mjs +++ b/scripts/check-import-directions.mjs @@ -15,6 +15,11 @@ const tests = (file) => file.endsWith('.test.mjs') || file.startsWith('src/testSupport/') || file.startsWith('src/tooling/') || + // Test doubles outside src/testSupport, imported by tests only. + file === 'src/input/testDoubles.mjs' || + file === 'src/layers/recentImagery/testDoubles.mjs' || + file === 'src/voice/voiceWorkflowHarness.mjs' || + file === 'src/layers/wildlifeSightings/renderPerformanceFixtures.mjs' || file === 'src/overlays/worldOverlayAllocation.worker.mjs'; const source = (file) => file.startsWith('src/sources/') || diff --git a/scripts/focus-allocation-check.mjs b/scripts/focus-allocation-check.mjs index e15538a2f1..f256f7ef7c 100644 --- a/scripts/focus-allocation-check.mjs +++ b/scripts/focus-allocation-check.mjs @@ -1,11 +1,8 @@ #!/usr/bin/env node import assert from 'node:assert/strict'; -import { - advanceSpriteFocus, -} from '../src/data/focusDeemphasis.js'; -import { - applyAircraftBillboardTreatment, -} from '../src/data/aircraftRecession.js'; +import { advanceSpriteFocus } from '../src/data/focusDeemphasis.js'; +import { aircraftTreatmentAlpha } from '../src/data/aircraftRecession.js'; +import { createIconSet } from '../src/data/iconSet.js'; if (typeof global.gc !== 'function') { throw new Error('focus-allocation-check.mjs requires node --expose-gc'); @@ -66,17 +63,14 @@ const focusInput = { target, }; -const baseColor = { withAlpha: (alpha) => ({ alpha }) }; -const billboard = { scale: 1, color: { alpha: 1 } }; const aircraftInput = { - billboard, - baseScale: 1, baseAlpha: 1, - baseColor, focusFactor: 1, cameraDistanceM: 100, cameraHeightM: 1000, }; +const icons = createIconSet({ capacity: 4 }); +const row = icons.add('sprite', {}); const baseline = bytesPerCall(() => focusInput.nowMs); const focus = netOfLoopBaseline( @@ -84,30 +78,22 @@ const focus = netOfLoopBaseline( baseline, ); const aircraft = netOfLoopBaseline( - bytesPerCall(() => applyAircraftBillboardTreatment(aircraftInput).alpha), + bytesPerCall(() => aircraftTreatmentAlpha(aircraftInput)), baseline, ); const productionSpriteTick = netOfLoopBaseline( bytesPerCall(() => { - // Match the hot civilian/military sprite path: the caller constructs fresh - // option literals, consumes the shared focus result immediately, and then - // constructs the composed aircraft-treatment options for the same sprite. + // Match the hot icon-set focus pass: the caller constructs a fresh option + // literal, consumes the shared focus result immediately and writes it to + // the row's focus column (the shader composes it with limb recession). const focusResult = advanceSpriteFocus(sprite, { screenPosition: focusInput.screenPosition, cameraDistance: focusInput.cameraDistance, nowMs: focusInput.nowMs, target, }); - const treatment = applyAircraftBillboardTreatment({ - billboard, - baseScale: aircraftInput.baseScale, - baseAlpha: aircraftInput.baseAlpha, - baseColor, - focusFactor: focusResult.factor, - cameraDistanceM: aircraftInput.cameraDistanceM, - cameraHeightM: aircraftInput.cameraHeightM, - }); - return focusResult.factor + treatment.alpha; + icons.setFocus(row, focusResult.factor); + return focusResult.factor; }), baseline, ); @@ -118,22 +104,24 @@ assert.ok( ); assert.ok( aircraft.roundedMedian <= PURE_CALL_BUDGET, - `applyAircraftBillboardTreatment allocated ${aircraft.rawMedian.toFixed(3)} B/call median`, + `aircraftTreatmentAlpha allocated ${aircraft.rawMedian.toFixed(3)} B/call median`, ); assert.ok( productionSpriteTick.roundedMedian <= PRODUCTION_SPRITE_TICK_BUDGET, `production sprite tick allocated ${productionSpriteTick.rawMedian.toFixed(3)} B/call median`, ); -console.log(JSON.stringify({ - callsPerTrial: CALLS, - trials: TRIALS, - budgets: { - pureCall: PURE_CALL_BUDGET, - productionSpriteTick: PRODUCTION_SPRITE_TICK_BUDGET, - }, - loopBaseline: baseline, - advanceSpriteFocus: focus, - applyAircraftBillboardTreatment: aircraft, - productionSpriteTick, -})); +console.log( + JSON.stringify({ + callsPerTrial: CALLS, + trials: TRIALS, + budgets: { + pureCall: PURE_CALL_BUDGET, + productionSpriteTick: PRODUCTION_SPRITE_TICK_BUDGET, + }, + loopBaseline: baseline, + advanceSpriteFocus: focus, + aircraftTreatmentAlpha: aircraft, + productionSpriteTick, + }), +); diff --git a/scripts/format-scope.json b/scripts/format-scope.json index df01df5069..e474377e12 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -43,6 +43,34 @@ "scripts/build-admin-packs.mjs", "scripts/qa-admin-outlines.mjs", "src/data/inputOwnership.test.mjs", + "src/input/dispatcher.test.mjs", + "src/input/testDoubles.mjs", + "src/input/sensorPick.js", + "src/input/dispatcher.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/input.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/nativeClick.test.mjs", + "src/render/cesium/pickMemo.js", + "src/render/cesium/input.test.mjs", + "src/render/cesium/cameraInput.test.mjs", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraControls.test.mjs", + "src/render/input/router.js", + "src/render/input/router.test.mjs", + "src/render/motion/iconMotion.test.mjs", + "src/render/motion/iconBook.test.mjs", + "src/render/camera/poseSignature.test.mjs", + "src/render/cesium/internals.test.mjs", + "src/render/cesium/uploadProbe.js", + "src/render/cesium/uploadProbe.test.mjs", + "src/render/cesium/tileRequests.js", + "src/render/cesium/tileRequests.test.mjs", + "src/queries/heights.test.mjs", + "src/render/cesium/heights.test.mjs", "docs/CODE-BOUNDARIES.md", "src/main.js", "docs/APPLICATION.md", @@ -56,10 +84,8 @@ "src/app/application.test.mjs", "src/app/mapLifecycle.test.mjs", "src/app/startupCamera.test.mjs", - "src/app/viewer.js", - "src/app/zoomOutGuard.test.mjs", - "src/app/controls.test.mjs", - "scripts/qa-zoom-out-guard.mjs", + "src/render/cesium/applicationViewer.js", + "src/sky/icrf.js", "src/app/atmosphereCompat.test.mjs", "src/standalone/application.js", "src/standalone/controls.js", @@ -180,6 +206,9 @@ "src/search/google.js", "src/search/coordinateParser.js", "src/search/coordinateParser.test.mjs", + "src/search/gridReference.js", + "src/search/gridReference.test.mjs", + "src/search/plusCode.js", "src/search/coordinateGeocoder.js", "src/search/presetGeocoder.js", "src/search/offlineGeocoders.test.mjs", @@ -355,7 +384,6 @@ "src/layers/flights/tracking.js", "src/layers/flights/rendering.js", "src/layers/flights/testing.js", - "src/layers/flights/hiddenContactRotation.test.mjs", "src/layers/flights/evidence.js", "src/layers/flights/ingestion.js", "src/layers/flights/queries.js", @@ -456,6 +484,7 @@ "src/layers/satellites/ingestion.js", "src/layers/satellites/index.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/motion.js", "src/layers/launches/lifecycle.js", "src/layers/launches/controls.js", "src/layers/launches/panel.js", @@ -483,6 +512,8 @@ "src/data/rocketLaunches.js", "src/layers/satellites/source.test.mjs", "src/layers/satellites/stale.test.mjs", + "src/layers/satellites/motion.test.mjs", + "src/layers/satellites/reckon.test.mjs", "src/layers/launches/source.test.mjs", "src/layers/launches/ingestion.test.mjs", "src/layers/launches/failedEntry.test.mjs", @@ -532,6 +563,8 @@ "src/layers/traffic/model.js", "src/layers/traffic/timing.js", "src/layers/traffic/style.js", + "src/layers/traffic/style.test.mjs", + "src/layers/traffic/timing.test.mjs", "src/layers/bikeshare/lifecycle.js", "src/layers/bikeshare/viewport.js", "src/layers/bikeshare/registry.js", @@ -557,6 +590,13 @@ "src/ui/frameRateMonitor.js", "src/ui/frameRateMonitor.test.mjs", "src/ui/frameRateView.test.mjs", + "src/render/cesium/renderFailure.test.mjs", + "src/ui/renderFailureView.test.mjs", + "src/render/cesium/renderFailureLoopErrors.test.mjs", + "src/render/cesium/renderFailureEventRetry.test.mjs", + "src/app/renderFailureInlineRetry.test.mjs", + "src/render/cesium/renderFailureSecondLoop.test.mjs", + "src/render/cesium/renderLoopFixture.mjs", "src/layers/cctv/lifecycle.js", "src/layers/cctv/controls.js", "src/layers/cctv/geometry.js", @@ -637,6 +677,7 @@ "src/layers/radio/volume.js", "src/data/radio.js", "src/layers/radio/source.test.mjs", + "src/layers/radio/lifecycle.test.mjs", "src/layers/submarineCables/bundledSource.js", "src/layers/submarineCables/geometry.js", "src/layers/submarineCables/index.js", @@ -661,10 +702,14 @@ "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", + "src/maps/engine.js", + "src/maps/startupRoute.js", + "src/maps/attribution.js", + "src/render/cesium/mapEngine.js", "src/maps/terrainRetry.js", "src/maps/terrainRetry.test.mjs", "src/mapStackController.js", @@ -672,7 +717,7 @@ "src/mapStackChips.test.mjs", "src/mapStackUnavailableReason.test.mjs", "src/mapStartup.test.mjs", - "src/maps/sourceFactories.test.mjs", + "src/render/cesium/mapSources.test.mjs", "src/search/geospatial.js", "src/search/http.js", "src/search/defaults.js", @@ -689,6 +734,16 @@ "src/services/application.js", "src/services/requests.js", "src/app/scene.js", + "src/render/cesium/appRenderer.test.mjs", + "src/render/noCesiumOutsideRender.test.mjs", + "src/render/cesiumAllowList.json", + "src/render/viewerAccess.test.mjs", + "src/render/viewerAccessAllowList.json", + "src/testSupport/viewerAccess.mjs", + "scripts/viewer-access-baseline.mjs", + "src/geo/geo.test.mjs", + "src/geo/celestial.test.mjs", + "src/geo/quaternion.test.mjs", "src/app/controls.js", "src/app/data.js", "src/app/tools.js", @@ -744,6 +799,7 @@ "src/layers/flights/snapshotRenderer.js", "src/layers/flights/records.test.mjs", "src/layers/flights/ingestion.test.mjs", + "src/layers/flights/controller.test.mjs", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", "src/layers/military/snapshotRenderer.js", @@ -827,7 +883,6 @@ "src/tooling/transitProvider.test.mjs", "src/app/layers/transit.js", "src/data/transitIcons.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.test.mjs", @@ -899,6 +954,10 @@ "src/layers/weather/rendering.js", "src/layers/weather/shellRendering.js", "src/layers/weather/shellRendering.test.mjs", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawFields.test.mjs", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawStreamlines.test.mjs", "src/layers/weather/infraredAlpha.js", "src/layers/weather/infraredAlpha.test.mjs", "src/layers/weather/infraredImage.js", @@ -929,8 +988,6 @@ "src/ui/weatherPanel.test.mjs", "src/ui/railCards.js", "src/ui/railCards.test.mjs", - "src/ui/railTimeline.js", - "src/ui/railTimeline.test.mjs", "src/layers/weather/imageryOrder.js", "src/layers/weather/imageryOrder.test.mjs", "server/providers/cyclones.js", @@ -1119,7 +1176,6 @@ "src/layers/traffic/roadModes.test.mjs", "scripts/qa-traffic-motion.mjs", "src/layers/traffic/motion.test.mjs", - "src/layers/traffic/lineRebuild.test.mjs", "scripts/qa-journey-recorder.mjs", "scripts/qa-alpr-journey.mjs", "scripts/qa-context-arrivals.mjs", @@ -1152,6 +1208,9 @@ "src/view/index.test.mjs", "src/tools/views.test.mjs", "src/app/embed.test.mjs", + "src/app/panelRendering.js", + "src/render/cesium/application.js", + "src/app/panelRendering.test.mjs", "src/tools/globePanel.test.mjs", "src/costEndpointThrottle.test.mjs", "src/sources/gbfsStations.test.mjs", @@ -1168,7 +1227,7 @@ "scripts/build-bright-stars.mjs", "scripts/build-milky-way.mjs", "src/sky/stars.test.mjs", - "src/sky/starrySky.test.mjs", + "src/render/cesium/starrySky.test.mjs", "src/tooling/skyAssets.test.mjs", "src/tooling/skyAssets.paintOut.test.mjs", "src/tooling/responseCompression.test.mjs", @@ -1186,6 +1245,31 @@ "src/ui/shellFacade.test.mjs", "src/voice/globeResetConfirmation.test.mjs", "src/hudDms.test.mjs", + "server/providers/common/rateLimitKeys.test.mjs", + "src/render/contract/contract.test.mjs", + "src/render/contract/common.d.ts", + "src/render/contract/renderer.d.ts", + "src/render/contract/frame.d.ts", + "src/render/contract/globe.d.ts", + "src/render/contract/draw.d.ts", + "src/render/contract/camera.d.ts", + "src/render/contract/query.d.ts", + "src/render/contract/input.d.ts", + "src/render/contract/effects.d.ts", + "src/render/contract/credits.d.ts", + "src/render/contract/quality.d.ts", + "src/render/contract/index.d.ts", + "src/render/stub/stub.test.mjs", + "src/render/conformance/scenes.test.mjs", + "src/render/cesium/cameraGoldens.test.mjs", + "scripts/record-camera-goldens.mjs", + "server/standalone/conformance-references.js", + "dev/conformance/index.html", + "dev/conformance/main.js", + "docs/RENDERER-CONTRACT.md", + "src/render/cesium/zoomOutGuard.test.mjs", + "src/app/controls.test.mjs", + "scripts/qa-zoom-out-guard.mjs", "src/hudSummaryGate.test.mjs", "src/hudSummaryLine.test.mjs", "src/testSupport/stubMgrs.mjs", @@ -1291,7 +1375,6 @@ "src/tooling/nominatimGuardLifecycle.test.mjs", "src/tooling/nominatimLockOwnership.test.mjs", "src/tooling/nominatimOutlineRoute.test.mjs", - "server/providers/common/rateLimitKeys.test.mjs", "src/voice/areaCandidateContract.js", "src/voice/layerActionOwnership.js", "src/data/areaGeometry.test.mjs", @@ -1334,6 +1417,7 @@ "src/layers/shipwrecks/index.test.mjs", "src/layers/shipwrecks/source.test.mjs", "src/data/shipwrecksProxy.test.mjs", + "src/data/aircraftIconLayer.test.mjs", "src/app/sourceComposition.js", "src/app/sourceComposition.test.mjs", "src/data/dataCredits.js", @@ -1428,5 +1512,47 @@ "src/ui/ownerFlagSheet.js", "src/data/placePacksLoading.test.mjs", "src/ui/placePacksLoading.js", - "src/ui/placePacksLoading.test.mjs" + "src/ui/placePacksLoading.test.mjs", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/globeEngine.test.mjs", + "src/render/cesium/viewers.js", + "src/app/scene.test.mjs", + "dev/stub-app/main.js", + "scripts/qa-stub-boot.mjs", + "src/ui/creditsView.js", + "src/ui/creditsView.test.mjs", + "src/cockpitSubjectProviders.js", + "src/cockpitSubjectProviders.test.mjs", + "src/cockpitProgress.js", + "src/cockpitProgress.test.mjs", + "src/ui/cockpitSubjectView.test.mjs", + "src/ui/styles/cockpitSubject.css", + "src/layers/rail/cockpitSubject.js", + "src/layers/rail/cockpitSubject.test.mjs", + "src/layers/transit/cockpitSubject.js", + "src/data/fleetModels.test.mjs", + "src/data/fleetModelInstances.test.mjs", + "src/testSupport/fleetGlb.mjs", + "src/testSupport/fleetModelFakes.mjs", + "scripts/measure-fleet-trail-anchors.mjs", + "src/ui/panelEdge.js", + "src/ui/railEdgeScroll.js", + "src/ui/railEdgeScroll.test.mjs", + "src/ui/kit/UiPanelEdge.vue", + "src/ui/styles/rail-edge.css", + "src/ui/styles/rail-split.css", + "src/ui/styles/left-tools.css", + "src/ui/styles/panel-edge.css", + "src/data/placementProvider.test.mjs", + "src/layers/vessels/placement.test.mjs", + "src/ui/styles/visual-panel.css", + "src/ui/styles/scope-off-shadows.css", + "src/ui/styles/cockpit-panels.css", + "src/ui/styles/layer-section-index.css", + "src/ui/styles/layer-finder.css", + "src/ui/layerFinder.test.mjs", + "src/data/wikidataCities.js", + "src/data/wikidataCities.test.mjs", + "scripts/build-wikidata-cities.mjs" ] diff --git a/scripts/i18n.mjs b/scripts/i18n.mjs index c424666a29..7baf43dc22 100644 --- a/scripts/i18n.mjs +++ b/scripts/i18n.mjs @@ -479,7 +479,8 @@ function readMarkup(file) { // Text that never reaches the page as UI: tool results and descriptions for // AI clients (MCP and the voice model). -const NOT_UI = [/^src\/tools\//]; +// The conformance suite's check titles are developer output, not UI. +const NOT_UI = [/^src\/tools\//, /^src\/render\/conformance\//]; function sourceFiles() { return trackedFiles( diff --git a/scripts/measure-fleet-trail-anchors.mjs b/scripts/measure-fleet-trail-anchors.mjs new file mode 100644 index 0000000000..c26874dc7a --- /dev/null +++ b/scripts/measure-fleet-trail-anchors.mjs @@ -0,0 +1,53 @@ +#!/usr/bin/env node +/** + * Re-measure the trail attachment point of every aircraft-layer fleet model + * and print `src/data/fleetTrailAnchors.js`. + * + * node scripts/measure-fleet-trail-anchors.mjs > src/data/fleetTrailAnchors.js + * + * Run it whenever a model under `public/models/fleet/` changes; the unit + * suite (`src/data/fleetModels.test.mjs`) re-derives each value and fails + * on a table that no longer matches its GLB. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import { projectRoot } from './project-root.mjs'; +import { + fleetMesh, + measuredTrailAnchor, +} from '../src/testSupport/fleetGlb.mjs'; + +/** Catalog categories the aircraft layers draw (ADS-B ground vehicles and balloons included). */ +export const TRAIL_ANCHOR_CATEGORIES = ['aircraft', 'helicopters', 'other']; + +const root = projectRoot(import.meta.url); +const dir = path.join(root, 'public', 'models', 'fleet'); +const catalog = JSON.parse( + fs.readFileSync(path.join(dir, 'catalog.json'), 'utf8'), +); +const rows = []; +for (const [name, model] of Object.entries(catalog)) { + if (!TRAIL_ANCHOR_CATEGORIES.includes(model.category)) continue; + const anchor = measuredTrailAnchor( + await fleetMesh(path.join(dir, model.file)), + ); + if (!anchor) continue; + const [x, y] = anchor.map((value) => Number(value.toFixed(4)) || 0); + rows.push( + ` ${/^[a-z_]\w*$/.test(name) ? name : `'${name}'`}: Object.freeze([${x}, ${y}, 0]),`, + ); +} +process.stdout.write(`/** + * Aft-belly trail attachment points of the fleet models the aircraft layers + * draw, in raw glTF axes (X along the body, nose toward -X; Y up), metres + * before scale, node transforms applied. Each is the point of the model's + * centreline profile (its z = 0 slice) nearest its aft-belly bounding-box + * corner: on the hull, aft, and on the centreline (see modelVisualAnchor.js). + * + * Written by scripts/measure-fleet-trail-anchors.mjs; re-measured against the + * GLBs by fleetModels.test.mjs. + */ +export const FLEET_TRAIL_ANCHORS = Object.freeze({ +${rows.join('\n')} +}); +`); diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index cfc18f7ddb..4147d8f6cd 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -8,12 +8,68 @@ "modules": [ "src/data/infrastructure.js", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", + "src/render/cesium/heights.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconAtlas.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", "src/data/localGeojsonLod.js", "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/index.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", "src/data/infrastructureOverlayEntry.js", - "src/sources/infrastructureData.js" + "src/sources/infrastructureData.js", + "src/queries/heights.js", + "src/render/color.js", + "src/geo/sphere.js", + "src/geo/rhumb.js", + "src/geo/frustum.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "application": { "exports": ["./application"], @@ -22,6 +78,9 @@ "src/ui/vueRuntime.js", "src/ui/views/index.js", "src/ui/views/CockpitView.vue", + "src/ui/views/panels/CockpitProgress.vue", + "src/cockpitProgress.js", + "src/cockpitSubjectProviders.js", "src/ui/views/CommandDockView.vue", "src/ui/views/ContextView.vue", "src/ui/views/panels/RadioPanel.vue", @@ -99,6 +158,7 @@ "src/ui/stores/streetLevel.js", "src/ui/rail/RailChips.vue", "src/ui/views/panels/DisplayPanel.vue", + "src/ui/views/panels/VisualPresets.vue", "src/ui/views/panels/GeoImport.vue", "src/ui/views/panels/DrawControls.vue", "src/ui/views/panels/DrawMarkList.vue", @@ -109,6 +169,8 @@ "src/ui/views/panels/DataLibraryCard.vue", "src/ui/views/panels/DataLibraryDialog.vue", "src/ui/views/panels/DataLibraryBrowse.vue", + "src/ui/views/panels/LayerFinder.vue", + "src/ui/views/panels/LayerSectionIndex.vue", "src/ui/libraryBrowser.js", "src/ui/localSdrPresentation.js", "src/ui/unitLabels.js", @@ -151,6 +213,8 @@ "src/ui/kit/UiSegmented.vue", "src/ui/rail/RailPanel.vue", "src/ui/kit/UiPanel.vue", + "src/ui/kit/UiPanelEdge.vue", + "src/ui/panelEdge.js", "src/ui/kit/UiPanelToggle.vue", "src/ui/stores/panelChrome.js", "src/ui/rail/PanelCollapseButton.vue", @@ -163,6 +227,7 @@ "src/ui/kit/UiBadge.vue", "src/ui/stores/globeActions.js", "src/ui/views/panels/GlobeActions.vue", + "src/ui/views/panels/RenderFailure.vue", "src/ui/views/panels/GlobeCompass.vue", "src/ui/stores/recording.js", "src/ui/styleParameters.js", @@ -205,13 +270,17 @@ "viewer": { "exports": ["./application/viewer"], "modules": [ - "src/app/viewer.js", + "src/render/cesium/applicationViewer.js", "src/app/atmosphereCompat.js", - "src/globeInView.js", - "src/sky/starrySky.js", + "src/render/cesium/starrySky.js", "src/sky/stars.js", "src/data/bundledJson.js", - "src/renderGovernor.js" + "src/renderGovernor.js", + "src/sky/icrf.js", + "src/sky/assets.js", + "src/globeInView.js", + "src/render/cesium/imageryLookAhead.js", + "src/cockpitOrbital.js" ], "external": ["cesium"] }, @@ -247,6 +316,7 @@ "src/data/adsbLolFallback.js", "src/data/aisStreamAdapter.js", "src/data/aisWatchdog.js", + "src/data/vesselTypes.js", "src/sources/httpBody.js", "src/i18n/marker.js", "server/providers/acartia.js", @@ -660,6 +730,8 @@ "src/search/alpsGeocoder.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/search/nominatim.js", "src/nominatimGeocode.js", @@ -733,11 +805,43 @@ "modules": ["src/ui/displayControls.js"], "external": [] }, + "display-groups": { + "exports": ["./ui/display/groups"], + "modules": [ + "src/ui/displayGroups.js", + "src/ui/vueRuntime.js", + "src/ui/stores/display.js", + "src/ui/stores/owners.js", + "src/i18n/locale.js", + "src/i18n/locales/ar.json", + "src/i18n/locales/de.json", + "src/i18n/locales/es.json", + "src/i18n/locales/fr.json", + "src/i18n/locales/it.json", + "src/i18n/locales/he.json", + "src/i18n/locales/ja.json", + "src/i18n/locales/sv.json", + "src/i18n/locales/pt.json", + "src/i18n/locales/ru.json", + "src/i18n/locales/zh-CN.json", + "src/i18n/locales/uk.json", + "src/i18n/locales/zh-Hant.json", + "src/i18n/index.js", + "src/ui/i18n.js" + ], + "external": ["vue", "pinia", "vue-i18n"] + }, + "weather-effects": { + "exports": ["./render/weather", "./weather/effects"], + "modules": ["src/render/weather.js", "src/weatherEffectsMath.js"], + "external": [] + }, "visual-effects": { "exports": ["./ui/effects", "./ui/effects/bloom"], "modules": [ "src/ui/effects.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualPresets.js", "src/bloom.js", "src/styles/retro.js", @@ -794,7 +898,6 @@ "src/ui/layerPanel/RowSwitch.vue", "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", - "src/ui/railTimeline.js", "src/ui/clearLayersControl.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", @@ -827,7 +930,6 @@ "src/ui/rail/RailCard.vue", "src/ui/rail/RailCards.vue", "src/ui/rail/utcClock.js", - "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", "src/ui/newsPanel.js", @@ -932,7 +1034,11 @@ "src/ui/vueRuntime.js", "src/ui/stores/cctv.js", "src/ui/stores/status.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/horizon.js", + "src/render/rendererOf.js" ], "external": ["vue", "pinia", "vue-i18n", "cesium"] }, @@ -983,32 +1089,58 @@ "src/data/distanceFormat.js", "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/ui/cockpitBriefPages.js", "src/data/regionalNewsWindow.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", - "src/ui/cockpitOrbitalView.js", - "src/ui/cockpitOrbitalFocus.js", - "src/ui/cockpitOrbitalSignals.js", - "src/ui/cockpitOrbitalSatellites.js", - "src/cockpitOrbitalSatellites.js", - "src/layers/installations/classLabel.js", - "src/data/installationNames.js", - "src/i18n/marker.js", - "src/data/placeBelow.js", - "src/layers/satellites/sensors.js", - "src/data/adminBoundaries.js", - "src/data/bundledJson.js", - "src/data/retryableLoad.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", + "src/data/followed.js", "src/ui/cockpitDisplayPortal.js", "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", - "src/data/inputOwnership.js", "src/ui/cockpitInstruments.js", + "src/cockpitSubjectProviders.js", + "src/cockpitProgress.js", "src/ui/cockpitLayout.js", "src/ui/cockpitPresentation.js", "src/ui/cockpitSignals.js", @@ -1016,13 +1148,6 @@ "src/cockpitMath.js", "src/cockpitUtilityLayout.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", - "src/geoDistance.js", - "src/data/motionModel.js", "src/ui/panelRailGeometry.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1039,10 +1164,46 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", "src/ui/layerNames.js", - "src/ui/unitLabels.js" + "src/ui/cockpitOrbitalView.js", + "src/ui/cockpitOrbitalFocus.js", + "src/ui/cockpitOrbitalSignals.js", + "src/ui/cockpitOrbitalSatellites.js", + "src/cockpitOrbitalSatellites.js", + "src/layers/installations/classLabel.js", + "src/data/installationNames.js", + "src/i18n/marker.js", + "src/data/placeBelow.js", + "src/layers/satellites/sensors.js", + "src/data/adminBoundaries.js", + "src/data/bundledJson.js", + "src/data/retryableLoad.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/geoDistance.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "scene-controls": { "exports": ["./ui/scenes"], @@ -1095,21 +1256,12 @@ "src/cockpitTracking.js", "src/cockpitUtilityLayout.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", - "src/geoDistance.js", - "src/data/motionModel.js", "src/contactsDetectionPolicy.js", "src/contextModePolicy.js", "src/data/detectionPolicy.js", "src/data/installationFeedback.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/militaryAwarenessEngine.js", @@ -1129,6 +1281,58 @@ "src/styles/surveillance.js", "src/styles/thermal.js", "src/ui/applicationShell.js", + "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/google3d.js", + "src/maps/startupRoute.js", + "src/sky/stars.js", + "src/renderGovernor.js", + "src/data/bundledJson.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/data/followed.js", + "src/render/cesium/camera.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/ui/railEdgeScroll.js", "src/ui/localePicker.js", "src/ui/cyberSonarControls.js", "src/ui/locationNavigation.js", @@ -1142,8 +1346,6 @@ "src/ui/cctvFrames.js", "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", - "src/data/iconOrientation.js", - "src/ui/quebecCctvOverlay.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", @@ -1153,27 +1355,14 @@ "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", - "src/ui/cockpitOrbitalView.js", - "src/ui/cockpitOrbitalFocus.js", - "src/ui/cockpitOrbitalSignals.js", - "src/ui/cockpitOrbitalSatellites.js", - "src/cockpitOrbitalSatellites.js", - "src/layers/installations/classLabel.js", - "src/data/placeBelow.js", - "src/ui/placePacksLoading.js", - "src/ui/ownerFlag.js", - "src/ui/ownerFlagSheet.js", - "src/layers/satellites/sensors.js", - "src/data/adminBoundaries.js", - "src/data/bundledJson.js", - "src/data/retryableLoad.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", - "src/data/inputOwnership.js", "src/ui/cockpitInstruments.js", + "src/cockpitSubjectProviders.js", + "src/cockpitProgress.js", "src/ui/cockpitLayout.js", "src/ui/cockpitPresentation.js", "src/ui/cockpitSignals.js", @@ -1202,7 +1391,6 @@ "src/ui/layerPanel/RowSwitch.vue", "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", - "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -1241,10 +1429,18 @@ "src/ui/surfaceKeyboard.js", "src/ui/uiLifetime.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualInput.js", "src/ui/visualPresets.js", "src/ui/visualSettings.js", "src/worldFocus.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", "src/data/feedState.js", "src/data/layerSnapshot.js", "src/ui/aircraftDisplay.js", @@ -1297,7 +1493,6 @@ "src/ui/rail/RailCard.vue", "src/ui/rail/RailCards.vue", "src/ui/rail/utcClock.js", - "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", "src/ui/newsPanel.js", @@ -1333,7 +1528,19 @@ "src/ui/stores/globeActions.js", "src/ui/stores/recording.js", "src/ui/i18n.js", - "src/time/worldClock.js", + "src/data/entityRecords.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/sky/icrf.js", + "src/data/firmsIntensity.js", "src/ui/kit/UiSegmented.vue", "src/ui/wildlifeSightingCard.js", "src/layers/wildlifeSightings/records.js", @@ -1341,9 +1548,56 @@ "src/ui/views/panels/WildlifeSightingCard.vue", "src/ui/wildlifeSightingPlacement.js", "src/overlays/worldOverlayChrome.js", - "src/layers/wildlifeSightings/photoText.js" + "src/layers/wildlifeSightings/photoText.js", + "src/data/iconOrientation.js", + "src/ui/quebecCctvOverlay.js", + "src/time/worldClock.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/geoDistance.js", + "src/data/satelliteClassMask.js", + "src/ui/cockpitOrbitalView.js", + "src/ui/cockpitOrbitalFocus.js", + "src/ui/cockpitOrbitalSignals.js", + "src/ui/cockpitOrbitalSatellites.js", + "src/cockpitOrbitalSatellites.js", + "src/layers/installations/classLabel.js", + "src/data/placeBelow.js", + "src/ui/placePacksLoading.js", + "src/ui/ownerFlag.js", + "src/ui/ownerFlagSheet.js", + "src/layers/satellites/sensors.js", + "src/data/adminBoundaries.js", + "src/data/retryableLoad.js", + "src/maps/imageryHost.js", + "src/render/cesium/viewers.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", + "src/time/frameWait.js" ], - "external": ["cesium", "vue", "pinia", "vue-i18n"] + "external": [ + "cesium", + "vue", + "pinia", + "vue-i18n", + "pbf", + "@mapbox/vector-tile", + "kdbush" + ] }, "ui-styles": { "exports": ["./ui/styles"], @@ -1356,6 +1610,7 @@ "src/ui/styles/status.css", "src/ui/styles/cockpit.css", "src/ui/styles/cockpitBridge.css", + "src/ui/styles/cockpitSubject.css", "src/ui/styles/cockpitRadar.css", "src/ui/styles/overlays.css", "src/ui/styles/layers.css", @@ -1413,6 +1668,41 @@ "src/data/bhoteKoshiFloodPath.js", "src/maps/catalog.js", "src/scenes/director.js", + "src/data/followed.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", + "src/geo/index.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/scenes/sceneSaveError.js", "src/scenes/playbackAdapter.js", "src/director/playback.js", @@ -1481,9 +1771,24 @@ "src/ui/toast.js", "src/ui/stores/sceneInteractions.js", "src/ui/stores/dataPacks.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "vue", "pinia", "vue-i18n"] + "external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"] }, "live-observations": { "exports": ["./sources/live"], @@ -1504,6 +1809,10 @@ "civil-flights": { "exports": ["./layers/flights"], "modules": [ + "src/data/fleetModels.js", + "src/data/vesselTypes.js", + "src/data/fleetTrailAnchors.js", + "src/data/fleetModelInstances.js", "src/data/headingDegrees.js", "src/i18n/marker.js", "src/cyberSonar.js", @@ -1517,36 +1826,74 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", + "src/render/color.js", "src/layers/flights/queries.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/followed.js", "src/layers/flights/rendering.js", + "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/render/motion/iconBook.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/modelRecord.js", "src/layers/flights/state.js", + "src/data/displayDelay.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", + "src/geo/index.js", "src/data/trailContinuity.js", "src/layers/flights/records.js", "src/layers/flights/clockFollow.js", "src/time/snapshotTimeline.js", + "src/data/timelineHistory.js", + "src/time/timelineFixes.js", "src/sources/live/contract.js", "src/layers/flights/recordPolicy.js", "src/layers/flights/snapshotRenderer.js", @@ -1569,15 +1916,51 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/quaternion.js", + "src/geo/celestial.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/internals.js", + "src/data/firmsIntensity.js", "src/time/worldClock.js", - "src/time/julian.js", - "src/data/planespottersPhoto.js" + "src/data/satelliteClassMask.js", + "src/data/planespottersPhoto.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/layers/flights/placed.js", + "src/data/courseFromFixes.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "military-flights": { "exports": ["./layers/military"], "modules": [ + "src/layers/flights/modelSpec.js", + "src/layers/flights/policy.js", + "src/data/fleetModels.js", + "src/data/vesselTypes.js", + "src/data/fleetTrailAnchors.js", + "src/data/fleetModelInstances.js", "src/data/headingDegrees.js", "src/i18n/marker.js", "src/cyberSonar.js", @@ -1590,31 +1973,68 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/renderAltitude.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/military/controller.js", "src/layers/military/index.js", "src/layers/military/ingestion.js", "src/layers/military/clockFollow.js", "src/time/snapshotTimeline.js", + "src/data/timelineHistory.js", + "src/time/timelineFixes.js", "src/sources/live/contract.js", "src/layers/military/lifecycle.js", "src/layers/military/motion.js", + "src/data/renderedFrames.js", "src/layers/military/policy.js", + "src/render/color.js", "src/layers/military/queries.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/geo/index.js", + "src/data/followed.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/render/motion/iconBook.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/modelRecord.js", "src/layers/military/state.js", + "src/data/displayDelay.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", + "src/data/trackedAircraftIcon.js", "src/data/trailContinuity.js", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", @@ -1636,11 +2056,42 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/data/firmsIntensity.js", "src/ui/unitLabels.js", "src/time/worldClock.js", - "src/time/julian.js" + "src/data/satelliteClassMask.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/layers/flights/placed.js", + "src/data/courseFromFixes.js", + "src/data/approxDistance.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "aircraft-mechanics": { "exports": ["./aircraft"], @@ -1654,45 +2105,76 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", + "src/data/modelRecord.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/data/entityRecords.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", + "src/geo/vector.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/aircraft/classification.js", "src/layers/aircraft/index.js", - "src/data/inputOwnership.js" + "src/data/inputOwnership.js", + "src/data/firmsIntensity.js", + "src/data/satelliteClassMask.js" ], "external": ["cesium"] }, "vessel-layer": { "exports": ["./layers/vessels"], "modules": [ + "src/data/fleetModels.js", + "src/data/aircraftClass.js", + "src/i18n/marker.js", + "src/data/fleetModelInstances.js", + "src/data/aircraftModelLighting.js", + "src/data/modelEligibility.js", + "src/data/fleetTrailAnchors.js", "src/data/headingDegrees.js", "src/layers/vessels/cards.js", + "src/geo/index.js", "src/layers/vessels/evidence.js", "src/layers/vessels/index.js", "src/layers/vessels/ingestion.js", "src/layers/vessels/motion.js", "src/time/snapshotTimeline.js", + "src/time/timelineFixes.js", "src/time/worldClock.js", "src/sources/live/contract.js", "src/layers/vessels/cameraArea.js", + "src/geo/ellipsoid.js", "src/layers/vessels/viewArea.js", "src/layers/vessels/lifecycle.js", "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", + "src/geo/vector.js", "src/layers/vessels/rendering.js", + "src/render/camera/poseSignature.js", + "src/render/motion/iconBook.js", + "src/layers/vessels/iconBook.js", + "src/data/entityRecords.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", "src/layers/vessels/selection.js", + "src/data/followed.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", "src/layers/vessels/tracking.js", @@ -1702,8 +2184,6 @@ "src/layers/vessels/records.js", "src/layers/vessels/recordPolicy.js", "src/layers/vessels/snapshotRenderer.js", - "src/layers/vessels/cockpitSubject.js", - "src/geoDistance.js", "src/data/inputOwnership.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1720,18 +2200,287 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/credits.js", + "src/queries/heights.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/frame.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/rendererOf.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/layers/vessels/cockpitSubject.js", + "src/geoDistance.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", "src/layers/vessels/photos.js", "src/data/openVesselPhoto.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] + }, + "render-cesium-plugin": { + "exports": ["./render/cesium/plugin"], + "modules": [ + "src/render/cesium/plugin.js", + "src/render/cesium/appRenderer.js", + "src/render/cesium/renderFailure.js", + "src/share/shareLinkPath.js", + "src/app/errors.js", + "src/render/cesium/applicationViewer.js", + "src/render/rendererOf.js", + "src/globeInView.js", + "src/render/cesium/mapEngine.js", + "src/render/contract/index.js", + "src/render/cesium/freeLookLimit.js", + "src/render/cesium/sceneCommandRelease.js", + "src/render/cesium/ports.js", + "src/render/cesium/creditKeyboard.js", + "src/render/cesium/viewers.js", + "src/render/cesium/input.js", + "src/i18n/index.js", + "src/app/atmosphereCompat.js", + "src/render/cesium/imageryLookAhead.js", + "src/render/cesium/starrySky.js", + "src/geo/ellipsoid.js", + "src/data/followed.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/maps/engine.js", + "src/render/cesium/mapImagery.js", + "src/render/cesium/mapTerrain.js", + "src/render/cesium/google3d.js", + "src/render/cesium/internals.js", + "src/render/cesium/controlledCamera.js", + "src/render/cesium/common.js", + "src/render/cesium/camera.js", + "src/render/cesium/credits.js", + "src/render/cesium/frame.js", + "src/render/cesium/gpuIcons.js", + "src/render/cesium/effects.js", + "src/render/cesium/globe.js", + "src/render/cesium/query.js", + "src/render/cesium/quality.js", + "src/render/input/wheel.js", + "src/render/input/router.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/draw.js", + "src/i18n/locale.js", + "src/i18n/locales/ar.json", + "src/i18n/locales/es.json", + "src/i18n/locales/de.json", + "src/i18n/locales/fr.json", + "src/i18n/locales/he.json", + "src/i18n/locales/ja.json", + "src/i18n/locales/it.json", + "src/i18n/locales/pt.json", + "src/i18n/locales/sv.json", + "src/i18n/locales/ru.json", + "src/i18n/locales/zh-CN.json", + "src/i18n/locales/zh-Hant.json", + "src/i18n/locales/uk.json", + "src/cockpitOrbital.js", + "src/data/bundledJson.js", + "src/renderGovernor.js", + "src/sky/stars.js", + "src/data/entityRecords.js", + "src/sky/icrf.js", + "src/render/applicationHooks.js", + "src/maps/attribution.js", + "src/maps/globeEngine.js", + "src/maps/terrainRetry.js", + "src/maps/startupRoute.js", + "src/maps/keylessTerrain.js", + "src/render/stub/viewRectangle.js", + "src/render/cesium/follow.js", + "src/time/frameWait.js", + "src/render/cesium/cameraControls.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/creditMarkup.js", + "src/render/cesium/nativeClick.js", + "src/data/iconSegment.js", + "src/data/iconSet.js", + "src/data/iconAtlas.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/heights.js", + "src/render/baseTilesets.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/vectorBase.js", + "src/render/cesium/imagery.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/vectorBase/index.js", + "src/render/cesium/drawHit.js", + "src/geo/polyline.js", + "src/geo/screenCluster.js", + "src/geo/celestial.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/render/cesium/drawFields.js", + "src/render/stub/math.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/zoomOutGuard.js", + "src/geo/index.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/geo/horizon.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/aircraftRecession.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/imageryFrames.js", + "src/render/occlusion/depthProbe.js", + "src/render/vectorBase/style.js", + "src/render/cesium/drawStreamlines.js", + "src/render/vectorBase/expressions.js", + "src/geo/quaternion.js", + "src/geo/geodesic.js", + "src/data/detectionOcclusion.js", + "src/render/vectorBase/paint.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/sky/assets.js" + ], + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] + }, + "render-cesium-unbound": { + "exports": ["./render/cesium/unbound"], + "modules": [ + "src/render/stub/viewRectangle.js", + "src/render/stub/math.js", + "src/render/cesium/unbound.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/google3d.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/drawHit.js", + "src/queries/heights.js", + "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/celestial.js", + "src/geo/ellipsoid.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/nativeClick.js", + "src/render/input/router.js", + "src/render/input/wheel.js", + "src/render/cesium/input.js", + "src/maps/engine.js", + "src/maps/attribution.js", + "src/maps/startupRoute.js", + "src/render/cesium/mapImagery.js", + "src/maps/terrainRetry.js", + "src/render/cesium/mapTerrain.js", + "src/render/cesium/mapEngine.js", + "src/data/bundledJson.js", + "src/renderGovernor.js", + "src/sky/icrf.js", + "src/sky/stars.js", + "src/sky/assets.js", + "src/render/cesium/starrySky.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", + "src/time/frameWait.js" + ], + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "earthquakes": { "exports": ["./layers/earthquakes"], "modules": [ "src/layers/earthquakes/index.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", "src/layers/earthquakes/model.js", "src/layers/earthquakes/source.js", - "src/layers/earthquakes/records.js" + "src/layers/earthquakes/records.js", + "src/time/worldClock.js" ], "external": ["cesium"] }, @@ -1740,6 +2489,9 @@ "modules": [ "src/i18n/marker.js", "src/layers/recentImagery/index.js", + "src/render/rendererOf.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", "src/layers/recentImagery/source.js", "src/layers/recentImagery/model.js", "src/layers/recentImagery/catalog.js", @@ -1762,7 +2514,11 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", - "src/layers/recentImagery/display.js" + "src/layers/recentImagery/display.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js", + "src/maps/keylessTerrain.js" ], "external": ["cesium"] }, @@ -1770,20 +2526,53 @@ "exports": ["./layers/firms"], "modules": [ "src/data/firmsAdapt.js", - "src/data/firmsIntensity.js", - "src/data/firmsHeatRaster.js", "src/data/firmsLabels.js", "src/data/iconOrientation.js", "src/layers/firms/anchors.js", "src/layers/firms/cards.js", + "src/geo/index.js", + "src/geo/julian.js", + "src/render/rendererOf.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", "src/layers/firms/index.js", "src/layers/firms/ingestion.js", "src/layers/firms/lifecycle.js", "src/layers/firms/model.js", + "src/geo/ellipsoid.js", + "src/geo/rectangle.js", + "src/geo/vector.js", "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", - "src/layers/firms/heatImagery.js", + "src/data/entityRecords.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", @@ -1803,33 +2592,85 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/data/firmsIntensity.js", + "src/data/firmsHeatRaster.js", + "src/layers/firms/heatImagery.js", + "src/render/color.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "satellites-layer": { "exports": ["./layers/satellites"], "modules": [ "src/data/satelliteClass.js", - "src/data/satelliteClassMask.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/data/satellitePass.js", "src/sources/tle.js", "src/layers/satellites/catalog.js", - "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", "src/layers/satellites/ingestion.js", "src/layers/satellites/interaction.js", + "src/data/followed.js", "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", + "src/layers/satellites/motion.js", "src/layers/satellites/orbits.js", "src/layers/satellites/records.js", "src/layers/satellites/policy.js", + "src/render/color.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", "src/layers/satellites/state.js", "src/layers/satellites/testing.js", "src/layers/satellites/tracking.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", "src/data/inputOwnership.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1847,35 +2688,108 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/ellipsoid.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/rendererOf.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/time/worldClock.js", + "src/data/satelliteClassMask.js", + "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", "src/data/bundledJson.js", "src/data/retryableLoad.js", - "src/time/worldClock.js" + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "satellite.js"] + "external": ["cesium", "satellite.js", "kdbush"] }, "launches-layer": { "exports": ["./layers/launches"], "modules": [ "src/cyberSonar.js", "src/layers/launches/camera.js", + "src/geo/sphere.js", + "src/geo/geodesic.js", + "src/layers/launches/geometry.js", "src/layers/launches/controls.js", "src/layers/launches/index.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", "src/layers/launches/ingestion.js", "src/layers/launches/launchPad.js", "src/layers/launches/lifecycle.js", "src/layers/launches/model.js", + "src/render/color.js", + "src/geo/index.js", "src/layers/launches/orbitRendering.js", "src/layers/launches/overlays.js", "src/layers/launches/panel.js", "src/layers/launches/paths.js", "src/layers/launches/policy.js", "src/layers/launches/policyHelpers.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/launches/rendering.js", + "src/geo/horizon.js", "src/layers/launches/replay.js", + "src/data/followed.js", "src/layers/launches/selection.js", "src/layers/launches/source.js", "src/layers/launches/state.js", @@ -1896,24 +2810,79 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/time/worldClock.js" + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/time/worldClock.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "installations-layer": { "exports": ["./layers/installations"], "modules": [ - "src/data/cameraSensitivity.js", "src/data/installationFeedback.js", "src/data/militaryInstallationData.js", "src/data/installationNames.js", "src/layers/installations/controls.js", + "src/geo/geodesic.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconAtlas.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/geo/index.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/installations/index.js", "src/layers/installations/ingestion.js", "src/layers/installations/lifecycle.js", "src/layers/installations/model.js", + "src/render/color.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", + "src/geo/sphere.js", + "src/data/followed.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", @@ -1934,6 +2903,7 @@ "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/layers/installations/namedMarkers.js", + "src/geo/horizon.js", "src/data/infrastructureOverlayEntry.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -1950,9 +2920,25 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/layers/installations/classLabel.js" + "src/layers/installations/classLabel.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "@mapbox/vector-tile", "pbf"] + "external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"] }, "awareness-layer": { "exports": ["./layers/awareness"], @@ -1964,11 +2950,35 @@ "src/awarenessEcho.js", "src/cockpitMath.js", "src/data/iconOrientation.js", + "src/render/camera/poseSignature.js", "src/data/militaryAwarenessEngine.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", + "src/geo/julian.js", "src/data/installationNames.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", "src/layers/awareness/focus.js", + "src/render/cesium/camera.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/awareness/history.js", "src/layers/awareness/index.js", "src/layers/awareness/ingestion.js", @@ -1982,6 +2992,7 @@ "src/layers/awareness/rendering.js", "src/layers/awareness/state.js", "src/layers/awareness/subject.js", + "src/data/followed.js", "src/layers/awareness/testing.js", "src/ui/panelRailGeometry.js", "src/i18n/index.js", @@ -1999,18 +3010,20 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/ui/unitLabels.js", + "src/data/entityRecords.js", + "src/layers/awareness/rangeRing.js", "src/data/feedState.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", "src/ui/layerNames.js", - "src/ui/unitLabels.js" + "src/render/cesium/zoomOutGuard.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "traffic-layer": { "exports": ["./layers/traffic"], "modules": [ - "src/data/cameraSensitivity.js", "src/data/flowMatch.js", "src/data/tomtomTiles.js", "src/data/tileBudget.js", @@ -2021,6 +3034,9 @@ "src/data/trafficQueue.js", "src/layers/traffic/animation.js", "src/layers/traffic/controls.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/layers/traffic/flow.js", "src/layers/traffic/flowDecode.js", "src/layers/traffic/flowSource.js", @@ -2029,16 +3045,60 @@ "src/layers/traffic/ingestion.js", "src/sources/requestDeadline.js", "src/layers/traffic/lifecycle.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/google3d.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", "src/layers/traffic/model.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", "src/layers/traffic/policy.js", + "src/render/color.js", "src/layers/traffic/rendering.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", "src/layers/traffic/style.js", "src/layers/traffic/surface.js", + "src/render/cesium/heights.js", "src/layers/traffic/timing.js", "src/layers/traffic/viewport.js", + "src/render/rendererOf.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/aircraftRecession.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/render/motion/iconMotion.js", + "src/data/iconAtlas.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/query.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/cesium/frame.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/sources/overpassRoads.js", "src/sources/capability.js", "src/sources/httpBody.js", @@ -2063,9 +3123,28 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/queries/heights.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/render/input/wheel.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/render/input/router.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/input.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js" ], - "external": ["cesium", "pbf", "@mapbox/vector-tile"] + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "bikeshare-layer": { "exports": ["./layers/bikeshare"], @@ -2074,6 +3153,7 @@ "src/layers/bikeshare/index.js", "src/layers/bikeshare/ingestion.js", "src/layers/bikeshare/lifecycle.js", + "src/render/rendererOf.js", "src/layers/bikeshare/model.js", "src/geoDistance.js", "src/sources/gbfsStations.js", @@ -2081,13 +3161,14 @@ "src/layers/bikeshare/queries.js", "src/layers/bikeshare/registry.js", "src/layers/bikeshare/rendering.js", + "src/geo/ellipsoid.js", "src/layers/bikeshare/selection.js", "src/layers/bikeshare/source.js", "src/layers/bikeshare/state.js", "src/layers/bikeshare/testing.js", "src/layers/bikeshare/viewport.js", + "src/geo/vector.js", "src/data/inputOwnership.js", - "src/data/cameraSensitivity.js", "src/i18n/index.js", "src/i18n/locale.js", "src/i18n/locales/ar.json", @@ -2102,19 +3183,44 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, "cctv-layer": { "exports": ["./layers/cctv"], "modules": [ + "src/render/cesium/google3d.js", + "src/render/cesium/globe.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/tileRequests.js", "src/data/headingDegrees.js", "src/data/cctvCards.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", "src/data/cctvViewshed.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/trackingClickGesture.js", "src/layers/cctv/calibration.js", "src/layers/cctv/cards.js", @@ -2122,23 +3228,68 @@ "src/layers/cctv/controls.js", "src/layers/cctv/frames.js", "src/layers/cctv/geometry.js", + "src/data/entityRecords.js", "src/layers/cctv/geometryQueue.js", + "src/data/followed.js", "src/layers/cctv/ground.js", "src/layers/cctv/headingConfidence.js", + "src/geo/index.js", + "src/geo/julian.js", "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", + "src/geo/frames.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", "src/layers/cctv/model.js", "src/geoDistance.js", "src/layers/cctv/modelSpecs.js", "src/layers/cctv/navigation.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/render/recession.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", "src/layers/cctv/policy.js", + "src/render/color.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", + "src/render/motion/iconBook.js", + "src/geo/frustum.js", + "src/render/cesium/iconOrientation.js", + "src/render/cesium/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", @@ -2161,9 +3312,29 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js" ], - "external": ["hls.js", "cesium"] + "external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "street-level-layer": { "exports": [ @@ -2176,10 +3347,44 @@ ], "modules": [ "src/layers/streetLevel/index.js", + "src/render/cesium/credits.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/geo/index.js", + "src/geo/geodesic.js", "src/layers/streetLevel/credits.js", + "src/render/creditMarkup.js", "src/layers/streetLevel/providers/mapillary/index.js", "src/layers/streetLevel/viewerHost.js", "src/layers/streetLevel/cameraFraming.js", + "src/render/cesium/camera.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", "src/layers/streetLevel/marker.js", "src/layers/streetLevel/view.js", "src/layers/streetLevel/uiState.js", @@ -2191,6 +3396,7 @@ "src/layers/streetLevel/policy.js", "src/layers/streetLevel/state.js", "src/layers/streetLevel/lineCoverage.js", + "src/render/color.js", "src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/providers/mapillary/decode.js", @@ -2237,20 +3443,70 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/layers/streetLevel/providers/mapillary/policy.js", - "src/time/worldClock.js" + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/time/worldClock.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "pbf", "@mapbox/vector-tile", "mapillary-js"] + "external": [ + "cesium", + "pbf", + "@mapbox/vector-tile", + "mapillary-js", + "kdbush" + ] }, "alpr-cameras": { "exports": ["./layers/alpr"], "modules": [ "src/data/headingDegrees.js", "src/layers/alpr/index.js", + "src/data/followed.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", + "src/geo/horizon.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/data/inputOwnership.js", "src/data/displayText.js", @@ -2278,22 +3534,41 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "@mapbox/vector-tile", "pbf"] + "external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"] }, "radio-layer": { "exports": ["./layers/radio"], "modules": [ "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/radioCountry.js", "src/layers/radio/catalogModel.js", "src/layers/radio/categories.js", + "src/geo/index.js", + "src/geo/julian.js", "src/layers/radio/clustering.js", "src/layers/radio/controls.js", "src/layers/radio/index.js", @@ -2303,11 +3578,50 @@ "src/layers/radio/lifecycle.js", "src/layers/radio/model.js", "src/layers/radio/navigation.js", + "src/data/followed.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", "src/layers/radio/playback.js", "src/layers/radio/policy.js", "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", + "src/render/color.js", + "src/render/cesium/iconOrientation.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -2330,9 +3644,27 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/internals.js", + "src/data/firmsIntensity.js", + "src/data/satelliteClassMask.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "submarine-cables": { "exports": ["./layers/submarine-cables"], @@ -2340,11 +3672,39 @@ "src/layers/submarineCables/geometry.js", "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", + "src/geo/index.js", "src/layers/submarineCables/interaction.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/layers/submarineCables/pin.js", + "src/data/entityRecords.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/render/color.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/data/inputOwnership.js", @@ -2362,9 +3722,24 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "bundled-cables": { "exports": ["./sources/bundled-cables"], @@ -2401,15 +3776,65 @@ "modules": [ "src/i18n/marker.js", "src/maps/availability.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/maps/catalog.js", "src/maps/controller.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/credits.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/camera.js", + "src/render/cesium/cameraControls.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", "src/maps/imageryComparison.js", "src/maps/credits.js", + "src/render/rendererOf.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/creditMarkup.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", "src/maps/terrainRetry.js", "src/keySetupCore.mjs", "src/localRequestGate.mjs", @@ -2428,9 +3853,33 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/render/cesium/input.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/maps/attribution.js", + "src/maps/startupRoute.js", + "src/maps/engine.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js" ], - "external": ["cesium"] + "external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"] }, "voice-connection": { "exports": [ @@ -2493,6 +3942,7 @@ "src/voice/narration.js", "src/voice/earcon.js", "src/voice/pointerContext.js", + "src/render/rendererOf.js", "src/voice/pointerReticle.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -2545,6 +3995,26 @@ "./standalone/catalog" ], "modules": [ + "src/render/stub/viewRectangle.js", + "src/render/stub/math.js", + "src/render/cesium/controlledCamera.js", + "src/geo/index.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/eyeMoves.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/data/fleetModels.js", + "src/data/fleetTrailAnchors.js", + "src/data/fleetModelInstances.js", + "src/app/layers/fleetModels.js", "src/sources/adsbFields.js", "src/data/headingDegrees.js", "src/data/distanceFormat.js", @@ -2555,10 +4025,15 @@ "src/hudLayouts.js", "src/hudLayoutPolicy.js", "src/ui/radioPanelPlacement.js", - "src/cyberSonarGpu.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", "src/scenes/nepalEvidencePack.js", "src/data/approxDistance.js", "src/data/bhoteKoshiEvent.js", + "src/render/cesium/heights.js", "src/ui/imagerySplit.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", @@ -2599,22 +4074,54 @@ "src/app/layers/traffic.js", "src/app/operations.js", "src/app/scene.js", - "src/app/zoomOutGuard.js", + "src/render/cesium/sceneCommandRelease.js", + "src/render/cesium/appRenderer.js", + "src/render/cesium/renderFailure.js", + "src/render/cesium/frame.js", + "src/render/creditMarkup.js", + "src/render/rendererOf.js", + "src/render/cesium/ports.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/query.js", + "src/render/cesium/globe.js", + "src/render/baseTilesets.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/quality.js", + "src/render/cesium/credits.js", + "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/common.js", + "src/render/cesium/camera.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/follow.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/contract/index.js", "src/sources/sourceSlot.js", "src/app/sources.js", "src/app/startupChrome.js", "src/app/stateChannel.js", "src/app/surfaceServices.js", "src/app/tools.js", - "src/app/viewer.js", - "src/sky/starrySky.js", + "src/data/followed.js", + "src/render/cesium/applicationViewer.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/starrySky.js", "src/sky/stars.js", "src/app/atmosphereCompat.js", "src/bloom.js", "src/camera.js", "src/cameraGroundGuard.js", "src/cameraVerbs.js", - "src/globeInView.js", "src/cctvFocusPolicy.js", "src/cctvFocusRequest.js", "src/celestialRing.js", @@ -2623,14 +4130,9 @@ "src/cockpitTracking.js", "src/cockpitUtilityLayout.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", "src/contactsDetectionPolicy.js", "src/contextModePolicy.js", - "src/creditKeyboard.js", + "src/render/cesium/creditKeyboard.js", "src/data/aircraftClass.js", "src/data/aircraftEmergency.js", "src/data/aircraftIcons.js", @@ -2667,19 +4169,19 @@ "src/layers/wind/source.js", "src/sources/windBody.js", "src/data/detection.js", + "src/render/cesium/iconOrientation.js", "src/data/detectionCohort.js", "src/data/detectionDraw.js", "src/data/detectionPolicy.js", "src/data/detectionOcclusion.js", "src/data/detectionPresentation.js", "src/data/detectionRenderDemand.js", - "src/data/sceneOcclusionProbe.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", "src/data/earthquakes.js", "src/data/fireAnchors.js", "src/data/firmsAdapt.js", "src/data/firmsHeatmap.js", - "src/data/firmsIntensity.js", - "src/data/firmsHeatRaster.js", "src/data/firmsLabels.js", "src/data/flights.js", "src/data/flowMatch.js", @@ -2688,17 +4190,19 @@ "src/data/groundFloor.js", "src/data/groundSnap.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/infrastructure.js", "src/data/osmOverlays.js", "src/data/installationFeedback.js", "src/data/labelArbiter.js", "src/data/idSwitches.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/lifecycle.js", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/regions.json", @@ -2743,7 +4247,6 @@ "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", - "src/data/trackedModelRegime.js", "src/data/trackedReadout.js", "src/data/trackingClickGesture.js", "src/data/traffic.js", @@ -2773,6 +4276,7 @@ "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", @@ -2818,6 +4322,8 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", + "src/layers/launches/geometry.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", "src/layers/cctv/model.js", @@ -2844,27 +4350,34 @@ "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", - "src/layers/firms/heatImagery.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/clockFollow.js", "src/time/snapshotTimeline.js", + "src/data/timelineHistory.js", + "src/time/timelineFixes.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelRecord.js", "src/layers/flights/state.js", + "src/data/displayDelay.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/installations/controls.js", + "src/geo/geodesic.js", "src/layers/installations/index.js", "src/layers/installations/ingestion.js", "src/layers/installations/lifecycle.js", @@ -2903,6 +4416,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", @@ -2922,6 +4436,7 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -2929,13 +4444,13 @@ "src/layers/radio/tuningNoise.js", "src/layers/radio/volume.js", "src/layers/satellites/catalog.js", - "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", "src/layers/satellites/ingestion.js", "src/layers/satellites/interaction.js", "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", + "src/layers/satellites/motion.js", "src/layers/satellites/orbits.js", "src/sources/tle.js", "src/layers/satellites/records.js", @@ -2950,10 +4465,13 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pin.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", @@ -2987,6 +4505,8 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/render/motion/iconBook.js", + "src/layers/vessels/iconBook.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -3005,10 +4525,12 @@ "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", "src/maps/terrainRetry.js", "src/navigationPolicy.js", "src/orbit.js", @@ -3056,8 +4578,8 @@ "src/styles/surveillance.js", "src/styles/thermal.js", "src/ui/applicationShell.js", + "src/ui/railEdgeScroll.js", "src/ui/mobileShell.js", - "src/exclusiveSurfaces.js", "src/ui/localePicker.js", "src/ui/cyberSonarControls.js", "src/ui/locationNavigation.js", @@ -3071,7 +4593,6 @@ "src/ui/cctvFrames.js", "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", - "src/ui/quebecCctvOverlay.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", @@ -3081,21 +4602,14 @@ "src/ui/cockpitInstrumentState.js", "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.js", - "src/ui/cockpitOrbitalView.js", - "src/ui/cockpitOrbitalFocus.js", - "src/ui/cockpitOrbitalSignals.js", - "src/ui/cockpitOrbitalSatellites.js", - "src/cockpitOrbitalSatellites.js", - "src/data/placeBelow.js", - "src/ui/placePacksLoading.js", - "src/ui/ownerFlag.js", - "src/ui/ownerFlagSheet.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", "src/ui/cockpitInstruments.js", + "src/cockpitSubjectProviders.js", + "src/cockpitProgress.js", "src/ui/cockpitLayout.js", "src/ui/cockpitPresentation.js", "src/ui/cockpitSignals.js", @@ -3125,7 +4639,6 @@ "src/ui/layerPanel/RowSwitch.vue", "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", - "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -3162,6 +4675,7 @@ "src/ui/surfaceKeyboard.js", "src/ui/uiLifetime.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualInput.js", "src/ui/visualPresets.js", "src/ui/visualSettings.js", @@ -3211,22 +4725,24 @@ "src/layers/vessels/records.js", "src/layers/vessels/recordPolicy.js", "src/layers/vessels/snapshotRenderer.js", - "src/layers/vessels/cockpitSubject.js", "src/data/inputOwnership.js", "src/annotations/drawMarks.js", "src/annotations/drawMode.js", "src/annotations/drawTool.js", "src/data/geoFileImport.js", + "src/data/geoImportFeatures.js", + "src/data/geoImportShared.js", "src/ui/flyToDataSource.js", "src/ui/geoFileImport.js", "src/data/routeSteps.js", "src/layers/directions/index.js", - "src/data/pointerOwnerNames.js", "src/layers/directions/source.js", "src/data/directions.js", "src/app/layers/directions.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/voice/session.js", "src/voice/sessionCommands.js", @@ -3239,12 +4755,14 @@ "src/layers/earthquakes/records.js", "src/app/layers/perimeters.js", "src/layers/perimeters/index.js", + "src/render/color.js", "src/layers/perimeters/source.js", "src/layers/perimeters/records.js", "src/layers/perimeters/cards.js", "src/layers/perimeters/inciweb.js", "src/app/layers/gnss.js", "src/layers/gnss/index.js", + "src/geo/rectangle.js", "src/layers/gnss/source.js", "src/layers/gnss/records.js", "src/app/layers/ghostMaps.js", @@ -3283,6 +4801,7 @@ "src/app/layers/rail.js", "src/data/railFeeds.js", "src/layers/rail/index.js", + "src/layers/rail/cockpitSubject.js", "src/layers/rail/source.js", "src/layers/rail/policy.js", "src/layers/rail/ingestion.js", @@ -3303,12 +4822,12 @@ "src/data/railTimeZones.js", "src/data/transit.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/layers/transit/controls.js", "src/layers/transit/height.js", "src/layers/transit/index.js", + "src/layers/transit/cockpitSubject.js", "src/layers/transit/ingestion.js", "src/layers/transit/lifecycle.js", "src/layers/transit/policy.js", @@ -3318,7 +4837,6 @@ "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", "src/data/transitProxy.js", @@ -3390,6 +4908,7 @@ "src/layers/weather/imageryHost.js", "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", + "src/geo/sphere.js", "src/layers/cyclones/labels.js", "src/layers/cyclones/source.js", "src/app/layers/localAdsb.js", @@ -3679,7 +5198,6 @@ "src/ui/rail/RailCards.vue", "src/ui/rail/RailCardBlocks.vue", "src/ui/rail/utcClock.js", - "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", "src/ui/newsPanel.js", @@ -3695,7 +5213,6 @@ "src/ui/stores/cockpit.js", "src/ui/stores/locale.js", "src/ui/stores/providerSettings.js", - "src/ui/stores/sceneSharing.js", "src/ui/stores/voice.js", "src/ui/stores/location.js", "src/ui/stores/display.js", @@ -3728,9 +5245,6 @@ "src/ui/stores/globeActions.js", "src/ui/stores/recording.js", "src/ui/i18n.js", - "src/time/viewerClock.js", - "src/time/worldClock.js", - "src/time/julian.js", "src/annotations/outlineRungs.js", "src/sources/openFreeMapOutlines.js", "src/sources/nominatimOutlines.js", @@ -3739,6 +5253,26 @@ "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", "src/data/local_data/wof_neighborhoods/files.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/input/dispatcher.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/pickMemo.js", + "src/maps/startupRoute.js", + "src/maps/engine.js", + "src/maps/attribution.js", + "src/render/cesium/mapEngine.js", + "src/sky/icrf.js", + "src/sky/assets.js", + "src/app/panelRendering.js", + "src/render/cesium/application.js", "src/sources/osmFeatures.js", "src/voice/imageryActions.js", "src/voice/layerActionOwnership.js", @@ -3752,6 +5286,15 @@ "src/layers/osmPlaces/index.js", "src/app/layers/osmPlaces.js", "src/voice/areaActions.js", + "src/render/cesium/zoomOutGuard.js", + "src/layers/awareness/rangeRing.js", + "src/data/firmsIntensity.js", + "src/data/firmsHeatRaster.js", + "src/layers/firms/heatImagery.js", + "src/data/rioRouteNames.js", + "src/globeInView.js", + "src/app/globeInViewRecovery.js", + "src/render/cesium/freeLookLimit.js", "src/app/layers/wildlifeSightings.js", "src/layers/wildlifeSightings/cards.js", "src/layers/wildlifeSightings/controls.js", @@ -3777,14 +5320,53 @@ "src/overlays/worldOverlayChrome.js", "src/layers/wildlifeSightings/photoText.js", "src/layers/wildlifeSightings/performance.js", + "src/layers/wildlifeSightings/iconCollection.js", + "src/layers/wildlifeSightings/view.js", + "src/ui/quebecCctvOverlay.js", + "src/time/viewerClock.js", + "src/time/worldClock.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/data/satelliteClassMask.js", + "src/layers/satellites/cockpitSubject.js", + "src/ui/cockpitOrbitalView.js", + "src/ui/cockpitOrbitalFocus.js", + "src/ui/cockpitOrbitalSignals.js", + "src/ui/cockpitOrbitalSatellites.js", + "src/cockpitOrbitalSatellites.js", + "src/data/placeBelow.js", + "src/ui/placePacksLoading.js", + "src/ui/ownerFlag.js", + "src/ui/ownerFlagSheet.js", + "src/layers/vessels/cockpitSubject.js", "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", + "src/render/cesium/imageryLookAhead.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js", + "src/ui/creditsView.js", "src/data/planespottersPhoto.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", "src/ui/stores/dataLibrary.js", "src/data/openVesselPhoto.js", - "src/layers/vessels/photos.js" + "src/layers/vessels/photos.js", + "src/viewSky.js", + "src/render/weather.js", + "src/layers/flights/placed.js", + "src/data/placementProvider.js", + "src/data/courseFromFixes.js", + "src/time/frameWait.js" ], "external": [ "hls.js", @@ -3798,9 +5380,11 @@ "@jtarrio/webrtlsdr", "hyparquet", "fzstd", + "h3-js", "vue", "pinia", - "vue-i18n" + "vue-i18n", + "kdbush" ] }, "application-catalog": { @@ -3811,6 +5395,21 @@ "application-layer-construction": { "exports": ["./application/layers"], "modules": [ + "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/fixCurve.js", + "src/data/aircraftModelLayer.js", + "src/data/aircraftMotionRegime.js", + "src/geo/julian.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/fleetModels.js", + "src/data/fleetTrailAnchors.js", + "src/data/fleetModelInstances.js", + "src/app/layers/fleetModels.js", "src/data/feedState.js", "src/loadingFeedback.js", "src/sources/adsbFields.js", @@ -3824,6 +5423,25 @@ "src/maps/imageryComparison.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", + "src/render/cesium/camera.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/imagery.js", + "src/render/cesium/imageryFrames.js", + "src/render/cesium/google3d.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/follow.js", "src/data/bhoteKoshiIncidentPlaces.js", "src/data/bhoteKoshiFloodPath.js", "src/data/bhoteKoshiShotPaths.js", @@ -3884,13 +5502,13 @@ "src/data/detectionDraw.js", "src/data/detectionPolicy.js", "src/data/firmsAdapt.js", - "src/data/firmsIntensity.js", - "src/data/firmsHeatRaster.js", "src/data/firmsLabels.js", "src/data/flowMatch.js", "src/data/focusDeemphasis.js", "src/data/geoid.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/infrastructure.js", "src/data/osmOverlays.js", "src/data/installationFeedback.js", @@ -3898,9 +5516,9 @@ "src/data/labelArbiter.js", "src/data/idSwitches.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/regions.json", @@ -3930,7 +5548,6 @@ "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", - "src/data/trackedModelRegime.js", "src/data/trackedReadout.js", "src/data/trackingClickGesture.js", "src/data/trafficBounds.js", @@ -3944,11 +5561,13 @@ "src/keylessGeocoder.js", "src/layers/aircraft/classification.js", "src/layers/alpr/index.js", + "src/data/followed.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", @@ -3994,6 +5613,8 @@ "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", + "src/layers/cctv/drawSets.js", + "src/layers/launches/geometry.js", "src/layers/cctv/ingestion.js", "src/layers/cctv/lifecycle.js", "src/layers/cctv/model.js", @@ -4004,6 +5625,7 @@ "src/layers/cctv/projection.js", "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", + "src/render/cesium/iconOrientation.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", @@ -4020,28 +5642,35 @@ "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", - "src/layers/firms/heatImagery.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/clockFollow.js", "src/time/snapshotTimeline.js", + "src/data/timelineHistory.js", + "src/time/timelineFixes.js", "src/sources/live/contract.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelRecord.js", "src/layers/flights/state.js", + "src/data/displayDelay.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/installations/controls.js", + "src/geo/geodesic.js", "src/layers/installations/index.js", "src/layers/installations/ingestion.js", "src/layers/installations/lifecycle.js", @@ -4080,6 +5709,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", @@ -4099,6 +5729,7 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -4106,13 +5737,13 @@ "src/layers/radio/tuningNoise.js", "src/layers/radio/volume.js", "src/layers/satellites/catalog.js", - "src/layers/satellites/cockpitSubject.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", "src/layers/satellites/ingestion.js", "src/layers/satellites/interaction.js", "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", + "src/layers/satellites/motion.js", "src/layers/satellites/orbits.js", "src/sources/tle.js", "src/layers/satellites/records.js", @@ -4126,10 +5757,13 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pin.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", @@ -4163,11 +5797,17 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/render/motion/iconBook.js", + "src/layers/vessels/iconBook.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", "src/layers/vessels/tracking.js", "src/locations.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/cesium/common.js", "src/cityPois.js", "src/navigationPolicy.js", "src/overlays/worldOverlay.js", @@ -4185,6 +5825,13 @@ "src/ui/panelRailGeometry.js", "src/ui/radioTunerModel.js", "src/worldFocus.js", + "src/geo/index.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/eyeMoves.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", "src/layers/flights/records.js", "src/layers/flights/recordPolicy.js", "src/layers/flights/snapshotRenderer.js", @@ -4195,18 +5842,13 @@ "src/layers/vessels/records.js", "src/layers/vessels/recordPolicy.js", "src/layers/vessels/snapshotRenderer.js", - "src/layers/vessels/cockpitSubject.js", "src/data/inputOwnership.js", "src/annotations/worldAnnotationRenderer.js", "src/cameraGroundGuard.js", "src/cameraVerbs.js", - "src/globeInView.js", - "src/scopeMaskPolicy.js", - "src/scopeMask.js", "src/services/groundFloor.js", "src/data/routeSteps.js", "src/layers/directions/index.js", - "src/data/pointerOwnerNames.js", "src/layers/directions/source.js", "src/services/terrainHeights.js", "src/data/terrainHeights.js", @@ -4215,6 +5857,8 @@ "src/app/layers/directions.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/app/localGeojsonServices.js", "src/data/displayText.js", @@ -4222,12 +5866,14 @@ "src/layers/earthquakes/records.js", "src/app/layers/perimeters.js", "src/layers/perimeters/index.js", + "src/render/color.js", "src/layers/perimeters/source.js", "src/layers/perimeters/records.js", "src/layers/perimeters/cards.js", "src/layers/perimeters/inciweb.js", "src/app/layers/gnss.js", "src/layers/gnss/index.js", + "src/geo/rectangle.js", "src/layers/gnss/source.js", "src/layers/gnss/records.js", "src/app/layers/ghostMaps.js", @@ -4267,6 +5913,7 @@ "src/app/layers/rail.js", "src/data/railFeeds.js", "src/layers/rail/index.js", + "src/layers/rail/cockpitSubject.js", "src/layers/rail/source.js", "src/layers/rail/policy.js", "src/layers/rail/ingestion.js", @@ -4286,12 +5933,12 @@ "src/data/railSchedule.js", "src/data/railTimeZones.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/layers/transit/controls.js", "src/layers/transit/height.js", "src/layers/transit/index.js", + "src/layers/transit/cockpitSubject.js", "src/layers/transit/ingestion.js", "src/layers/transit/lifecycle.js", "src/layers/transit/policy.js", @@ -4301,7 +5948,6 @@ "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", "src/data/transitProxy.js", @@ -4328,6 +5974,7 @@ "src/layers/weather/imageryHost.js", "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", + "src/geo/sphere.js", "src/layers/cyclones/labels.js", "src/layers/cyclones/source.js", "src/app/layers/localAdsb.js", @@ -4349,7 +5996,8 @@ "src/data/detectionRenderDemand.js", "src/data/detectionPresentation.js", "src/data/detectionOcclusion.js", - "src/data/sceneOcclusionProbe.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", "src/data/modelEligibility.js", "src/app/layers/recentImagery.js", "src/layers/recentImagery/index.js", @@ -4357,15 +6005,19 @@ "src/layers/recentImagery/model.js", "src/layers/recentImagery/catalog.js", "src/layers/recentImagery/rendering.js", + "src/render/baseTilesets.js", + "src/render/cesium/globe.js", "src/layers/recentImagery/thumbnails.js", "src/maps/imageryHost.js", "src/layers/streetLevel/index.js", + "src/render/cesium/credits.js", "src/layers/streetLevel/uiState.js", "src/layers/streetLevel/pickRouter.js", "src/layers/streetLevel/params.js", "src/layers/streetLevel/registry.js", "scripts/qa-street-level.mjs", "src/layers/streetLevel/credits.js", + "src/render/creditMarkup.js", "src/layers/streetLevel/providers/mapillary/index.js", "src/layers/streetLevel/viewerHost.js", "src/layers/streetLevel/cameraFraming.js", @@ -4446,7 +6098,9 @@ "src/layers/streetLevel/providers/mapillary/policy.js", "src/data/geoImportImages.js", "src/data/geoImportPins.js", + "src/data/geoImportShared.js", "src/data/geoFileImport.js", + "src/data/geoImportFeatures.js", "src/ui/stores/imagerySplit.js", "src/ui/vueRuntime.js", "src/ui/stores/windInspection.js", @@ -4454,8 +6108,6 @@ "src/ui/stores/bhoteKoshiPanel.js", "src/hudReadouts.js", "src/ui/i18n.js", - "src/time/worldClock.js", - "src/time/julian.js", "src/annotations/outlineRungs.js", "src/sources/openFreeMapOutlines.js", "src/sources/nominatimOutlines.js", @@ -4464,9 +6116,34 @@ "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", "src/data/local_data/wof_neighborhoods/files.js", + "src/data/entityRecords.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", "src/layers/osmPlaces/model.js", "src/layers/osmPlaces/index.js", "src/app/layers/osmPlaces.js", + "src/layers/awareness/rangeRing.js", + "src/data/feedState.js", + "src/loadingFeedback.js", + "src/data/firmsIntensity.js", + "src/data/firmsHeatRaster.js", + "src/layers/firms/heatImagery.js", + "src/data/rioRouteNames.js", + "src/globeInView.js", + "src/scopeMaskPolicy.js", + "src/scopeMask.js", "src/app/layers/wildlifeSightings.js", "src/layers/wildlifeSightings/cards.js", "src/layers/wildlifeSightings/controls.js", @@ -4490,13 +6167,34 @@ "src/overlays/worldOverlayChrome.js", "src/layers/wildlifeSightings/photoText.js", "src/layers/wildlifeSightings/performance.js", + "src/layers/wildlifeSightings/view.js", + "src/layers/wildlifeSightings/iconCollection.js", + "src/time/worldClock.js", + "src/data/satelliteClassMask.js", + "src/layers/satellites/cockpitSubject.js", + "src/layers/vessels/cockpitSubject.js", "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", + "src/render/cesium/viewers.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js", "src/data/planespottersPhoto.js", + "src/render/cesium/zoomOutGuard.js", + "src/maps/keylessTerrain.js", + "src/render/cesium/vectorBase.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", "src/layers/vessels/photos.js", - "src/data/openVesselPhoto.js" + "src/data/openVesselPhoto.js", + "src/layers/flights/placed.js", + "src/data/placementProvider.js", + "src/data/courseFromFixes.js", + "src/time/frameWait.js" ], "external": [ "hls.js", @@ -4508,9 +6206,11 @@ "mgrs", "mapillary-js", "@jtarrio/webrtlsdr", + "h3-js", "vue", "pinia", - "vue-i18n" + "vue-i18n", + "kdbush" ] }, "application-operations": { @@ -4540,8 +6240,49 @@ "src/keylessGeocoder.js", "src/layers/firms/anchors.js", "src/locations.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/entityRecords.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", "src/cityPois.js", "src/cameraGroundGuard.js", + "src/data/followed.js", "src/search/alpsGeocoder.js", "src/search/defaults.js", "src/search/geospatial.js", @@ -4556,6 +6297,8 @@ "src/services/terrainHeights.js", "src/search/coordinateGeocoder.js", "src/search/coordinateParser.js", + "src/search/gridReference.js", + "src/search/plusCode.js", "src/search/presetGeocoder.js", "src/search/nominatim.js", "src/nominatimGeocode.js", @@ -4585,7 +6328,21 @@ "src/data/placeBoundaries.js", "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", - "src/data/local_data/wof_neighborhoods/files.js" + "src/data/local_data/wof_neighborhoods/files.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/data/pickRegistry.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/render/cesium/nativeClick.js", + "src/render/cesium/input.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], "external": [ "cesium", @@ -4593,9 +6350,40 @@ "satellite.js", "@mapbox/vector-tile", "pbf", - "mgrs" + "mgrs", + "kdbush" ] }, + "entity-records": { + "exports": ["./data/entity-records"], + "modules": ["src/data/entityRecords.js"], + "external": [] + }, + "input": { + "exports": ["./input"], + "modules": [ + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/render/rendererOf.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" + ], + "external": ["cesium"] + }, "layer-lifecycle": { "exports": ["./data/lifecycle"], "modules": [ @@ -4609,7 +6397,32 @@ "exports": ["./ui/navigation"], "modules": [ "src/navigationPolicy.js", + "src/geo/index.js", "src/ui/navigationController.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/queries/heights.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/data/followed.js", "src/app/stateChannel.js", "src/data/cameraArrival.js", "src/i18n/locale.js", @@ -4626,9 +6439,25 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/i18n/index.js" + "src/i18n/index.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/follow.js", + "src/render/cesium/internals.js", + "src/render/cesium/common.js", + "src/data/entityRecords.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "ui-share-restoration": { "exports": ["./ui/share-restoration"], @@ -4636,15 +6465,14 @@ "src/i18n/marker.js", "src/data/installationFeedback.js", "src/data/idSwitches.js", - "src/data/firmsIntensity.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/loadingFeedback.js", "src/navigationPolicy.js", "src/share/follow.js", "src/ui/shareRestoration.js", + "src/data/followed.js", "src/ui/uiLifetime.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -4661,7 +6489,11 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/time/worldClock.js" + "src/data/entityRecords.js", + "src/render/rendererOf.js", + "src/data/firmsIntensity.js", + "src/time/worldClock.js", + "src/data/satelliteClassMask.js" ], "external": [] }, @@ -4674,14 +6506,6 @@ "src/ui/radioPanelPlacement.js", "src/bloom.js", "src/cockpitVisionPolicy.js", - "src/cockpitSubjects.js", - "src/cockpitRadar.js", - "src/cockpitLook.js", - "src/cockpitOrbital.js", - "src/cockpitOrbitalFocus.js", - "src/cockpitOrbitalSatellites.js", - "src/geoDistance.js", - "src/data/motionModel.js", "src/contactsDetectionPolicy.js", "src/data/detectionPolicy.js", "src/styles/anime.js", @@ -4695,9 +6519,11 @@ "src/ui/rail/rangeValue.js", "src/ui/uiLifetime.js", "src/ui/visualEffects.js", + "src/styles/styleStages.js", "src/ui/visualInput.js", "src/ui/visualPresets.js", "src/ui/visualSettings.js", + "src/render/rendererOf.js", "src/ui/stores/display.js", "src/ui/stores/owners.js", "src/ui/vueRuntime.js", @@ -4722,7 +6548,15 @@ "src/visualStylePolicy.js", "src/ui/rail/fieldValue.js", "src/ui/kit/UiSlider.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/cockpitSubjects.js", + "src/cockpitRadar.js", + "src/cockpitLook.js", + "src/cockpitOrbital.js", + "src/cockpitOrbitalFocus.js", + "src/cockpitOrbitalSatellites.js", + "src/geoDistance.js", + "src/data/motionModel.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -4776,7 +6610,11 @@ "src/data/approxDistance.js", "src/data/renderAltitude.js", "src/data/aircraftClass.js", - "src/data/aircraftEmergency.js" + "src/data/aircraftEmergency.js", + "src/data/fleetModels.js", + "src/data/vesselTypes.js", + "src/data/fleetTrailAnchors.js", + "src/data/courseFromFixes.js" ], "external": [] }, @@ -4798,7 +6636,9 @@ "src/data/aircraftMeta.js", "src/data/renderAltitude.js", "src/data/aircraftClass.js", - "src/data/aircraftEmergency.js" + "src/data/aircraftEmergency.js", + "src/data/courseFromFixes.js", + "src/data/approxDistance.js" ], "external": [] }, @@ -4814,7 +6654,8 @@ "exports": ["./layers/vessels/records"], "modules": [ "src/layers/vessels/records.js", - "src/layers/vessels/recordPolicy.js" + "src/layers/vessels/recordPolicy.js", + "src/time/timelineFixes.js" ], "external": [] }, @@ -4847,7 +6688,10 @@ "src/data/distanceFormat.js", "src/i18n/marker.js", "src/layers/directions/index.js", - "src/data/pointerOwnerNames.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", + "src/render/color.js", "src/layers/directions/source.js", "src/data/routeSteps.js", "src/i18n/index.js", @@ -4865,7 +6709,25 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/unitLabels.js" + "src/ui/unitLabels.js", + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -5165,13 +7027,56 @@ "transit-standalone": { "exports": ["./layers/transit/standalone"], "modules": [ + "src/data/fleetModels.js", + "src/data/vesselTypes.js", + "src/data/aircraftClass.js", + "src/i18n/marker.js", + "src/data/fleetModelInstances.js", + "src/data/modelEligibility.js", + "src/data/fleetTrailAnchors.js", + "src/data/aircraftModelLighting.js", "src/data/headingDegrees.js", "src/cyberSonar.js", "src/celestialRing.js", + "src/render/cesium/camera.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/iconAtlas.js", + "src/render/cesium/frame.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/cameraControls.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/follow.js", + "src/render/rendererOf.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/cesium/common.js", "src/data/approxDistance.js", - "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", + "src/render/color.js", "src/data/dataCredits.js", "src/data/detectionCohort.js", "src/data/detectionPolicy.js", @@ -5180,6 +7085,8 @@ "src/data/gtfsRealtime.js", "src/geoDistance.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/inputOwnership.js", "src/data/labelArbiter.js", "src/data/meshFloorSampler.js", @@ -5188,14 +7095,16 @@ "src/data/spriteOrder.js", "src/data/terrainHeights.js", "src/data/transit.js", + "src/geo/index.js", + "src/geo/geodesic.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/data/transitProxy.js", "src/layers/transit/controls.js", "src/layers/transit/height.js", "src/layers/transit/index.js", + "src/layers/transit/cockpitSubject.js", "src/layers/transit/ingestion.js", "src/layers/transit/lifecycle.js", "src/layers/transit/movement.js", @@ -5203,11 +7112,14 @@ "src/layers/transit/qaMetrics.js", "src/layers/transit/queries.js", "src/layers/transit/rendering.js", + "src/geo/frustum.js", + "src/render/cesium/iconOrientation.js", "src/layers/transit/selection.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/trails.js", "src/layers/transit/viewport.js", + "src/geo/rectangle.js", "src/overlays/worldOverlay.js", "src/overlays/worldOverlayDraw.js", "src/overlays/worldOverlayTokens.js", @@ -5240,40 +7152,105 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/data/rioRouteNames.js", + "src/overlays/worldOverlayChrome.js", "src/time/worldClock.js", - "src/overlays/worldOverlayChrome.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "egm96-universal", "pbf"] + "external": ["cesium", "egm96-universal", "pbf", "kdbush"] }, "transit-layer": { "exports": ["./layers/transit"], "modules": [ + "src/i18n/marker.js", + "src/data/fleetModels.js", + "src/data/vesselTypes.js", + "src/data/fleetModelInstances.js", + "src/data/aircraftClass.js", + "src/data/aircraftModelLighting.js", + "src/data/fleetTrailAnchors.js", + "src/data/modelEligibility.js", "src/data/headingDegrees.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", + "src/render/camera/poseSignature.js", "src/data/inputOwnership.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/geoDistance.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", "src/layers/transit/controls.js", "src/layers/transit/height.js", "src/layers/transit/index.js", + "src/layers/transit/cockpitSubject.js", "src/layers/transit/ingestion.js", "src/layers/transit/lifecycle.js", "src/layers/transit/policy.js", "src/layers/transit/queries.js", "src/layers/transit/rendering.js", + "src/geo/frustum.js", + "src/render/cesium/iconOrientation.js", "src/layers/transit/selection.js", + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/julian.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", - "src/data/cameraSensitivity.js", + "src/geo/rectangle.js", + "src/render/rendererOf.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/iconSet.js", + "src/geo/horizon.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/data/iconAtlas.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/frame.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", + "src/render/color.js", "src/data/transitProxy.js", "src/data/gtfsRealtime.js", "src/layers/transit/trails.js", + "src/geo/ellipsoid.js", "src/layers/transit/movement.js", "src/layers/transit/qaMetrics.js", "src/layers/transit/qaMetrics.test.mjs", @@ -5297,9 +7274,34 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/time/worldClock.js" + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/geo/vector.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/internals.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/nativeClick.js", + "src/data/rioRouteNames.js", + "src/time/worldClock.js", + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium", "pbf"] + "external": ["cesium", "pbf", "kdbush"] }, "transit-source-factory": { "exports": ["./layers/transit/source"], @@ -5398,6 +7400,10 @@ "exports": ["./layers/perimeters"], "modules": [ "src/layers/perimeters/index.js", + "src/render/color.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/layers/perimeters/source.js", @@ -5418,7 +7424,25 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/inputOwnership.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/scenePick.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -5426,6 +7450,11 @@ "exports": ["./layers/gnss"], "modules": [ "src/layers/gnss/index.js", + "src/render/color.js", + "src/geo/rectangle.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/layers/gnss/source.js", @@ -5448,7 +7477,7 @@ "src/ui/statusText.js", "src/ui/layerNames.js" ], - "external": ["cesium"] + "external": ["cesium", "h3-js"] }, "gnss-source": { "exports": ["./layers/gnss/source"], @@ -5495,12 +7524,17 @@ "exports": ["./layers/ghostmaps"], "modules": [ "src/layers/ghostMaps/index.js", + "src/render/color.js", + "src/geo/index.js", + "src/geo/julian.js", "src/layers/ghostMaps/catalog.js", "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", "src/layers/ghostMaps/source.js", "src/sources/httpBody.js", "src/data/geoFileImport.js", + "src/data/geoImportFeatures.js", + "src/data/geoImportShared.js", "src/i18n/marker.js", "src/i18n/index.js", "src/i18n/locale.js", @@ -5519,10 +7553,66 @@ "src/i18n/locales/zh-Hant.json", "src/data/geoImportImages.js", "src/data/geoImportPins.js", + "src/data/geojsonPins.js", + "src/geo/sphere.js", + "src/data/followed.js", "src/layers/streetLevel/tileMath.js", - "src/layers/streetLevel/view.js" + "src/layers/streetLevel/view.js", + "src/geo/ellipsoid.js", + "src/geo/horizon.js", + "src/geo/vector.js", + "src/data/inputOwnership.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js", + "src/data/pickRegistry.js", + "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/recession.js", + "src/data/aircraftRecession.js", + "src/data/motionModel.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/query.js", + "src/render/cesium/heights.js", + "src/render/cesium/draw.js", + "src/render/cesium/setBlend.js", + "src/geo/screenCluster.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawModels.js", + "src/geo/polyline.js", + "src/render/cesium/gpuIcons.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/frame.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/common.js", + "src/render/cesium/internals.js", + "src/render/rendererOf.js", + "src/data/entityRecords.js", + "src/render/cesium/input.js", + "src/render/input/wheel.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/cameraControls.js", + "src/render/input/router.js", + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js" ], - "external": ["cesium"] + "external": ["cesium", "kdbush"] }, "ghostmaps-source": { "exports": ["./layers/ghostmaps/source"], @@ -5578,7 +7668,17 @@ "src/i18n/locales/sv.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/render/color.js", + "src/input/dispatcher.js", + "src/geo/vector.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/styles/styleStages.js" ], "external": ["cesium"] }, @@ -5612,18 +7712,16 @@ "src/tools/queries/brief.js", "src/tools/queries/maritime.js", "src/tools/queries/share.js", - "src/data/firmsIntensity.js", - "src/data/firmsAdapt.js", "src/data/idSwitches.js", "src/data/vesselTypes.js", "src/data/layerState.js", - "src/data/satelliteClassMask.js", "src/data/layerStateTokenReservations.json", "src/sources/gbfsStations.js", "src/sources/tle.js", "src/data/satellitePass.js", "src/tools/queries/atmosphere.js", "src/layers/wind/inspection.js", + "src/geo/ellipsoid.js", "src/layers/wind/model.js", "src/layers/wind/fields.js", "src/i18n/marker.js", @@ -5637,7 +7735,6 @@ "src/tools/surfaces.js", "src/layers/transit/policy.js", "src/data/transitFeeds.js", - "src/data/rioRouteNames.js", "src/layers/transit/movement.js", "src/data/contactPlayback.js", "src/data/layerSnapshot.js", @@ -5649,7 +7746,12 @@ "src/tools/globePanel.js", "src/tools/queries/panelRequest.js", "src/geoDistance.js", - "src/visualStylePolicy.js" + "src/visualStylePolicy.js", + "src/geo/vector.js", + "src/data/firmsIntensity.js", + "src/data/firmsAdapt.js", + "src/data/rioRouteNames.js", + "src/data/satelliteClassMask.js" ], "external": ["satellite.js"] }, @@ -5770,6 +7872,10 @@ "exports": ["./layers/air-quality"], "modules": [ "src/layers/airQuality/index.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", + "src/render/color.js", "src/layers/airQuality/model.js", "src/layers/airQuality/source.js", "src/sources/httpBody.js", @@ -5807,15 +7913,130 @@ "agent-world-packet": { "exports": ["./agent/world-packet"], "modules": [ + "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", "src/agent/worldPacket.js", "src/data/layerSnapshot.js", "src/data/feedState.js", "src/contextModePolicy.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", - "src/i18n/marker.js" + "src/i18n/marker.js", + "src/render/rendererOf.js" ], - "external": ["cesium"] + "external": [] + }, + "heights": { + "exports": ["./queries/heights"], + "modules": [ + "src/queries/heights.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js" + ], + "external": [] + }, + "geo": { + "exports": ["./geo"], + "modules": [ + "src/geo/index.js", + "src/geo/horizon.js", + "src/geo/geodesic.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/celestial.js", + "src/geo/quaternion.js" + ], + "external": [] + }, + "sky": { + "exports": ["./sky"], + "modules": [ + "src/sky/index.js", + "src/sky/assets.js", + "src/sky/stars.js", + "src/sky/icrf.js" + ], + "external": [] + }, + "render": { + "exports": [ + "./render/contract", + "./render/stub", + "./render/occlusion", + "./render/camera/events", + "./render/camera/followTransition", + "./render/conformance", + "./render/input/router", + "./render/stub/camera", + "./render/stub/viewRectangle", + "./render/stub/harness", + "./render/motion", + "./render/vectorBase", + "./render/iconSegment", + "./render/recession", + "./render/windStreamlines", + "./geo/screenCluster" + ], + "modules": [ + "src/render/contract/index.js", + "src/render/stub/index.js", + "src/geo/screenCluster.js", + "src/render/occlusion/index.js", + "src/render/occlusion/depthProbe.js", + "src/data/detectionOcclusion.js", + "src/render/color.js", + "src/geo/polyline.js", + "src/render/motion/iconMotion.js", + "src/geo/horizon.js", + "src/render/conformance/index.js", + "src/render/conformance/scenes.js", + "src/render/conformance/cameraScripts.js", + "src/render/conformance/visual.js", + "src/render/conformance/cameraRunner.js", + "src/render/input/wheel.js", + "src/render/conformance/expect.js", + "src/render/conformance/checks/ports.js", + "src/render/stub/math.js", + "src/geo/index.js", + "src/geo/julian.js", + "src/geo/vector.js", + "src/geo/ellipsoid.js", + "src/geo/frames.js", + "src/geo/eyeMoves.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/render/stub/camera.js", + "src/geo/geodesic.js", + "src/render/camera/events.js", + "src/render/camera/followTransition.js", + "src/render/stub/viewRectangle.js", + "src/render/input/router.js", + "src/render/conformance/goldens/camera.json", + "src/render/conformance/checks/camera.js", + "src/render/vectorBase/index.js", + "src/render/vectorBase/style.js", + "src/render/vectorBase/paint.js", + "src/render/vectorBase/expressions.js", + "src/render/vectorBase/encode.js", + "src/render/weather.js", + "src/render/stub/harness.js", + "src/data/iconSegment.js", + "src/data/motionModel.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/render/recession.js" + ], + "external": ["pbf", "@mapbox/vector-tile", "kdbush"] }, "wildlife-sightings": { "exports": ["./layers/wildlife-sightings"], @@ -5862,7 +8083,22 @@ "src/layers/wildlifeSightings/billboardModel.js", "src/layers/wildlifeSightings/sprites.js", "src/layers/wildlifeSightings/photoText.js", - "src/layers/wildlifeSightings/performance.js" + "src/layers/wildlifeSightings/performance.js", + "src/geo/horizon.js", + "src/render/rendererOf.js", + "src/input/dispatcher.js", + "src/geo/ellipsoid.js", + "src/layers/wildlifeSightings/view.js", + "src/layers/wildlifeSightings/iconCollection.js", + "src/render/color.js", + "src/data/inputOwnership.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/input/sensorPick.js", + "src/geo/vector.js", + "src/data/spriteOrder.js", + "src/styles/styleStages.js", + "src/render/creditMarkup.js" ], "external": ["cesium"] }, @@ -5881,5 +8117,10 @@ "src/layers/wildlifeSightings/performance.js" ], "external": [] + }, + "rail-paths": { + "exports": ["./layers/rail/paths"], + "modules": ["src/data/railPaths.js"], + "external": [] } } diff --git a/scripts/qa-admin-outlines.mjs b/scripts/qa-admin-outlines.mjs index 114daacadf..97fd10c6bb 100644 --- a/scripts/qa-admin-outlines.mjs +++ b/scripts/qa-admin-outlines.mjs @@ -12,10 +12,11 @@ * and finally Brandenburg (Berlin is a hole) and Hawaii (eight islands). * * Asserts for every outline: it resolves from the bundled packs (no geocode, - * boundary or Overpass request), is drawn as a draped outline within the - * budget, and holds still — no rebuilt primitives and no new entities while - * the camera is still. The whole journey must log zero console/page errors and - * send zero requests to any Overpass host or nominatim.openstreetmap.org. + * boundary or Overpass request), shows its first frame within the budget, + * has its draped fill and outline built (their time is reported), and holds + * still — none of its primitives rebuilt while the camera is still. The whole + * journey must log zero console/page errors and send zero requests to any + * Overpass host or nominatim.openstreetmap.org. * * Evidence in qa-shots/ (gitignored): admin-outlines-.png screenshots, * admin-outlines-journey.mp4 (CDP screencast at ~24 fps, frames re-timed from @@ -210,56 +211,84 @@ try { requestAnimationFrame(step); }); }, - annotationSource() { - for (let i = 0; i < viewer.dataSources.length; i++) { - const source = viewer.dataSources.get(i); - if (source.name === 'gev-annotations') return source; - } - return null; - }, - groundPrimitives() { + /** + * The annotations' primitives in the scene, each with the marks its + * instances draw (their pick ids carry `meta.annotation`); only those + * of `mark` when given. + */ + annotationPrimitives(mark) { + const marksOf = (primitive) => { + let inner = primitive; + for (let depth = 0; inner && depth < 4; depth++) { + if (Array.isArray(inner._instanceIds)) + return inner._instanceIds + .map((id) => id?.meta?.annotation) + .filter((id) => id !== undefined); + inner = inner._primitive; + } + return []; + }; const list = []; const walk = (collection) => { for (let i = 0; i < collection.length; i++) { const item = collection.get(i); if (item?.length !== undefined && typeof item.get === 'function') walk(item); - else list.push(item); + else { + const marks = marksOf(item); + if (marks.length && (mark === undefined || marks.includes(mark))) + list.push(item); + } } }; - walk(viewer.scene.groundPrimitives); + walk(viewer.scene.primitives); return list; }, - snapshot() { - const source = this.annotationSource(); - const entities = source ? source.entities.values : []; - const primitives = this.groundPrimitives(); + /** What `mark` draws (every annotation's, without one). */ + snapshot(mark) { + const primitives = this.annotationPrimitives(mark); window.__qaPrimitiveIds ??= new WeakMap(); let next = window.__qaPrimitiveNext ?? 1; - const ids = primitives.map((primitive) => { - if (!window.__qaPrimitiveIds.has(primitive)) - window.__qaPrimitiveIds.set(primitive, next++); - return window.__qaPrimitiveIds.get(primitive); - }); + // By identity only: hosts may trade places without a rebuild. + const ids = primitives + .map((primitive) => { + if (!window.__qaPrimitiveIds.has(primitive)) + window.__qaPrimitiveIds.set(primitive, next++); + return window.__qaPrimitiveIds.get(primitive); + }) + .sort((a, b) => a - b); window.__qaPrimitiveNext = next; return { - entities: entities.length, - polygons: entities.filter((e) => e.polygon).length, - polylines: entities.filter((e) => e.polyline).length, + primitives: primitives.length, + fills: primitives.filter((p) => p instanceof Cesium.GroundPrimitive) + .length, + lines: primitives.filter( + (p) => p instanceof Cesium.GroundPolylinePrimitive, + ).length, + // Draped on terrain and tiles alike. draped: - entities.every( - (e) => - !e.polygon || - e.polygon.classificationType?.getValue() === - Cesium.ClassificationType.BOTH, - ) && - entities.every( - (e) => !e.polyline || e.polyline.clampToGround?.getValue(), + primitives.length > 0 && + primitives.every( + (p) => p.classificationType === Cesium.ClassificationType.BOTH, ), primitiveIds: ids, - ready: viewer.dataSourceDisplay.ready, + ready: primitives.every((p) => p.ready), }; }, + /** The annotations drawn under the middle of the view. */ + marksAtCentre() { + const { canvas } = viewer.scene; + const centre = new Cesium.Cartesian2( + canvas.clientWidth / 2, + canvas.clientHeight / 2, + ); + const marks = new Set(); + for (const hit of viewer.scene.drillPick(centre, 16)) { + const mark = hit?.id?.meta?.annotation; + if (mark !== undefined) marks.add(mark); + } + return [...marks]; + }, }; }); @@ -313,17 +342,31 @@ try { { flyTo }, ); const resolvedMs = performance.now() - started; - // "Drawn" = the first rendered frame after the entity visualizers have - // built the mark's primitives (each tick updates them before render). + // "Drawn" = the first rendered frame after the mark is drawn (as + // before, when it was the entities' first frame); "ready" = the first + // with its primitives all built, which may wait on Cesium's workers. const { viewer } = window.__godsEyeView; + const markId = response.ids?.[0]; + let drawnMs = null; + let readyMs = null; await new Promise((resolve) => { - const off = viewer.scene.postRender.addEventListener(() => { - if (!viewer.dataSourceDisplay.ready) return; + const giveUp = setTimeout(done, 15_000); + function done() { + clearTimeout(giveUp); off(); resolve(); + } + const off = viewer.scene.postRender.addEventListener(() => { + const now = performance.now() - started; + drawnMs ??= now; + const drawn = window.__qaOutlines.annotationPrimitives(markId); + if (drawn.length && drawn.every((p) => p.ready)) { + readyMs = now; + done(); + } }); + viewer.scene.requestRender(); }); - const drawnMs = performance.now() - started; const mark = window.__godsEyeView.annotations .list() .find((m) => m.id === response.ids?.[0]); @@ -331,6 +374,7 @@ try { response: response.results?.[0] ?? null, resolvedMs, drawnMs, + readyMs, parts: mark?.polygons?.length ?? (mark?.ring ? 1 : 0), holes: (mark?.polygons ?? []).reduce( (n, part) => n + part.length - 1, @@ -338,6 +382,7 @@ try { ), ringVertices: mark?.ring?.length ?? 0, pending: Boolean(mark?.pendingOutline), + markId, }; }, target, @@ -347,23 +392,29 @@ try { await settle(); // Hold still: the drawn mark must not rebuild or grow. marker = `still:${name}`; - const before = await page.evaluate(() => window.__qaOutlines.snapshot()); + const before = await page.evaluate( + (mark) => window.__qaOutlines.snapshot(mark), + timing.markId, + ); const stillStart = frames.length; const times = await page.evaluate( (ms) => window.__qaOutlines.frameTimes(ms), STILL_MS, ); - const after = await page.evaluate(() => window.__qaOutlines.snapshot()); + const after = await page.evaluate( + (mark) => window.__qaOutlines.snapshot(mark), + timing.markId, + ); const step = { step: `outline:${name}`, target, ...timing, - entities: after.entities, - polygons: after.polygons, - polylines: after.polylines, + primitives: after.primitives, + fills: after.fills, + lines: after.lines, draped: after.draped, stableWhileStill: - before.entities === after.entities && + after.primitives > 0 && JSON.stringify(before.primitiveIds) === JSON.stringify(after.primitiveIds), stillFrameTimes: stats(times), @@ -375,6 +426,7 @@ try { result.steps.push(step); console.log( `${name}: resolved ${timing.resolvedMs.toFixed(0)} ms, drawn ${timing.drawnMs.toFixed(0)} ms, ` + + `ready ${timing.readyMs?.toFixed(0)} ms, ` + `${timing.parts} part(s), ${timing.holes} hole(s), via ${timing.response?.resolvedVia}; ` + `still p50/p95 ${step.stillFrameTimes.p50}/${step.stillFrameTimes.p95} ms; ` + `stable=${step.stableWhileStill}`, @@ -387,6 +439,11 @@ try { timing.drawnMs < OUTLINE_BUDGET_MS, `${name}: drawn in ${timing.drawnMs} ms`, ); + assert.notEqual(timing.readyMs, null, `${name}: its primitives built`); + assert.ok( + step.fills > 0 && step.lines > 0, + `${name}: drawn as a fill and an outline`, + ); assert.equal(step.draped, true, `${name}: draped on terrain/tiles`); assert.equal(step.stableWhileStill, true, `${name}: no redraw when still`); assert.deepEqual(step.lookups, [], `${name}: no network lookups`); @@ -512,8 +569,15 @@ try { await move(name, { lat, lon, height, pitch: -90 }, 1); await outline(name, target); await shot(name); - const rendered = await page.evaluate(() => window.__qaOutlines.snapshot()); - assert.ok(rendered.polygons > 0, `${target} polygon renders`); + const rendered = await page.evaluate(() => ({ + marks: window.__godsEyeView.annotations.list().map((m) => m.id), + atCentre: window.__qaOutlines.marksAtCentre(), + })); + assert.ok( + rendered.marks.length === 1 && + rendered.atCentre.includes(rendered.marks[0]), + `${target} polygon renders`, + ); } if (recordVideo) { @@ -632,6 +696,7 @@ console.table( step: s.step, resolvedMs: s.resolvedMs?.toFixed(0), drawnMs: s.drawnMs?.toFixed(0), + readyMs: s.readyMs?.toFixed(0), parts: s.parts, stable: s.stableWhileStill, p50: (s.stillFrameTimes || s.frameTimes)?.p50, diff --git a/scripts/qa-anime-sky.mjs b/scripts/qa-anime-sky.mjs index a0a0c99350..040ba76f85 100644 --- a/scripts/qa-anime-sky.mjs +++ b/scripts/qa-anime-sky.mjs @@ -127,7 +127,7 @@ try { let animeOn = false; for (let i = 0; i < s.postProcessStages.length; i++) { const stage = s.postProcessStages.get(i); - if (stage.name === 'godsEyeView_anime') + if (stage.name === 'effects_style_anime') animeOn = stage.enabled && stage.uniforms.intensity > 0.99; } return { diff --git a/scripts/qa-camera-controls.mjs b/scripts/qa-camera-controls.mjs index c2d2b56464..b16a793df2 100644 --- a/scripts/qa-camera-controls.mjs +++ b/scripts/qa-camera-controls.mjs @@ -339,6 +339,45 @@ try { '#cctv-frame', (image) => !image.getAttribute('src') && image.dataset.cameraId === '', ); + // The address bar follows the share state after a short delay: wait for the + // CCTV panel token (1 collapsed, 0 open) the step expects. + const panelState = async (expectedToken) => { + const settled = await page + .waitForFunction( + (token) => + new RegExp(`(?:^|_)v\\.c\\.${token}(?:_|$)`).test( + new URLSearchParams(location.hash.slice(1)).get('ui') || '', + ), + { timeout: 5000 }, + expectedToken, + ) + .then( + () => true, + () => false, + ); + return page.evaluate( + (shared) => ({ + collapsed: document + .getElementById('cctv-panel') + .classList.contains('collapsed'), + shared, + ui: new URLSearchParams(location.hash.slice(1)).get('ui'), + }), + settled ? expectedToken : null, + ); + }; + const closedOnDisable = await panelState('1'); + check( + 'disable collapses the panel and its share preference', + closedOnDisable.collapsed && closedOnDisable.shared === '1', + JSON.stringify(closedOnDisable), + ); + // The switch sits inside the collapsed panel: reopen it from the right rail. + await page.click('[data-rail-item="cctv-panel"]'); + await page.waitForFunction( + () => + !document.getElementById('cctv-panel').classList.contains('collapsed'), + ); await page.click('#cctv-enable-btn'); await page.waitForFunction( () => @@ -351,6 +390,42 @@ try { 'disable clears the preview and re-enable reacquires the camera frame', disabledCleanly, ); + // Contacts switches CCTV off to isolate itself and restores it on the way + // out: the open panel and its share preference survive the round trip. + const cameraBeforeContacts = await page.evaluate( + () => + window.__godsEyeView.styleManager._cctvControls.getState() + ?.activeCameraId, + ); + const entered = await page.evaluate(() => + window.__godsEyeView.styleManager.setContextMode('flights'), + ); + await page.waitForFunction( + () => !window.__godsEyeView.dataManager.isEnabled('cctv'), + ); + const duringContacts = await panelState('0'); + await page.evaluate(() => + window.__godsEyeView.styleManager.setContextMode(null), + ); + await page.waitForFunction(() => + window.__godsEyeView.dataManager.isEnabled('cctv'), + ); + const afterContacts = await panelState('0'); + check( + 'Contacts isolation keeps the open CCTV panel and restores its camera', + entered?.ok === true && + !duringContacts.collapsed && + duringContacts.shared === '0' && + !afterContacts.collapsed && + afterContacts.shared === '0' && + (await page.evaluate( + (cameraId) => + window.__godsEyeView.styleManager._cctvControls.getState() + ?.activeCameraId === cameraId, + cameraBeforeContacts, + )), + JSON.stringify({ entered, duringContacts, afterContacts }), + ); await page.$eval('#cctv-frame', (image) => image.scrollIntoView({ block: 'nearest' }), ); diff --git a/scripts/qa-cctv-v2.mjs b/scripts/qa-cctv-v2.mjs index 88e0a5a2c4..84eb09f6c1 100644 --- a/scripts/qa-cctv-v2.mjs +++ b/scripts/qa-cctv-v2.mjs @@ -263,32 +263,30 @@ function installRenderFramesHelper(page) { // In-page helper (stringified and re-defined inside each evaluate that needs // it, since functions can't cross the puppeteer boundary): serializes the -// 5 frustum polylines + plane position/orientation/dimensions for a camera -// into plain arrays of numbers, using only the camera's own clock time (no -// Cesium namespace needed — Property.getValue just needs *a* JulianDate, -// and the viewer's own clock.currentTime is a valid live instance of one). +// 5 frustum lines + plane position/orientation/dimensions for a camera +// into plain arrays of numbers, from what the layer reports it draws. const SERIALIZE_GEOM_SRC = ` function serializeGeom(camId) { - const viewer = window.__godsEyeView.viewer; - const time = viewer.clock.currentTime; + const drawn = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest(); const roles = ['ray-tl', 'ray-tr', 'ray-br', 'ray-bl', 'cap']; const poly = {}; for (const role of roles) { - const ent = viewer.entities.getById('cctv-' + camId + '-' + role); - poly[role] = ent && ent.polyline - ? ent.polyline.positions.getValue(time).map((p) => [p.x, p.y, p.z]) + const line = drawn.coverage['cctv-' + camId + '-' + role]; + poly[role] = line?.positions + ? line.positions.map((p) => [p.x, p.y, p.z]) : null; } - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); + const quad = drawn.planes['cctv-' + camId + '-plane']; let plane = null; - if (planeEnt) { - const pos = planeEnt.position.getValue(time); - const orient = planeEnt.orientation.getValue(time); - const dims = planeEnt.plane.dimensions.getValue(time); + if (quad) { + const pos = quad.center; + const orient = quad.orientation; plane = { position: [pos.x, pos.y, pos.z], orientation: [orient.x, orient.y, orient.z, orient.w], - dimensions: [dims.x, dims.y], + dimensions: [quad.size[0], quad.size[1]], }; } return { poly, plane }; @@ -695,10 +693,9 @@ async function main() { const camera = dataManager.layers .get('cctv') .module.getUIState().activeCamera; - const ray = viewer.entities.getById(`cctv-${camera.id}-ray-tl`); - const mount = ray?.polyline?.positions.getValue( - viewer.clock.currentTime, - )?.[0]; + const ray = dataManager.layers.get('cctv').module._cctvDrawnForTest() + .coverage[`cctv-${camera.id}-ray-tl`]; + const mount = ray?.positions?.[0]; const height = mount && viewer.scene.globe.ellipsoid.cartesianToCartographic(mount) @@ -849,8 +846,10 @@ async function main() { // source. Assert the migrated surface via the host diagnostics. const diag = window.__gevWorldOverlay?.getDiagnostics?.(); g.hasLabel = (diag?.entriesBySource?.['cctv-projection'] || 0) >= 1; - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); - g.planeShow = planeEnt ? planeEnt.show : null; + const quad = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane']; + g.planeShow = quad ? quad.show : null; return g; })(${JSON.stringify(activeId)})`); @@ -1212,26 +1211,22 @@ async function main() { console.log( 'Checking frame-loop health (placeholder -> frame swap, URL family)...', ); - // The plane's material.image is always defined (placeholder canvas from - // the moment the runtime is created, real frame content painted onto the + // The plane's image is always defined (placeholder canvas from the + // moment the runtime is created, real frame content painted onto the // same canvas/video reference once the fetch resolves) — assert it's // never null/undefined once the runtime exists, i.e. there's no gap where // the plane shows nothing. const materialInfo = await page.evaluate((camId) => { - const viewer = window.__godsEyeView.viewer; - const time = viewer.clock.currentTime; - const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); - const mat = planeEnt?.plane?.material; - const image = mat?.image; - const resolved = - image && typeof image.getValue === 'function' - ? image.getValue(time) - : image; + const quad = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane']; + const source = quad?.source; + const resolved = source?.video || source?.canvas || source?.image; return { - hasMaterial: !!mat, + hasMaterial: !!source, hasImage: !!resolved, tagName: resolved?.tagName || null, - show: planeEnt?.show, + show: quad?.show, }; }, activeId); record( @@ -1665,14 +1660,12 @@ async function main() { 'Checking viewshed mode (coverage tri-state + color-coded volumes)...', ); const countVolumes = () => - page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - let n = 0; - for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) n += 1; - } - return n; - }); + page.evaluate( + () => + window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest().viewsheds.length, + ); const cBeforeViewshed = await readCounters(); const modeAfterSet = await page.evaluate(() => { @@ -1725,26 +1718,26 @@ async function main() { mod.setParams({ coverageMode: 'viewshed' }); }); await sleep(400); - await page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - window.__qaViewshedRefs = []; - for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) - window.__qaViewshedRefs.push(prims.get(i)); - } - }); + // Volumes are draw-port mesh items: "no churn" is no volume written. + const drawnViewsheds = () => + page.evaluate(() => { + const drawn = window.__godsEyeView.dataManager.layers + .get('cctv') + .module._cctvDrawnForTest(); + return { ids: drawn.viewsheds, writes: drawn.viewshedWrites }; + }); + const viewshedsBefore = await drawnViewsheds(); await sleep(8000); - const viewshedIdle = await page.evaluate(() => { - const prims = window.__godsEyeView.viewer.scene.primitives; - const now = []; - for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) now.push(prims.get(i)); - } - const before = window.__qaViewshedRefs || []; - const sameCount = now.length === before.length; - const sameIdentity = sameCount && before.every((p) => now.includes(p)); - return { sameCount, sameIdentity, count: now.length }; - }); + const viewshedsAfter = await drawnViewsheds(); + const viewshedIdle = (() => { + const sameCount = + viewshedsAfter.ids.length === viewshedsBefore.ids.length; + const sameIdentity = + sameCount && + viewshedsBefore.ids.every((id) => viewshedsAfter.ids.includes(id)) && + viewshedsAfter.writes === viewshedsBefore.writes; + return { sameCount, sameIdentity, count: viewshedsAfter.ids.length }; + })(); const cAfterViewshed = await readCounters(); const lateFloorSamples = cAfterViewshed.sampleHeight - cBeforeViewshed.sampleHeight; @@ -1785,9 +1778,9 @@ async function main() { const gizmoStates = await page.evaluate((parts) => { const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; mod.setParams({ calibrationMode: true }); - const viewer = window.__godsEyeView.viewer; + const drawn = mod._cctvDrawnForTest().gizmo; return parts.map((p) => { - const e = viewer.entities.getById('cctv-gizmo-' + p); + const e = drawn['cctv-gizmo-' + p]; return e ? (e.show ? 'shown' : 'hidden') : 'missing'; }); }, GIZMO_PARTS); @@ -1802,9 +1795,10 @@ async function main() { // stay frozen until release, with no transient sampleHeight calls. const eastDrag = await page.evaluate(() => { const viewer = window.__godsEyeView.viewer; - const e = viewer.entities.getById('cctv-gizmo-move-east'); + const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; + const e = mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east']; if (!e) return null; - const pts = e.polyline.positions.getValue(viewer.clock.currentTime); + const pts = e.positions; const scene = viewer.scene; const w = scene.canvas.clientWidth; const h = scene.canvas.clientHeight; @@ -2082,9 +2076,9 @@ async function main() { const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; mod.setParams({ calibrationMode: false }); mod.setParams({ calibration: { reset: true } }); - const viewer = window.__godsEyeView.viewer; + const drawn = mod._cctvDrawnForTest().gizmo; return parts.map((p) => { - const e = viewer.entities.getById('cctv-gizmo-' + p); + const e = drawn['cctv-gizmo-' + p]; return e ? (e.show ? 'shown' : 'hidden') : 'missing'; }); }, GIZMO_PARTS); diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index a342a5cdf6..5bb070f74a 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -765,7 +765,7 @@ try { } : null, navigation: snapshot?.navigation || null, afterId: trackedInfo?.icao24 || null, - viewerTrackedId: viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, contextVisible: !document.getElementById('military-awareness-panel')?.hidden, entryAvailableAfterSettlement: Boolean(entry && !entry.hidden), blockerStillRegistered: dataManager.layers.has(blockerId), @@ -1365,7 +1365,7 @@ try { contextMode: styleManager._contextControls._contextMode, contextChanging: styleManager._contextControls._contextModeChanging, subject: context?.subject ? `${context.subject.layerId}:${context.subject.id}` : null, - tracked: tracker?.gevTrackedId || null, + tracked: window.__godsEyeView.entityRecords.read(tracker)?.trackedId || null, density: styleManager.getDetectionState().densityPct, detectionMode: styleManager.getDetectionState().detectionMode, installations: dataManager.getLayerLifecycleState('military-installations'), diff --git a/scripts/qa-conformance.mjs b/scripts/qa-conformance.mjs new file mode 100644 index 0000000000..98992f9dca --- /dev/null +++ b/scripts/qa-conformance.mjs @@ -0,0 +1,119 @@ +#!/usr/bin/env node +/** + * Run the renderer conformance logic suite on the Cesium renderer in + * headless Chromium (`dev/conformance/`, `window.conformance.runLogic`), + * and fail on any failed check, or on a skip that is not expected. + * + * Without `--url` it starts a Vite dev server of this checkout on `--port` + * (default 5289) and stops it after. WebGL runs on SwiftShader, so the run + * needs no GPU. `--only id,id` runs just those checks; `--json path` writes + * the report. + * + * npm run qa:conformance [-- --url http://127.0.0.1:5280] [--only ids] + * [--json path] + */ +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import puppeteer from 'puppeteer'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** Checks the run skips, with why: anything else skipped fails it. */ +export const EXPECTED_SKIPS = Object.freeze({ + // The page scripts no heights for the Cesium renderer. + 'query.heights': 'no scripted heights in this harness', +}); + +/** A whole run has this long; a check that hangs fails it rather than CI. */ +const RUN_TIMEOUT_MS = 15 * 60_000; + +function parseArgs(argv) { + const args = { port: 5289 }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--url') args.url = argv[++i]; + else if (arg === '--port') args.port = Number(argv[++i]); + else if (arg === '--only') args.only = argv[++i].split(','); + else if (arg === '--json') args.json = argv[++i]; + else throw new Error(`Unknown argument: ${arg}`); + } + return args; +} + +async function startViteServer(port) { + const { createServer } = await import('vite'); + const server = await createServer({ + root: ROOT, + configFile: path.join(ROOT, 'vite.config.js'), + // No hot reload: the page is loaded once and nothing edits it. + server: { port, strictPort: true, host: '127.0.0.1', hmr: false }, + logLevel: 'warn', + }); + await server.listen(); + return server; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const server = args.url ? null : await startViteServer(args.port); + try { + await run(args); + } finally { + await server?.close(); + } +} + +async function run(args) { + const base = (args.url ?? `http://127.0.0.1:${args.port}`).replace(/\/$/, ''); + const browser = await puppeteer.launch({ + headless: true, + executablePath: + process.env.PUPPETEER_EXECUTABLE_PATH || + (await puppeteer.executablePath()), + defaultViewport: { width: 1280, height: 800 }, + protocolTimeout: RUN_TIMEOUT_MS, + args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'], + }); + const pageErrors = []; + let report; + try { + const page = await browser.newPage(); + page.on('pageerror', (error) => pageErrors.push(error.message)); + await page.goto(`${base}/dev/conformance/`, { waitUntil: 'load' }); + await page.waitForFunction(() => window.conformance?.runLogic, { + timeout: 120_000, + }); + report = await page.evaluate( + (only) => window.conformance.runLogic('cesium', { only }), + args.only ?? null, + ); + } finally { + await browser.close(); + } + if (args.json) writeFileSync(args.json, JSON.stringify(report, null, 2)); + console.log( + `cesium: ${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped`, + ); + const problems = []; + for (const failure of report.failures) { + console.error(`fail\t${failure.id}\t${failure.detail ?? ''}`); + problems.push(failure.id); + } + for (const skip of report.skips) { + const expected = EXPECTED_SKIPS[skip.id] === skip.detail; + console.log(`skip\t${skip.id}\t${skip.detail ?? ''}`); + if (!expected) problems.push(`${skip.id} skipped`); + } + if (!args.only && report.passed === 0) problems.push('nothing passed'); + if (problems.length) { + console.error(`FAIL: ${problems.join('; ')}`); + process.exitCode = 1; + } else console.log('ok: the Cesium renderer passes the conformance suite'); +} + +if (import.meta.url === `file://${process.argv[1]}`) + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); diff --git a/scripts/qa-context-arrivals.mjs b/scripts/qa-context-arrivals.mjs index 704d34a6b3..8403b5c340 100644 --- a/scripts/qa-context-arrivals.mjs +++ b/scripts/qa-context-arrivals.mjs @@ -362,7 +362,9 @@ async function contacts() { entities: ds?.entities.values.length ?? 0, created, tracked: - window.__godsEyeView.viewer.trackedEntity?.gevTrackedId ?? null, + window.__godsEyeView.entityRecords.read( + window.__godsEyeView.viewer.trackedEntity, + )?.trackedId ?? null, cockpit: document.body.classList.contains('cockpit-mode'), }); if (samples.length > 5000) samples.splice(0, 1000); @@ -377,8 +379,9 @@ async function contacts() { await page .waitForFunction( () => - window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === - 'flights:aaa051', + window.__godsEyeView.entityRecords.read( + window.__godsEyeView.viewer.trackedEntity, + )?.trackedId === 'flights:aaa051', { timeout: 60_000 }, ) .catch(() => {}); diff --git a/scripts/qa-directions.mjs b/scripts/qa-directions.mjs index 9fb8b98020..f0af5c045c 100644 --- a/scripts/qa-directions.mjs +++ b/scripts/qa-directions.mjs @@ -645,44 +645,34 @@ try { `owner=${afterClear.pointerOwner}`, ); - // ── 8. A tool holding the pointer blocks placement, and says so. ───────── + // ── 8. Arming takes the pointer from a tool holding it, which is told. ── await page.evaluate(() => { + window.__gevQaDrawLost = 0; // A claim answers with a lease; the release takes that lease back. - window.__gevQaDrawLease = window.__gevQa.claimPointer('draw'); + window.__gevQaDrawLease = window.__gevQa.claimPointer('draw', { + onLost: () => (window.__gevQaDrawLost += 1), + }); }); await clickChip('set-a'); - const blocked = await layerState(); + const taken = await layerState(); + const lost = await page.evaluate(() => window.__gevQaDrawLost); check( - "another tool's pointer claim is never stolen", - blocked.pointerOwner === 'draw', - `owner=${blocked.pointerOwner}`, + 'the newest claim takes over: Directions holds the pointer', + taken.pointerOwner === 'directions', + `owner=${taken.pointerOwner}`, ); + check('the tool it replaced is told once', lost === 1, `told=${lost}`); check( - 'nothing is armed, and the row says why the click would do nothing', - blocked.chips.find((chip) => chip.id === 'set-a')?.active === false && - /Another map tool/.test(blocked.stats.error || ''), - blocked.stats.error, + 'SET A is armed, and the row has nothing to complain of', + taken.chips.find((chip) => chip.id === 'set-a')?.active === true && + !taken.stats.error, + taken.stats.error, ); - // The row is not where the operator is looking after pressing a chip, so the - // refusal also has to reach the app's toast (owner field test). - const toast = await page.evaluate(() => { - const node = document.getElementById('toast'); - return { - text: node?.textContent || '', - visible: !!node?.classList.contains('visible'), - }; - }); - check( - 'the refusal reaches the app toast, naming the tool and how to leave it', - /Draw is active/.test(toast.text) && /then set A/.test(toast.text), - JSON.stringify(toast.text), - ); - check('and that toast is actually on screen', toast.visible); - await shot(`05-${LABEL}-pointer-blocked-toast.jpg`); - const released = await page.evaluate(() => + const staleReleased = await page.evaluate(() => window.__gevQa.releasePointer(window.__gevQaDrawLease), ); - check('and it gets the pointer back when it lets go', released); + check("the replaced tool's late release frees nothing", !staleReleased); + await clickChip('set-a'); // ── 9. Denver: maneuver dots sit on the ground, not at sea level. ──────── if (!SKIP.has('denver')) { diff --git a/scripts/qa-draw-tool.mjs b/scripts/qa-draw-tool.mjs index 5985730ec0..43f463a47b 100644 --- a/scripts/qa-draw-tool.mjs +++ b/scripts/qa-draw-tool.mjs @@ -65,6 +65,27 @@ const LINE_CLIP = { x: 390, y: 200, width: 510, height: 380 }; const canvasShot = () => page.screenshot({ clip: LINE_CLIP, type: 'png', encoding: 'base64' }); +/** + * `canvasShot` once the globe has no imagery or terrain tiles left to load + * (bounded: a view that never settles is shot as it is, and the comparison + * then reports what it sees). `globe.tilesLoaded` covers the globe only: a + * 3D Tiles tileset on a keyed server can still be refining when it is true. + */ +async function settledCanvasShot() { + await page + .waitForFunction( + () => { + const scene = window.__godsEyeView.viewer.scene; + scene.requestRender(); + return scene.globe.tilesLoaded; + }, + { timeout: 15_000, polling: 100 }, + ) + .catch(() => {}); + await wait(200); + return canvasShot(); +} + /** * Amber pixels in one shot that are not amber in another of the same view: * a mark's own pixels, apart from imagery and panels that both shots share. @@ -263,39 +284,16 @@ try { }), ); - // The viewer's OWN click actions, captured before the tool ever runs. Both - // must be absent while drawing and back — as the SAME functions — after. - await page.evaluate(() => { - const Cesium = window.__CESIUM__; - const stock = window.__godsEyeView.viewer.screenSpaceEventHandler; - window.__qaStock = { - click: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null, - double: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null, + // The viewer's own select and follow, which the input port runs: on before + // the tool runs, off while drawing, and on again after. + const stockActions = async () => { + const state = await drawState(); + return { + clickOn: state.stockSingleClick, + doubleOn: state.stockDoubleClick, }; - }); - const stockActions = () => - page.evaluate(() => { - const Cesium = window.__CESIUM__; - const stock = window.__godsEyeView.viewer.screenSpaceEventHandler; - const live = { - click: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null, - double: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null, - }; - return { - clickPresent: Boolean(live.click), - doublePresent: Boolean(live.double), - clickIsOriginal: live.click === window.__qaStock.click, - doubleIsOriginal: live.double === window.__qaStock.double, - hadClick: Boolean(window.__qaStock.click), - hadDouble: Boolean(window.__qaStock.double), - }; - }); + }; + const beforeDraw = await stockActions(); // ── enable / disable cycles leave nothing behind ──────────────────────── const before = await drawState(); @@ -307,35 +305,32 @@ try { } const after = await drawState(); check( - 'three enable/disable cycles add no listener, handler or preview data source', + 'three enable/disable cycles add no listener, handler or preview set', after.domListeners === before.domListeners && - after.previewDataSources === 1 && - before.previewDataSources === 1 && + after.previewSets === 2 && + before.previewSets === 2 && after.sceneHandler === false && after.pointerOwner === null && after.stockDoubleClick === before.stockDoubleClick, - `listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewDataSources}, ` + + `listeners ${before.domListeners}→${after.domListeners}, previews ${after.previewSets}, ` + `handler ${after.sceneHandler}, owner ${after.pointerOwner}, stock dblclick ${after.stockDoubleClick}`, ); - // ── the viewer's own click actions are borrowed, then given back ──────── + // ── the viewer's own click actions are held off, then given back ─────── await page.click('#draw-toggle'); const duringDraw = await stockActions(); check( - "Cesium's own selecting click and tracking double-click are both borrowed while drawing", - duringDraw.clickPresent === false && duringDraw.doublePresent === false, - `click present ${duringDraw.clickPresent}, double present ${duringDraw.doublePresent} ` + - `(viewer had click ${duringDraw.hadClick}, double ${duringDraw.hadDouble})`, + "Cesium's own selecting click and tracking double-click are both off while drawing", + duringDraw.clickOn === false && duringDraw.doubleOn === false, + JSON.stringify({ beforeDraw, duringDraw }), ); await page.click('#draw-toggle'); const afterDraw = await stockActions(); check( - 'and both are restored as the SAME functions, not replacements', - afterDraw.clickPresent === duringDraw.hadClick && - afterDraw.doublePresent === duringDraw.hadDouble && - afterDraw.clickIsOriginal && - afterDraw.doubleIsOriginal, - JSON.stringify(afterDraw), + 'and both are back after', + afterDraw.clickOn === beforeDraw.clickOn && + afterDraw.doubleOn === beforeDraw.doubleOn, + JSON.stringify({ beforeDraw, afterDraw }), ); // ── a pin, finished with Enter ────────────────────────────────────────── @@ -531,12 +526,26 @@ try { await page.click(rowControl(lineId, 'swatch')); await page.click(rowControl(lineId, 'color-amber')); await markReaches(lineId, { color: 'amber', alpha: 1 }); + // Only the Line is on the board for its shots. The area's fill pulses, and + // under it borderline roofs drift into and out of amber between two shots + // of an unchanged scene, on the old build as on this one. + const others = await page.evaluate((id) => { + const marks = window.__gevAnnotations.list(); + const ids = marks.filter((m) => m.id !== id && !m.hidden).map((m) => m.id); + for (const other of ids) window.__gevAnnotations.setHidden(other, true); + return ids; + }, lineId); + for (const other of others) + await markReaches(other, { hidden: true, alpha: 0 }); await wait(800); - const shown = await canvasShot(); + // The fly-to above is still refining imagery near the camera at this + // point; a tile that sharpens between the two shots repaints roofs into + // and out of amber, so each shot waits for the globe to finish loading. + const shown = await settledCanvasShot(); await page.click(rowControl(lineId, 'toggle')); await markReaches(lineId, { hidden: true, alpha: 0 }); await wait(800); - const hiddenShot = await canvasShot(); + const hiddenShot = await settledCanvasShot(); // Amber the shown line had and the hidden one lost; amber that appears // only once it is hidden is noise, and must stay small beside it. const gone = await amberOnlyIn(shown, hiddenShot); @@ -548,12 +557,24 @@ try { ); await page.click(rowControl(lineId, 'toggle')); await wait(1200); - const back = await amberOnlyIn(await canvasShot(), hiddenShot); + const back = await amberOnlyIn(await settledCanvasShot(), hiddenShot); check( 'and paints again when shown', back > gone * 0.5, `${back} of ${gone} line pixels back`, ); + await page.evaluate((ids) => { + for (const other of ids) window.__gevAnnotations.setHidden(other, false); + }, others); + const restored = []; + for (const other of others) + if (await markReaches(other, { hidden: false, alpha: 1 })) + restored.push(other); + check( + 'the marks set aside for the Line shots are back on the board', + restored.length === others.length, + `${restored.length} of ${others.length} back`, + ); await shot('03-pins-and-shapes'); // ── Escape cancels the shape, a second Escape leaves draw mode ────────── @@ -601,32 +622,87 @@ try { : 'no CCTV camera or bundled site could be reached — the ownership case cannot be proved', ); if (target) { + // The camera pose the target was found at: a selecting click flies the + // camera to what it picked, so the drawing click has to come back here + // and find the target again, or it would land on plain ground. + await page.evaluate(() => { + const camera = window.__godsEyeView.viewer.camera; + window.__qaTargetView = { + destination: camera.positionWC.clone(), + orientation: { + heading: camera.heading, + pitch: camera.pitch, + roll: camera.roll, + }, + }; + }); + await page.evaluate(clearSelection); + await page.evaluate(startSelectionCount); await clickWorld(target.x, target.y, { settle: 900 }); - const selectedNormally = await page.evaluate(() => - Boolean(window.__godsEyeView.viewer.selectedEntity), - ); + const normal = await page.evaluate(readSelectionCount, target.key); check( `clicking a ${target.layer} selects it when nothing owns the pointer`, - selectedNormally, + // The CCTV branch looks for `CAM-` Cesium entities and reads the + // viewer's selection; neither build draws cameras that way any more, so + // it is not reached and the bundled data centre is the target. + normal.item > 0 || (target.layerId === 'cctv' && normal.entity), + `${normal.item} selection(s) of ${target.key}, ${normal.all} in all, entity ${normal.entity}`, ); + await page.evaluate(clearSelection); await page.evaluate(() => { - window.__godsEyeView.viewer.selectedEntity = undefined; + const viewer = window.__godsEyeView.viewer; + viewer.camera.cancelFlight?.(); + viewer.camera.setView(window.__qaTargetView); + viewer.scene.requestRender(); }); - await page.click('#draw-toggle'); - await page.click('.pp-mode-btn[data-shape="area"]'); - await clickWorld(target.x, target.y, { settle: 900 }); - const whileDrawing = await drawState(); - const selectedWhileDrawing = await page.evaluate(() => - Boolean(window.__godsEyeView.viewer.selectedEntity), + await wait(1500); + const again = await onScreen( + target.belongs, + target.contextPrefix, + target.key, ); check( - `clicking the same ${target.layer} while drawing adds a vertex and selects nothing`, - whileDrawing.vertices === 1 && selectedWhileDrawing === false, - `vertices ${whileDrawing.vertices}, selected ${selectedWhileDrawing}`, + `the ${target.layer} is picked again after the camera returns`, + Boolean(again), + again ? `at ${again.x},${again.y}` : 'not picked on screen any more', ); - await page.keyboard.press('Escape'); - await page.keyboard.press('Escape'); - await wait(150); + if (again) { + await page.click('#draw-toggle'); + await page.click('.pp-mode-btn[data-shape="area"]'); + // Draw mode's own panel must not have covered it: the drawing click has + // to land on the same item, not on plain ground. + const drawingSpot = await onScreen( + target.belongs, + target.contextPrefix, + target.key, + ); + check( + `the ${target.layer} is still picked once draw mode is open`, + Boolean(drawingSpot), + drawingSpot + ? `at ${drawingSpot.x},${drawingSpot.y}` + : 'not picked on screen in draw mode', + ); + if (drawingSpot) { + await page.evaluate(startSelectionCount); + await clickWorld(drawingSpot.x, drawingSpot.y, { settle: 900 }); + const whileDrawing = await drawState(); + const drawingSelection = await page.evaluate( + readSelectionCount, + target.key, + ); + check( + `clicking the same ${target.layer} while drawing adds a vertex and selects nothing`, + whileDrawing.vertices === 1 && + drawingSelection.all === 0 && + !drawingSelection.entity, + `vertices ${whileDrawing.vertices}, ${drawingSelection.all} selection(s), entity ${drawingSelection.entity}`, + ); + } + await page.keyboard.press('Escape'); + await page.keyboard.press('Escape'); + await wait(150); + } } // ── what a reload actually does ───────────────────────────────────────── @@ -664,19 +740,6 @@ try { document.getElementById('draw-toggle')?.getBoundingClientRect().width > 0, { timeout: 10_000 }, ); - // The reload built a new page context: re-capture the viewer's own click - // actions so the identity comparisons below still mean something. - await page.evaluate(() => { - const Cesium = window.__CESIUM__; - const stock = window.__godsEyeView.viewer.screenSpaceEventHandler; - window.__qaStock = { - click: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null, - double: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null, - }; - }); await page.evaluate((view) => { const viewer = window.__godsEyeView.viewer; viewer.camera.cancelFlight?.(); @@ -813,13 +876,10 @@ try { finalState.active === false && finalState.pointerOwner === null && finalState.sceneHandler === false && - finalState.previewDataSources === 1, + finalState.previewSets === 2, JSON.stringify(finalState), ); // ── destroy(): the shell disposing the tool leaves nothing behind ─────── - const beforeDestroy = await page.evaluate( - () => window.__godsEyeView.viewer.dataSources.length, - ); await page.click('#draw-toggle'); // destroy from an ACTIVE session: the harder case await wait(200); const destroyed = await page.evaluate(async () => { @@ -827,24 +887,15 @@ try { const wasActive = tool.active; await tool.destroy(); await new Promise((resolve) => setTimeout(resolve, 50)); - const Cesium = window.__CESIUM__; - const viewer = window.__godsEyeView.viewer; - const stock = viewer.screenSpaceEventHandler; - let previews = 0; - for (let i = 0; i < viewer.dataSources.length; i += 1) - if (viewer.dataSources.get(i)?.name === 'gev-draw-preview') previews += 1; + const diagnostics = tool.diagnostics(); return { wasActive, - diagnostics: tool.diagnostics(), - previews, - dataSources: viewer.dataSources.length, + diagnostics, + previews: diagnostics.previewSets, handleGone: window.__gevDrawTool === undefined, - clickRestored: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) === - window.__qaStock.click, - doubleRestored: - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) === - window.__qaStock.double, + // The viewer's own select and follow run again. + clickRestored: diagnostics.stockSingleClick, + doubleRestored: diagnostics.stockDoubleClick, drawingClass: document.body.classList.contains('gev-drawing'), }; }); @@ -859,11 +910,9 @@ try { JSON.stringify(destroyed.diagnostics), ); check( - 'destroy() detaches the preview data source and gives the window handle back', - destroyed.previews === 0 && - destroyed.dataSources === beforeDestroy - 1 && - destroyed.handleGone, - `previews ${destroyed.previews}, dataSources ${beforeDestroy} → ${destroyed.dataSources}, handle gone ${destroyed.handleGone}`, + 'destroy() disposes the preview draw sets and gives the window handle back', + destroyed.previews === 0 && destroyed.handleGone, + `preview sets ${destroyed.previews}, handle gone ${destroyed.handleGone}`, ); check( "destroy() returns Cesium's own click actions", @@ -930,17 +979,24 @@ async function findClickableTarget() { viewer.scene.requestRender(); }, camera); await wait(4000); - const spot = await onScreen( - (entity) => typeof entity.id === 'string' && entity.id.startsWith('CAM-'), - ); - if (spot) return { ...spot, layer: 'CCTV camera' }; + const spot = await onScreen(cameraEntity); + if (spot) + return { + ...spot, + layer: 'CCTV camera', + layerId: 'cctv', + belongs: cameraEntity, + contextPrefix: null, + }; } // Bundled infrastructure as the keyless fallback: a different guarded handler, // the same shared claim, and always present without a key. const site = await page .evaluate(async () => { - const viewer = window.__godsEyeView.viewer; + // The app registers each local feature's context as `:`, + // with its coordinates, whether the layer draws Cesium entities or + // through the draw port. await window.__godsEyeView.dataManager.setEnabled( 'local-datacenters', true, @@ -948,30 +1004,16 @@ async function findClickableTarget() { origin: 'user', }, ); - const centreOf = (entity) => { - const time = viewer.clock.currentTime; - const point = entity.position?.getValue?.(time); - if (point) return point; - const hierarchy = entity.polygon?.hierarchy?.getValue?.(time); - if (hierarchy?.positions?.length) return hierarchy.positions[0]; - const line = entity.polyline?.positions?.getValue?.(time); - return line?.length ? line[0] : null; - }; for (let attempt = 0; attempt < 40; attempt += 1) { - for (let i = 0; i < viewer.dataSources.length; i += 1) { - for (const entity of viewer.dataSources.get(i).entities.values) { - if (entity.__localLayerId !== 'local-datacenters') continue; - const point = centreOf(entity); - if (!point) continue; - const carto = window.Cesium - ? window.Cesium.Cartographic.fromCartesian(point) - : viewer.scene.globe.ellipsoid.cartesianToCartographic(point); - if (!carto) continue; - return { - lon: (carto.longitude * 180) / Math.PI, - lat: (carto.latitude * 180) / Math.PI, - }; - } + const records = window.__gevContextStore?.entities?.values() ?? []; + for (const record of records) { + if (!String(record?.id).startsWith('local-datacenters:')) continue; + if ( + !Number.isFinite(record.latitude) || + !Number.isFinite(record.longitude) + ) + continue; + return { lon: record.longitude, lat: record.latitude }; } await new Promise((resolve) => setTimeout(resolve, 500)); } @@ -993,21 +1035,97 @@ async function findClickableTarget() { viewer.scene.requestRender(); }, site); await wait(4000); - const spot = await onScreen( - (entity) => entity.__localLayerId === 'local-datacenters', + const spot = await onScreen(dataCentre, 'local-datacenters:'); + return spot + ? { + ...spot, + layer: 'data centre', + layerId: 'local-datacenters', + belongs: dataCentre, + contextPrefix: 'local-datacenters:', + } + : null; +} + +/** A CCTV camera entity (runs in the page through `onScreen`). */ +function cameraEntity(entity) { + return typeof entity.id === 'string' && entity.id.startsWith('CAM-'); +} + +/** + * A bundled data centre: a Cesium entity carrying its context, or a draw-port + * pick id `{ set, id }` from a set named `::` (runs in the + * page through `onScreen`). + */ +function dataCentre(entity) { + return ( + window.__godsEyeView.entityRecords + .read(entity) + ?.contextId?.startsWith('local-datacenters:') || + (typeof entity?.set === 'string' && + entity.set.startsWith('local-datacenters:')) ); - return spot ? { ...spot, layer: 'data centre' } : null; +} + +/** Clear both selection slots (runs in the page). */ +function clearSelection() { + window.__godsEyeView.viewer.selectedEntity = undefined; + const store = window.__gevContextStore; + if (store) store.selectedEntityId = null; +} + +/** + * Count click selections from now on (runs in the page). A layer selects + * through the shared context store, which announces each selection with + * `gev:entity-selected`; one drawn through the draw port has no Cesium entity + * to set as the viewer's selection. Counting the announcements rather than + * reading the slot keeps an earlier selection, or a tracking layer refilling + * the slot without announcing, from deciding the result. + */ +function startSelectionCount() { + const seen = []; + window.removeEventListener('gev:entity-selected', window.__qaOnSelected); + window.__qaSelections = seen; + window.__qaOnSelected = (event) => seen.push(event.detail ?? null); + window.addEventListener('gev:entity-selected', window.__qaOnSelected); +} + +/** + * Selections since `startSelectionCount` (runs in the page): `all`, those of + * the item whose context id is `key`, and whether the viewer holds a selected + * Cesium entity. + * @param {string} key + * @returns {{ all: number, item: number, entity: boolean }} + */ +function readSelectionCount(key) { + const seen = window.__qaSelections || []; + return { + all: seen.length, + item: seen.filter((record) => record?.id === key).length, + entity: Boolean(window.__godsEyeView.viewer.selectedEntity), + }; } /** * Canvas coordinates of the first entity matching `belongs` that is on screen * and clear of the side panels. Annotation marks and the draw tool's own * preview vertices are on screen too, so the predicate has to be specific. + * With `contextPrefix`, the context store's records under that prefix are + * candidates too (at their ground coordinates), for a layer drawn through the + * draw port, which has no entities to walk; `belongs` then also receives the + * draw-port pick id. Returns the spot and `key`, the picked item's context id + * (from the entity's record or the draw-port item's `meta`; without a prefix, + * the entity's own id); with `wantKey`, only that item counts. */ -async function onScreen(belongs, timeout = 20_000) { +async function onScreen( + belongs, + contextPrefix = null, + wantKey = null, + timeout = 20_000, +) { return page .waitForFunction( - (belongsSource) => { + (belongsSource, prefix, want) => { // eslint-disable-next-line no-new-func const belongsTo = new Function(`return (${belongsSource})`)(); const viewer = window.__godsEyeView.viewer; @@ -1018,29 +1136,62 @@ async function onScreen(belongs, timeout = 20_000) { if (source?.name === 'gev-draw-preview') continue; collections.push(source.entities); } + const candidates = []; for (const source of collections) { for (const entity of source.values) { if (!belongsTo(entity)) continue; const position = entity.position?.getValue?.( viewer.clock.currentTime, ); - if (!position) continue; - const window2d = scene.cartesianToCanvasCoordinates(position); - if (!window2d) continue; - const { x, y } = window2d; - if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue; - // Projecting into the window is not the same as being clickable: - // the entity may be beyond the horizon or behind a building. Only a - // spot where the scene actually picks it proves the control case. - const hit = scene.pick({ x: Math.round(x), y: Math.round(y) }); - if (!hit?.id || !belongsTo(hit.id)) continue; - return { x: Math.round(x), y: Math.round(y) }; + if (position) candidates.push(position); } } + if (prefix) { + const ellipsoid = scene.globe.ellipsoid; + for (const record of window.__gevContextStore?.entities?.values() ?? + []) { + if (!String(record?.id).startsWith(prefix)) continue; + if ( + !Number.isFinite(record.latitude) || + !Number.isFinite(record.longitude) + ) + continue; + candidates.push( + ellipsoid.cartographicToCartesian({ + longitude: (record.longitude * Math.PI) / 180, + latitude: (record.latitude * Math.PI) / 180, + height: 0, + }), + ); + } + } + for (const position of candidates) { + const window2d = scene.cartesianToCanvasCoordinates(position); + if (!window2d) continue; + const { x, y } = window2d; + if (!(x > 300 && x < 900 && y > 180 && y < 600)) continue; + // Projecting into the window is not the same as being clickable: + // the entity may be beyond the horizon or behind a building. Only a + // spot where the scene actually picks it proves the control case. + const hit = scene.pick({ x: Math.round(x), y: Math.round(y) }); + if (!hit?.id || !belongsTo(hit.id)) continue; + // The picked item's context id: an entity's own record, or that of + // the object a draw-port item carries as its `meta`. + const pickId = hit.id; + const records = window.__godsEyeView.entityRecords; + const key = + records.read(pickId)?.contextId || + records.read(pickId.meta)?.contextId || + (prefix ? null : String(pickId.id)); + if (!key || (want && key !== want)) continue; + return { x: Math.round(x), y: Math.round(y), key }; + } return false; }, { timeout, polling: 500 }, belongs.toString(), + contextPrefix, + wantKey, ) .then( (handle) => handle.jsonValue(), diff --git a/scripts/qa-geo-import-large.mjs b/scripts/qa-geo-import-large.mjs index 679ea14a1e..59b6908d1e 100644 --- a/scripts/qa-geo-import-large.mjs +++ b/scripts/qa-geo-import-large.mjs @@ -103,49 +103,113 @@ try { destination: C.Cartesian3.fromDegrees(-122.5, 37.72, 50000), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); + // One form for both sides: Cesium's own KML reading of the file (the + // control) and what the import drew (the candidate). + const css = (value) => + value === undefined || value === null + ? undefined + : (Array.isArray(value) + ? new C.Color(...value) + : C.Color.fromCssColorString(value) + ).toCssColorString(); + const at = (p) => { + const c = C.Cartographic.fromCartesian(new C.Cartesian3(p.x, p.y, p.z)); + return [ + +C.Math.toDegrees(c.longitude).toFixed(6), + +C.Math.toDegrees(c.latitude).toFixed(6), + ]; + }; + const sorted = (rows) => + rows.sort( + (a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind), + ); window.__qaStyleSnapshot = (source) => { const now = viewer.clock.currentTime; - const images = new Map(); - const imageValue = (p) => { - const value = p?.getValue(now); - if (value?.tagName !== 'CANVAS') return value; - if (!images.has(value)) images.set(value, value.toDataURL()); - return images.get(value); - }; - const color = (p) => p?.getValue(now)?.toCssColorString(); - const positions = (p) => p?.getValue(now)?.map((v) => [v.x, v.y, v.z]); - const renderedPins = new Map(); - const collection = source.importedBillboards; - if (collection) - for (let i = 0; i < collection.length; i++) { - const pin = collection.get(i); - renderedPins.set(pin.id, pin); - } - const actual = (e, key, fallback) => { - const pin = renderedPins.get(e); - return pin ? pin[key] : (e.billboard?.[key]?.getValue(now) ?? fallback); - }; - return (source.importedEntities || source.entities.values) - .map((e) => ({ - name: e.name, - point: renderedPins.get(e)?.position || e.position?.getValue(now), - scale: e.billboard ? actual(e, 'scale', 1) : undefined, - rotation: e.billboard ? actual(e, 'rotation', 0) : undefined, - image: renderedPins.get(e)?.image || imageValue(e.billboard?.image), - color: e.billboard - ? actual(e, 'color', C.Color.WHITE).toCssColorString() - : undefined, - width: e.polyline?.width?.getValue(now), - lineColor: color(e.polyline?.material?.color), - line: positions(e.polyline?.positions), - fill: e.polygon?.fill?.getValue(now), - outline: e.polygon?.outline?.getValue(now), - polygonColor: color(e.polygon?.material?.color), - polygon: e.polygon?.hierarchy - ?.getValue(now) - ?.positions?.map((v) => [v.x, v.y, v.z]), - })) - .sort((a, b) => a.name.localeCompare(b.name)); + return sorted( + source.entities.values + .filter((e) => e.billboard || e.polyline || e.polygon) + .map((e) => { + if (e.billboard) + return { + name: e.name, + kind: 'pin', + point: at(e.position.getValue(now)), + scale: e.billboard.scale?.getValue(now) ?? 1, + heading: Math.round( + -C.Math.toDegrees(e.billboard.rotation?.getValue(now) ?? 0), + ), + image: Boolean(e.billboard.image?.getValue(now)), + color: css( + e.billboard.color?.getValue(now)?.toCssColorString() ?? + 'white', + ), + }; + if (e.polyline) + return { + name: e.name, + kind: 'line', + width: e.polyline.width?.getValue(now), + color: e.polyline.material?.color + ?.getValue(now) + ?.toCssColorString(), + line: e.polyline.positions.getValue(now).map(at), + }; + return { + name: e.name, + kind: 'polygon', + fill: e.polygon.fill?.getValue(now) !== false, + color: e.polygon.material?.color + ?.getValue(now) + ?.toCssColorString(), + polygon: e.polygon.hierarchy.getValue(now).positions.map(at), + }; + }), + ); + }; + window.__qaDrawnSnapshot = (id) => { + const drawn = window.__gevGeoImport.drawn(id); + const ring = (points) => + points.map((p) => [+p.lon.toFixed(6), +p.lat.toFixed(6)]); + return sorted([ + ...drawn.icons.map((i) => ({ + name: i.meta?.name, + kind: 'pin', + point: [+i.pos.lon.toFixed(6), +i.pos.lat.toFixed(6)], + scale: i.scale ?? 1, + // A KML heading is drawn as a turn on screen, clockwise. + heading: Math.round((-(i.rotation ?? 0) * 180) / Math.PI), + image: Boolean(i.image), + color: css(i.color ?? 'white'), + })), + ...drawn.lines.map((l) => ({ + name: l.meta?.name, + kind: 'line', + width: l.widthPx, + color: css(l.style.color), + line: l.positions.map(at), + })), + ...drawn.shapes + .filter((s) => s.geometry.kind === 'polygon') + .map((s) => ({ + name: s.meta?.name, + kind: 'polygon', + fill: Boolean(s.fill), + color: css(s.fill), + polygon: ring(s.geometry.rings[0]), + })), + ]); + }; + // The import's draw sets among the scene's primitives. + window.__qaImportHosts = () => { + let n = 0; + for (let i = 0; i < viewer.scene.primitives.length; i++) + if ( + String(viewer.scene.primitives.get(i).drawSetId).startsWith( + 'geo-import:', + ) + ) + n += 1; + return n; }; window.__qaUnsharedKml = async (text) => { const doc = new DOMParser().parseFromString(text, 'application/xml'); @@ -159,25 +223,22 @@ try { canvas: viewer.scene.canvas, clampToGround: true, }); - for (const e of source.importedEntities || source.entities.values) - e.label = undefined; + for (const e of source.entities.values) e.label = undefined; return source; }; }); const equivalent = await page.evaluate(async (text) => { - const { viewer } = window.__godsEyeView; const control = await window.__qaUnsharedKml(text); const outcomes = await window.__gevGeoImport.importFiles([ new File([text], 'style-equivalence.kml'), ]); - const candidate = viewer.dataSources.get(viewer.dataSources.length - 1); + const expected = JSON.stringify(window.__qaStyleSnapshot(control)); + const actual = JSON.stringify(window.__qaDrawnSnapshot(outcomes[0]?.id)); const result = { ok: outcomes[0]?.ok, - same: - JSON.stringify(window.__qaStyleSnapshot(control)) === - JSON.stringify(window.__qaStyleSnapshot(candidate)), - entities: (candidate.importedEntities || candidate.entities.values) - .length, + same: expected === actual, + entities: JSON.parse(actual).length, + ...(expected === actual ? {} : { expected, actual }), }; await window.__gevGeoImport.remove(outcomes[0]?.id); return result; @@ -188,8 +249,8 @@ try { JSON.stringify(equivalent), ); - // The control bypasses the former style-count refusal solely in this test, - // to compare native unshared rendering against normalized rendering. + // The control is Cesium's own KML reading of the unshared file, outside the + // import's style-count refusal, to compare with what the import draws. await page.evaluate(async (text) => { const source = await window.__qaUnsharedKml(text); window.__qaUnsharedSnapshot = JSON.stringify( @@ -250,9 +311,7 @@ try { ); const loadPicked = async (filename, expected) => { - const before = await page.evaluate( - () => window.__godsEyeView.viewer.dataSources.length, - ); + const before = await page.evaluate(() => window.__qaImportHosts()); const priorIds = await page.evaluate(() => window.__gevGeoImport.list().map((f) => f.id), ); @@ -276,7 +335,7 @@ try { const state = await page.evaluate(() => ({ files: window.__gevGeoImport.list(), hint: document.getElementById('geo-import-hint').textContent, - sources: window.__godsEyeView.viewer.dataSources.length, + sources: window.__qaImportHosts(), })); const item = state.files.find((f) => !priorIds.includes(f.id)); check( @@ -285,7 +344,7 @@ try { (expected === null ? item?.entityCount > 0 : item?.entityCount === expected) && - state.sources === before + 1, + state.sources > before, JSON.stringify({ bytes: fs.statSync(filename).size, loadMs: Math.round(performance.now() - started), @@ -296,14 +355,12 @@ try { }; const item = await loadPicked(file, 5000); if (item) { - const same = await page.evaluate(() => { - const viewer = window.__godsEyeView.viewer; - const source = viewer.dataSources.get(viewer.dataSources.length - 1); - return ( - JSON.stringify(window.__qaStyleSnapshot(source)) === - window.__qaUnsharedSnapshot - ); - }); + const same = await page.evaluate( + (id) => + JSON.stringify(window.__qaDrawnSnapshot(id)) === + window.__qaUnsharedSnapshot, + item.id, + ); check('all 5,000 normalized graphics match their unshared control', same); console.log('NORMALIZED CANDIDATE', JSON.stringify(await measure())); await page.evaluate((id) => window.__gevGeoImport.remove(id), item.id); @@ -335,32 +392,24 @@ try { JSON.stringify(clockBefore) === JSON.stringify(clockAfter), ); if (suppliedItem && process.argv.includes('--expect-local-pins')) { - const markers = await page.evaluate(() => { + const markers = await page.evaluate((id) => { const { viewer } = window.__godsEyeView, C = window.__CESIUM__; - const source = viewer.dataSources.get(viewer.dataSources.length - 1); - const points = ( - source.importedEntities || source.entities.values - ).filter((e) => e.position && e.billboard); - const images = points.filter((e) => - e.billboard.image?.getValue(viewer.clock.currentTime), - ); + const drawn = window.__gevGeoImport.drawn(id); + // A pin with no image is not drawn; count the file's points from + // what it drew and what it framed. + const points = drawn.icons; + const images = points.filter((i) => i.image); if (images.length) { - const at = C.Cartographic.fromCartesian( - images[0].position.getValue(viewer.clock.currentTime), - ); + const { lon, lat } = images[0].pos; viewer.camera.cancelFlight(); viewer.camera.setView({ - destination: C.Cartesian3.fromRadians( - at.longitude, - at.latitude, - 100000, - ), + destination: C.Cartesian3.fromDegrees(lon, lat, 100000), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); } return { points: points.length, images: images.length }; - }); + }, suppliedItem.id); check( 'supplied point markers have drawable images', markers.points > 0 && markers.images === markers.points, diff --git a/scripts/qa-geo-import-regressions.mjs b/scripts/qa-geo-import-regressions.mjs index ba5a040a2a..c37083db0a 100644 --- a/scripts/qa-geo-import-regressions.mjs +++ b/scripts/qa-geo-import-regressions.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -/** Import regressions through the real UI controller and Cesium loaders. +/** Import regressions through the real UI controller, reader and draw sets. * Run against dev and preview: QA_BASE_URL=http://localhost:4173 node scripts/qa-geo-import-regressions.mjs */ import puppeteer from 'puppeteer'; @@ -129,13 +129,13 @@ try { ? JSON.stringify(value) : value; const [outcome] = await tool.importFiles([new File([content], name)]); - return { - outcome, - source: outcome.ok - ? viewer.dataSources.get(viewer.dataSources.length - 1) - : null, - }; + // What the file drew: its draw sets' items, by kind. + return { outcome, drawn: outcome.ok ? tool.drawn(outcome.id) : null }; }; + const items = (r) => + r.drawn ? [...r.drawn.icons, ...r.drawn.lines, ...r.drawn.shapes] : []; + const cartesian = (p) => new C.Cartesian3(p.x, p.y, p.z); + const heightOf = (p) => C.Cartographic.fromCartesian(cartesian(p)).height; const remove = (r) => { if (r.outcome.ok) tool.remove(r.outcome.id); }; @@ -171,26 +171,19 @@ try { }, 'xyz.geojson', ); - const pin = (r.source?.importedEntities || r.source?.entities.values).find( - (e) => e.billboard, - ), - polygon = (r.source?.importedEntities || r.source?.entities.values).find( - (e) => e.polygon, - ); + const pin = r.drawn?.icons[0], + polygon = r.drawn?.shapes.find((s) => s.geometry.kind === 'polygon'); check( 'XYZ ground footprint and isolated entity IDs', r.outcome.ok && pin.id !== 'kartaview-owned' && - Math.abs( - C.Cartographic.fromCartesian(pin.position.getValue(now)).height, - ) < 0.01 && - polygon.polygon.perPositionHeight?.getValue(now) !== true, + Math.abs(pin.pos.height) < 0.01 && + polygon.geometry.perPositionHeight !== true, + { pin: pin?.pos, polygon: polygon?.geometry.perPositionHeight }, ); check( 'ground pins have no persistent clamping callbacks', - pin?.billboard.heightReference?.getValue(now) === - C.HeightReference.NONE && - pin.billboard.disableDepthTestDistance.getValue(now) === Infinity, + pin?.height === 'absolute' && pin.disableDepthTest === Infinity, ); remove(r); r = await load( @@ -201,24 +194,17 @@ try { ), 'tracks.kml', ); - const find = (name) => - (r.source?.importedEntities || r.source?.entities.values).find( - (e) => e.name === name, - ); + const find = (name) => r.drawn?.lines.find((l) => l.meta?.name === name); check( 'ground tracks and untessellated authored lines clamp', - find('ground')?.polyline.clampToGround?.getValue(now) && - find('line')?.polyline.clampToGround?.getValue(now), + find('ground')?.mode === 'draped' && find('line')?.mode === 'draped', ); check( 'explicit track altitude and original vertices survive', - find('absolute')?.polyline.positions.getValue(now).length === 2 && - find('absolute') - .polyline.positions.getValue(now) - .every( - (p) => - Math.abs(C.Cartographic.fromCartesian(p).height - 10000) < 0.01, - ), + find('absolute')?.positions.length === 2 && + find('absolute').positions.every( + (p) => Math.abs(heightOf(p) - 10000) < 0.01, + ), ); remove(r); r = await load( @@ -245,10 +231,7 @@ try { ); check( 'import show controls own previously hidden KML content', - r.outcome.ok && - (r.source.importedEntities || r.source.entities.values).every( - (e) => e.isShowing, - ), + r.outcome.ok && r.drawn.show && r.drawn.icons.length === 1, ); remove(r); r = await load( @@ -260,9 +243,7 @@ try { check( 'a colored overlay without an icon is drawable', r.outcome.ok && - (r.source.importedEntities || r.source.entities.values).some( - (e) => e.rectangle, - ), + r.drawn.shapes.some((s) => s.geometry.kind === 'rectangle'), ); remove(r); const xml = wrap(`${point}`); @@ -325,8 +306,7 @@ try { 'portrait.geojson', ); await new Promise((resolve) => setTimeout(resolve, 2300)); - const positions = (r.source?.importedEntities || - r.source?.entities.values)[0].polyline.positions.getValue(now); + const positions = r.drawn?.lines[0]?.positions.map(cartesian); const screen = positions?.map((p) => C.SceneTransforms.worldToWindowCoordinates(viewer.scene, p), ); @@ -349,11 +329,9 @@ try { 'intercontinental.geojson', ); await new Promise((resolve) => setTimeout(resolve, 2300)); - const intercontinental = ( - r.source?.importedEntities || r.source?.entities.values - ) - .filter((e) => e.position) - .map((e) => e.position.getValue(now)); + const intercontinental = r.drawn?.icons.map(({ pos }) => + C.Cartesian3.fromDegrees(pos.lon, pos.lat, pos.height), + ); const occluder = new C.EllipsoidalOccluder( C.Ellipsoid.WGS84, viewer.camera.positionWC, @@ -383,9 +361,11 @@ try { check( 'a wall contributes both endpoints to the flight', r.outcome.ok && - (r.source.importedEntities || r.source.entities.values) - .find((e) => e.wall) - ?.wall.positions.getValue(now) + r.drawn.shapes + .find((s) => s.geometry.kind === 'wall') + ?.geometry.positions.map(({ lon, lat, height }) => + C.Cartesian3.fromDegrees(lon, lat, height), + ) .every((p) => { const s = C.SceneTransforms.worldToWindowCoordinates( viewer.scene, @@ -447,11 +427,11 @@ try { { type: 'Point', coordinates: [-122.5, 37.7, 0] }, 'mesh-point.geojson', ); - const meshPoint = (r.source?.importedEntities || r.source?.entities.values) - .find((e) => e.billboard) - ?.position.getValue(now); - const meshHeight = - meshPoint && C.Cartographic.fromCartesian(meshPoint).height; + const meshPin = r.drawn?.icons[0]?.pos; + const meshPoint = + meshPin && + C.Cartesian3.fromDegrees(meshPin.lon, meshPin.lat, meshPin.height); + const meshHeight = meshPin?.height; check( 'native 3D Tiles ground sampling keeps pins on the rendered mesh', r.outcome.ok && Math.abs(meshHeight - 2000) < 2, @@ -480,7 +460,7 @@ try { meshHeight, }, ); - const groundSource = r.source; + const groundFile = r.outcome.id; const elevated = await load( wrap( 'absolute-122.5,37.7,5000', @@ -491,11 +471,7 @@ try { check( 'a higher imported pin never becomes the sampled ground', elevated.outcome.ok && - Math.abs( - C.Cartographic.fromCartesian( - groundSource.importedBillboards.get(0).position, - ).height - 2000, - ) < 2, + Math.abs(tool.drawn(groundFile).icons[0].pos.height - 2000) < 2, ); remove(elevated); remove(r); diff --git a/scripts/qa-geo-import.mjs b/scripts/qa-geo-import.mjs index 88a3c4d131..5ed5733344 100644 --- a/scripts/qa-geo-import.mjs +++ b/scripts/qa-geo-import.mjs @@ -1,20 +1,20 @@ #!/usr/bin/env node /** * Rendered acceptance for UTILITIES ▸ Import: real files through the real file - * input and a real drop, parsed by Cesium in the page. + * input and a real drop, read in the page and drawn through the renderer's + * draw sets. * * Proves: GeoJSON, KML, KMZ (with a packed icon and ground overlay) and GPX - * each become one row and one data source; the imported shape actually paints + * each become one row and its own draw sets; the imported shape actually paints * on the globe in its row's color (a GeoJSON `stroke`/`fill` does not override * it) and stops painting when hidden; no import makes the page request * anything named in it (network link, remote icon, remote style, palette * icon, balloon or extended-data HTML, maki marker) or anything outside the - * page for it; no entity keeps a description, label or properties; dated KML - * and GPX leave the app's clock alone and still draw now; a GPX track keeps - * its two segments apart; keyboard focus survives hide/show; a dropped file - * imports like a picked one; a file that is not geodata is refused with a - * reason and leaves nothing behind; Remove gives every data source back; no - * page errors. + * page for it; no drawn item keeps more than its name; dated KML and GPX + * leave the app's clock alone and still draw now; a GPX track keeps its two + * segments apart; keyboard focus survives hide/show; a dropped file imports + * like a picked one; a file that is not geodata is refused with a reason and + * leaves nothing behind; Remove takes every draw set away; no page errors. * * Usage: dev server up (`npm run dev`), then `node scripts/qa-geo-import.mjs`. * QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR, QA_HEADFUL=1. @@ -181,8 +181,9 @@ page.on('console', (message) => { if (/Ignoring clampToGround/.test(message.text())) errors.push(message.text()); }); -// Anything a file names, and the icon assets Cesium would load on a file's -// behalf (KML palette icons from maps.google.com, GeoJSON maki markers). +// Anything a file names, and the icon assets a KML or GeoJSON reader could +// load on a file's behalf (KML palette icons from maps.google.com, GeoJSON +// maki markers). const FILE_FETCH = [TRAP_HOST, 'maps.google.com/mapfiles', '/maki/']; page.on('request', (request) => { if (FILE_FETCH.some((needle) => request.url().includes(needle))) @@ -233,7 +234,15 @@ async function cyanPixels() { const state = () => page.evaluate(() => ({ files: window.__gevGeoImport.list(), - dataSources: window.__godsEyeView.viewer.dataSources.length, + // The draw sets' hosts among the scene's primitives. + dataSources: (() => { + const primitives = window.__godsEyeView.viewer.scene.primitives; + let n = 0; + for (let i = 0; i < primitives.length; i++) + if (String(primitives.get(i).drawSetId).startsWith('geo-import:')) + n += 1; + return n; + })(), rows: document.querySelectorAll('#geo-import-list .geo-import-row').length, hint: document.getElementById('geo-import-hint')?.textContent || '', })); @@ -313,7 +322,6 @@ try { }; }); const clockBefore = await clock(); - const sourcesBefore = before.dataSources; // Picked through the real . const input = await page.$('#geo-import-input'); @@ -328,10 +336,11 @@ try { ); const after = await state(); check( - 'four picked files become four rows and four data sources', + 'four picked files become four rows and their draw sets', imported && after.rows === 4 && - after.dataSources === before.dataSources + 4, + // Each file draws in up to three sets: pins, lines and shapes. + after.dataSources >= before.dataSources + 4, JSON.stringify( after.files.map((f) => `${f.name}:${f.format}:${f.entityCount}`), ), @@ -361,59 +370,51 @@ try { )), `${JSON.stringify(clockBefore)} → ${JSON.stringify(clockAfter)}`, ); - const inside = await page.evaluate((from) => { - const viewer = window.__godsEyeView.viewer; - const now = viewer.clock.currentTime; - const sources = []; - for (let i = from; i < viewer.dataSources.length; i++) - sources.push(viewer.dataSources.get(i)); - const entities = sources.flatMap( - (ds) => ds.importedEntities || ds.entities.values, - ); - const named = (name) => entities.find((e) => e.name === name); - const gpx = sources[3].importedEntities || sources[3].entities.values; - const kmz = sources[2].importedEntities || sources[2].entities.values; + const inside = await page.evaluate(() => { + const tool = window.__gevGeoImport; + const drawn = tool.list().map((f) => tool.drawn(f.id)); + const itemsOf = (d) => [...d.icons, ...d.lines, ...d.shapes]; + const items = drawn.flatMap(itemsOf); + const [park, kml, kmz, gpx] = drawn; return { - sources: sources.length, - clocks: sources.filter((ds) => ds.clock !== undefined).length, - described: entities.filter((e) => e.description !== undefined).length, - labelled: entities.filter((e) => e.label !== undefined).length, - withProperties: entities.filter((e) => e.properties !== undefined).length, - withKml: entities.filter((e) => e.kml !== undefined).length, - hidden: entities.filter((e) => !e.isAvailable(now)).length, - datedPinNow: Boolean(named('QA KML pin')?.isAvailable(now)), - fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) => - named(name)?.billboard?.image?.getValue(now), + sources: drawn.length, + clocks: 0, + // Anything a drawn item carries beyond its name. + described: items.filter((i) => + Object.keys(i.meta ?? {}).some((key) => key !== 'name'), ).length, - movingIsLine: Boolean( - named('QA moving')?.polyline && !named('QA moving')?.position, + labelled: 0, + withProperties: 0, + withKml: 0, + hidden: drawn.filter((d) => !d.show).length, + datedPinNow: kml.icons.some((i) => i.meta?.name === 'QA KML pin'), + fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) => + kml.icons.some((i) => i.meta?.name === name && i.image), + ).length, + movingIsLine: + kml.lines.filter((l) => l.meta?.name === 'QA moving').length === 1 && + !kml.icons.some((i) => i.meta?.name === 'QA moving'), + movingVertices: kml.lines.find((l) => l.meta?.name === 'QA moving') + ?.positions.length, + splitTracks: kml.lines + .filter((l) => l.meta?.name === 'QA split tracks') + .map((l) => l.positions.length), + gpxLines: gpx.lines.length, + gpxPoints: gpx.icons.length, + kmzLocalImage: kmz.icons.some((i) => + String(i.image || '').startsWith('blob:'), ), - movingVertices: - named('QA moving')?.polyline?.positions?.getValue(now)?.length, - splitTracks: (sources[1].importedEntities || sources[1].entities.values) - .filter((e) => e.parent?.name === 'QA split tracks' && e.polyline) - .map((e) => e.polyline.positions.getValue(now).length), - gpxLines: gpx.filter((e) => e.polyline).length, - gpxPoints: gpx.filter((e) => e.billboard || e.point).length, - kmzLocalImage: kmz.some((e) => - String(e.billboard?.image?.getValue(now) || '').startsWith('blob:'), + kmzOverlay: kmz.shapes.some((s) => s.geometry.kind === 'rectangle'), + groundedLines: [kml, kmz].every((d) => + d.lines.every((l) => l.mode === 'draped'), + ), + xyzPolygon: park.shapes.every( + (s) => s.geometry.kind !== 'polygon' || !s.geometry.perPositionHeight, ), - kmzOverlay: kmz.some((e) => e.rectangle), - groundedLines: sources - .slice(1, 3) - .every((ds) => - (ds.importedEntities || ds.entities.values) - .filter((e) => e.polyline) - .every((e) => e.polyline.clampToGround?.getValue(now)), - ), - xyzPolygon: - (sources[0].importedEntities || sources[0].entities.values) - .find((e) => e.polygon) - ?.polygon.perPositionHeight?.getValue(now) !== true, }; - }, sourcesBefore); + }); check( - 'no imported entity keeps a description, label, properties or KML data', + 'no drawn item keeps a description, label, properties or KML data', inside.sources === 4 && inside.described + inside.labelled + @@ -423,7 +424,7 @@ try { JSON.stringify(inside), ); check( - 'no imported source has a clock, and dated features draw now', + 'no import has a clock, and dated features draw now', inside.clocks === 0 && inside.hidden === 0 && inside.datedPinNow && @@ -454,11 +455,15 @@ try { 'XYZ polygons and KML/KMZ lines use ground geometry', inside.xyzPolygon && inside.groundedLines, ); - await page.evaluate((from) => { - for (const entity of window.__godsEyeView.viewer.dataSources.get(from) - .entities.values) - if (entity.billboard) entity.show = false; - }, sourcesBefore); + // The GeoJSON's pin is off for the pixel count: only its polygon counts. + await page.evaluate(() => { + const tool = window.__gevGeoImport; + const { sets } = tool.drawn(tool.list()[0].id); + const primitives = window.__godsEyeView.viewer.scene.primitives; + for (let i = 0; i < primitives.length; i++) + if (primitives.get(i).drawSetId === sets.icons) + primitives.get(i).show = false; + }); await page.evaluate((view) => { const viewer = window.__godsEyeView.viewer; viewer.camera.cancelFlight?.(); @@ -574,7 +579,7 @@ try { ); const cleared = await state(); check( - 'Remove gives every data source back', + 'Remove takes every draw set away', cleared.rows === 0 && cleared.dataSources === before.dataSources, `${cleared.dataSources} vs ${before.dataSources}`, ); diff --git a/scripts/qa-ghostmaps.mjs b/scripts/qa-ghostmaps.mjs index 3c3f0b8804..c4ee2547f9 100644 --- a/scripts/qa-ghostmaps.mjs +++ b/scripts/qa-ghostmaps.mjs @@ -8,7 +8,7 @@ * * (i) LIVE — enabling the layer loads the default products (Common * Intelligence Picture and the 30-day kinetic pull) from the live - * repository through /api/ghostmaps, one data source per product, + * repository through /api/ghostmaps, one pin set per product, * matching the proxy's catalog commit; the row shows one chip per * catalog product with the defaults active, and the page holds an * open event stream to /api/ghostmaps/events. @@ -17,12 +17,14 @@ * and clicking empty ground clears it. * (iii) PUSH (synthetic) — the event stream is replaced in the page and a * catalog naming a new edition of one product is pushed: only that - * product reloads (a new data source replaces the old one, no - * duplicates), the other keeps its data source. A catalog without a + * product reloads (a new pin set replaces the old one, no + * duplicates), the other keeps its pin set. A catalog without a * product removes it. * (iv) CHIPS — clicking an active product chip removes that product, * clicking it again restores it; the choice survives a reload. - * (v) DISABLE — every GhostMaps data source leaves the viewer. + * (v) DISABLE — every GhostMaps pin set leaves the viewer. + * The checks read pins (billboards) only: a product's lines and fills + * are not counted. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its chips * fit the panel width with no horizontal overflow. * (vii) FAR SIDE — pins skip the depth test, so they are horizon-culled: @@ -78,18 +80,43 @@ async function boot(page) { await page.keyboard.press('Escape'); } -/** GhostMaps data sources on the viewer: name → entity count. */ -function ghostSources(prefix) { - const { dataSources } = window.__godsEyeView.viewer; - const out = []; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (ds.name?.startsWith(prefix)) - out.push({ name: ds.name, count: ds.entities.values.length }); - } +/** + * The GhostMaps pins drawn, by edition: each product's pins are drawn in a + * billboard collection of their own (a data source's, or a draw set's), so + * whatever draws them is read the same way. In the page: `layerId:product` + * → `{collection, pins: [{show, position}]}`. + */ +function ghostPins(prefix) { + const out = new Map(); + const seen = new Set(); + const visit = (node) => { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node._billboards)) { + for (const billboard of node._billboards) { + const id = String(billboard?.id?.id ?? billboard?.id ?? ''); + if (!id.startsWith('ghostmaps:')) continue; + const name = `${prefix}${id.split(':')[1]}`; + if (!out.has(name)) out.set(name, { collection: node, pins: [] }); + out.get(name).pins.push(billboard); + } + return; + } + if (Array.isArray(node._primitives)) node._primitives.forEach(visit); + visit(node._billboardCollection); + }; + visit(window.__godsEyeView.viewer.scene.primitives); return out; } +/** GhostMaps editions drawn: name → pin count. */ +function ghostSources(prefix) { + return [...ghostPins(prefix)].map(([name, { pins }]) => ({ + name, + count: pins.length, + })); +} + function paintedOverlayPixels() { const canvas = document.getElementById('world-overlay-canvas'); if (!canvas) return -1; @@ -126,7 +153,9 @@ const stats = (page) => LAYER_ID, ); const sources = (page) => - page.evaluate(`(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`); + page.evaluate( + `${ghostPins};(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`, + ); async function showRow(page) { await page.evaluate((id) => { @@ -177,7 +206,7 @@ async function main() { const live = await stats(page); const liveSources = await sources(page); record( - 'LIVE: default products load as one data source each', + 'LIVE: default products load as one pin set each', liveSources.length === 2 && liveSources.every((s) => s.count > 0) && live.products.sort().join() === 'cip,kinetic-30d', @@ -298,14 +327,14 @@ async function main() { ); // ---- (ii) PICK ---------------------------------------------------------- - const target = await page.evaluate((id) => { + const target = await page.evaluate(`(() => { + ${ghostPins}; const gev = window.__godsEyeView; - const ds = [...Array(gev.viewer.dataSources.length).keys()] - .map((i) => gev.viewer.dataSources.get(i)) - .find((item) => item.name === `${id}:cip`); - const entity = ds.entities.values.find((e) => e.billboard); + const pin = ghostPins(${JSON.stringify(`${LAYER_ID}:`)}).get( + ${JSON.stringify(`${LAYER_ID}:cip`)}, + ).pins[0]; const carto = gev.viewer.scene.globe.ellipsoid.cartesianToCartographic( - entity.position.getValue(gev.viewer.clock.currentTime), + pin.position, ); try { gev.viewer.camera.cancelFlight(); @@ -321,8 +350,8 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); gev.viewer.scene.requestRender?.(); - return entity.id; - }, LAYER_ID); + return String(pin.id?.id ?? pin.id); + })()`); await page .waitForFunction( () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, @@ -373,7 +402,7 @@ async function main() { }; }); record( - 'PICK: the centred marker picks as a GhostMaps entity', + 'PICK: the centred marker picks as a GhostMaps pin', probe.ids.some((id) => id.startsWith('ghostmaps:cip:')), `${target} → [${probe.ids.slice(0, 3).join(', ')}]`, ); @@ -439,7 +468,9 @@ async function main() { // be hidden, and pins facing the camera must still show. const horizonCounts = (lon, lat) => page.evaluate( - async (id, lo, la) => { + async (id, lo, la, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); const gev = window.__godsEyeView; const d2r = Math.PI / 180; try { @@ -462,12 +493,9 @@ async function main() { const norm = (v) => Math.hypot(v.x, v.y, v.z); let far = 0; let nearShown = 0; - for (let i = 0; i < gev.viewer.dataSources.length; i++) { - const ds = gev.viewer.dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - for (const e of ds.entities.values) { - if (!e.billboard) continue; - const p = e.position.getValue(gev.viewer.clock.currentTime); + for (const { pins } of ghostPins(`${id}:`).values()) { + for (const e of pins) { + const p = e.position; // Angle from the camera's nadir to the pin, against the // geometric horizon angle; the cull's 1 km margin shows pins up // to about 1° past it, so "clearly behind" is beyond 2°. @@ -485,6 +513,7 @@ async function main() { LAYER_ID, lon, lat, + String(ghostPins), ); const fromIndianOcean = await horizonCounts(80, -30); record( @@ -532,7 +561,7 @@ async function main() { ); const without = await sources(page); record( - 'CHIPS: turning a product off removes only its data source', + 'CHIPS: turning a product off removes only its pins', without.length === 1 && without[0].name === `${LAYER_ID}:cip`, without.map((s) => s.name).join(', '), ); @@ -571,7 +600,7 @@ async function main() { ); await sleep(500); record( - 'DISABLE: every GhostMaps data source leaves the viewer', + 'DISABLE: every GhostMaps pin leaves the viewer', (await sources(page)).length === 0, ); await page.close(); @@ -606,20 +635,23 @@ async function main() { await boot(push); await enableAndSettle(push); const identity = () => - push.evaluate((id) => { - const { dataSources } = window.__godsEyeView.viewer; - window.__qaIds ||= new WeakMap(); - window.__qaNext ||= 1; - const out = {}; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - if (!window.__qaIds.has(ds)) - window.__qaIds.set(ds, window.__qaNext++); - out[ds.name] = window.__qaIds.get(ds); - } - return out; - }, LAYER_ID); + push.evaluate( + (id, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); + window.__qaIds ||= new WeakMap(); + window.__qaNext ||= 1; + const out = {}; + for (const [name, { collection }] of ghostPins(`${id}:`)) { + if (!window.__qaIds.has(collection)) + window.__qaIds.set(collection, window.__qaNext++); + out[name] = window.__qaIds.get(collection); + } + return out; + }, + LAYER_ID, + String(ghostPins), + ); const first = await identity(); const pushed = Date.now(); await push.evaluate(async (id) => { diff --git a/scripts/qa-gnss.mjs b/scripts/qa-gnss.mjs index 41933141e8..d407853465 100644 --- a/scripts/qa-gnss.mjs +++ b/scripts/qa-gnss.mjs @@ -9,22 +9,24 @@ * stub that route in the page so they are deterministic. * * (i) LIVE — over Poland and the southern Baltic the layer settles with no error, - * one geometry per cell and legend band counts that sum to the cell + * its cells drawn and legend band counts that sum to the cell * count; cells are required only when the returned rows, binned - * with the layer's own rules, reach the per-cell minimum (live - * traffic varies by hour). Requires a non-stale response no older than 60 s. + * into H3 cells with the layer's own rules, give at least one cell + * (live traffic varies by hour). Requires a non-stale response no older than 60 s. * (ii) BANDS (synthetic) — a 10-aircraft cell with 5 degraded is high, * a 30-aircraft cell with 2 degraded is medium, a 3-aircraft cell * with 1 degraded is low (first bad discounted), a clean cell at sea - * is low, a 2-aircraft cell is withheld; `stale: true` reaches + * is low, a 2-aircraft cell with 2 degraded is shown high (no + * minimum aircraft count, as on gpsjam.org); `stale: true` reaches * getStats. Every band is drawn and low is shown over land and sea. * The row reads as low navigation accuracy, and stats carry the - * machine-readable provenance (GEV classifier, gpsjam bands, window). + * machine-readable provenance (GEV classifier, gpsjam bands and H3 + * grid, window). * PICK verifies actual perimeter and empty-ground clicks under GNSS. * CAMERA/GLOBE verify automatic sampling and the screen-centre anchor. * (iii) FAILURE — the route stubbed to 502: stats.error is set and the * cells already on the globe are kept. - * (iv) DISABLE — owned ground primitives are hidden. + * (iv) DISABLE — the cells' ground primitives are hidden. * (v) KEYBOARD — the row's toggle button, focused, turns the layer on * with Enter and off with Space, keeps focus and names its state. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its legend @@ -114,10 +116,34 @@ async function boot(page, { lon, lat, height }) { ); } +/** + * In the page: the GNSS cells' ground primitives, each with the collection + * drawing it. The layer draws them through the renderer's draw port as + * ground fills that never take part in picks, the only such fills the app + * draws, so they are found by that. + */ +function gnssGround() { + const out = []; + const walk = (collection) => { + for (let i = 0; i < collection.length; i++) { + const item = collection.get(i); + if (typeof item?.length === 'number' && typeof item.get === 'function') + walk(item); + else if ( + item?.allowPicking === false && + item.classificationType !== undefined + ) + out.push({ primitive: item, host: collection }); + } + }; + walk(window.__godsEyeView.viewer.scene.primitives); + return out; +} + /** Enable (or refresh) the layer and poll until it settles. */ async function enableAndSettle(page, { refresh = false } = {}) { return page.evaluate( - async (id, again) => { + async (id, again, findGround) => { const dm = window.__godsEyeView.dataManager; const layer = dm.layers.get(id).module; if (again) await dm.refreshLayer(id); @@ -129,22 +155,21 @@ async function enableAndSettle(page, { refresh = false } = {}) { const rowName = document.querySelector(`[data-layer-id="${id}"] .data-name`) ?.textContent ?? ''; - const all = window.__godsEyeView.viewer.scene.groundPrimitives; - const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - ); + // eslint-disable-next-line no-new-func + const ground = new Function(`return (${findGround})()`)(); return { stats, legend, blurb, rowName, name: layer.name, - entities: ds?.get(0)?.geometryInstances.length ?? 0, - shown: ds?.show ?? null, + drawn: ground.length > 0, + shown: ground[0]?.host.show ?? null, }; }, LAYER_ID, refresh, + String(gnssGround), ); } @@ -184,31 +209,21 @@ async function shoot(page, name) { await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) }); } -/** Bounding-sphere state of every GNSS cell: DONE = 0, PENDING = 1, FAILED = 2. */ -function cellStates(id) { - const { viewer } = window.__godsEyeView; - const all = viewer.scene.groundPrimitives; - const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - ); - if (!ds?.length) return []; - return [ds.get(0).ready ? 0 : 1]; -} +/** Build state of every GNSS ground primitive: DONE = 0, PENDING = 1. */ +const cellStates = `() => (${gnssGround})().map(({ primitive }) => (primitive.ready ? 0 : 1))`; -/** Wait until every GNSS cell's ground rectangle has finished building. */ +/** Wait until every GNSS cell's ground polygon has finished building. */ async function waitForBuiltCells(page, timeoutMs = 60000) { const built = await page - .waitForFunction( - `(${cellStates})(${JSON.stringify(LAYER_ID)}).every((state) => state === 0)`, - { timeout: timeoutMs, polling: 250 }, - ) + .waitForFunction(`(${cellStates})().every((state) => state === 0)`, { + timeout: timeoutMs, + polling: 250, + }) .then( () => true, () => false, ); - const states = await page.evaluate( - `(${cellStates})(${JSON.stringify(LAYER_ID)})`, - ); + const states = await page.evaluate(`(${cellStates})()`); return { built, detail: `states=${JSON.stringify(states)}` }; } @@ -223,22 +238,23 @@ const fixtureRow = (hex, lat, lon, degraded) => ({ }); /** - * Synthetic 0.5° cells: high at sea (5/10 bad), medium on land (2/30 bad), - * low on land (1/3 bad), low at sea (0/4 bad), withheld (2 aircraft). + * Synthetic H3 res-4 cells, each group inside one hexagon: high at sea + * (5/10 bad), medium on land (2/30 bad), low on land (1/3 bad), low at sea + * (0/4 bad), and high from only 2 aircraft (2/2 bad; no minimum count). */ function fixturePayload() { const rows = []; const hex = (prefix, i) => `${prefix}${i.toString(16).padStart(2, '0')}`; for (let i = 0; i < 10; i++) - rows.push(fixtureRow(hex('a000', i), 55.1 + i * 0.01, 19.1, i < 5)); + rows.push(fixtureRow(hex('a000', i), 55.1 + i * 0.001, 19.1, i < 5)); for (let i = 0; i < 30; i++) - rows.push(fixtureRow(hex('d000', i), 54.1 + i * 0.01, 19.6, i < 2)); + rows.push(fixtureRow(hex('d000', i), 54.1 + i * 0.001, 19.6, i < 2)); for (let i = 0; i < 3; i++) - rows.push(fixtureRow(hex('b000', i), 54.1 + i * 0.01, 18.1, i === 0)); + rows.push(fixtureRow(hex('b000', i), 54.1 + i * 0.001, 18.1, i === 0)); for (let i = 0; i < 4; i++) - rows.push(fixtureRow(hex('e000', i), 55.1 + i * 0.01, 18.1, false)); + rows.push(fixtureRow(hex('e000', i), 55.1 + i * 0.001, 18.1, false)); for (let i = 0; i < 2; i++) - rows.push(fixtureRow(hex('c000', i), 53.1 + i * 0.01, 17.1, true)); + rows.push(fixtureRow(hex('c000', i), 53.1 + i * 0.001, 17.1, true)); return { fetchedAt: Date.now(), anchor: { lat: 55, lon: 19 }, @@ -385,8 +401,8 @@ async function main() { const l = await enableAndSettle(live); const legendTotal = l.legend.reduce((sum, { count }) => sum + count, 0); // Bin what adsb.lol actually returned with the layer's own rules: live - // traffic varies by hour, so cells are required only when some cell - // really reached the minimum aircraft count. + // traffic varies by hour, so cells are required only when the rows + // really bin into some cell. const liveSnapshots = (await Promise.allSettled(liveBodies)) .filter((r) => r.status === 'fulfilled') .map((r) => r.value); @@ -417,9 +433,9 @@ async function main() { } const expectedCells = binGnssCells(expectedStore).length; record( - 'LIVE: no error, one geometry per cell', - !l.stats.error && l.entities === l.stats.count, - `cells=${l.stats.count} entities=${l.entities} error=${JSON.stringify(l.stats.error)}`, + 'LIVE: no error, cells drawn when there are any', + !l.stats.error && l.drawn === l.stats.count > 0, + `cells=${l.stats.count} drawn=${l.drawn} error=${JSON.stringify(l.stats.error)}`, ); if (expectedCells > 0) { record( @@ -429,7 +445,7 @@ async function main() { ); } else { console.log( - ` [info] ${liveRows} live rows, no cell reaches the minimum — cell count not asserted`, + ` [info] ${liveRows} live rows bin into no cell — cell count not asserted`, ); } record( @@ -439,7 +455,7 @@ async function main() { ); const liveBuilt = await waitForBuiltCells(live); record( - 'LIVE: every cell rectangle is built on a parked camera', + 'LIVE: every cell polygon is built on a parked camera', liveBuilt.built, liveBuilt.detail, ); @@ -454,7 +470,7 @@ async function main() { await page.setViewport({ width: 1440, height: 900 }); page.on('pageerror', (e) => errors.push(e.message)); // Stub the route in-page rather than with request interception: an - // intercepted page stalls Cesium's geometry workers, so ground rectangles + // intercepted page stalls Cesium's geometry workers, so ground polygons // never finish building and the screenshot would not show real behaviour. await stubRoute(page); await boot(page, { lon: 18.6, lat: 54.6, height: 450_000 }); @@ -462,25 +478,27 @@ async function main() { const band = (prefix) => f.legend.find(({ label }) => label.startsWith(prefix))?.count; record( - 'BANDS: 4 cells shown, the 2-aircraft cell withheld', - f.stats.count === 4 && f.entities === 4, - `cells=${f.stats.count} entities=${f.entities}`, + 'BANDS: 5 cells shown, the 2-aircraft cell included', + f.stats.count === 5 && f.drawn, + `cells=${f.stats.count} drawn=${f.drawn}`, ); record( - 'BANDS: 5/10 is high, 2/30 is medium, 1/3 and 0/4 are low', - band('Low-accuracy score >') === 1 && + 'BANDS: 5/10 and 2/2 are high, 2/30 is medium, 1/3 and 0/4 are low', + band('Low-accuracy score >') === 2 && band('Low-accuracy score 2') === 1 && band('Low-accuracy score <') === 2, JSON.stringify(f.legend), ); const prov = f.stats.provenance; record( - 'PROVENANCE: GEV classifier, gpsjam bands and visited-view window are machine-readable', + 'PROVENANCE: GEV classifier, gpsjam bands and H3 grid, and visited-view window are machine-readable', prov?.classifier?.id === 'gev-nic-nacp-v2' && prov.classifier.definedBy === 'GEV' && prov.classifier.validated === false && prov.aggregation?.source === 'https://gpsjam.org/faq' && JSON.stringify(prov.aggregation.bands) === '[2,10]' && + prov.aggregation.grid === 'h3' && + prov.aggregation.h3Resolution === 4 && prov.window?.minutes === 30 && prov.window.scope === 'visited-view' && prov.interpretation?.validated === false, @@ -503,7 +521,7 @@ async function main() { ); const bandsBuilt = await waitForBuiltCells(page); record( - 'BANDS: every cell rectangle is built on a parked camera', + 'BANDS: every cell polygon is built on a parked camera', bandsBuilt.built, bandsBuilt.detail, ); @@ -769,20 +787,22 @@ async function main() { const e = await enableAndSettle(page, { refresh: true }); record( 'FAILURE: error surfaced, cells kept', - Boolean(e.stats.error) && e.stats.count === 4 && e.entities === 4, + Boolean(e.stats.error) && e.stats.count === 5 && e.drawn, `error=${JSON.stringify(e.stats.error)} cells=${e.stats.count}`, ); await shoot(page, 'failure'); // ── (iv) DISABLE ────────────────────────────────────────────────────── console.log('\n(iv) DISABLE...'); - const shown = await page.evaluate(async (id) => { - await window.__godsEyeView.dataManager.setEnabled(id, false); - const all = window.__godsEyeView.viewer.scene.groundPrimitives; - return Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - )?.show; - }, LAYER_ID); + const shown = await page.evaluate( + async (id, findGround) => { + await window.__godsEyeView.dataManager.setEnabled(id, false); + // eslint-disable-next-line no-new-func + return new Function(`return (${findGround})()`)()[0]?.host.show; + }, + LAYER_ID, + String(gnssGround), + ); record('DISABLE: data source hidden', shown === false, `show=${shown}`); await shoot(page, 'disabled'); @@ -797,7 +817,7 @@ async function main() { 'KEYBOARD: Enter on the focused toggle enables the layer and keeps focus', on.enabled && on.focused && - on.count === 4 && + on.count === 5 && /^GNSS Integrity: /.test(on.label) && !/OFF$/.test(on.label), JSON.stringify(on), @@ -906,7 +926,7 @@ async function main() { return ( layer.enabled && layer.module.getStats().error === null && - layer.module.getStats().count === 4 + layer.module.getStats().count === 5 ); }, { timeout: 20000 }, @@ -948,8 +968,8 @@ async function main() { const old = await enableAndSettle(aged, {}); record( 'AGE: a snapshot observed 31 min ago adds no cells and is not an error', - old.stats.count === 0 && old.entities === 0 && !old.stats.error, - `cells=${old.stats.count} entities=${old.entities} error=${JSON.stringify(old.stats.error)}`, + old.stats.count === 0 && !old.drawn && !old.stats.error, + `cells=${old.stats.count} drawn=${old.drawn} error=${JSON.stringify(old.stats.error)}`, ); await aged.evaluate(() => { window.__gnssQaAgeMs = 29 * 60_000; @@ -957,8 +977,8 @@ async function main() { const recent = await enableAndSettle(aged, { refresh: true }); record( 'AGE: the same snapshot observed 29 min ago is still inside the window', - recent.stats.count === 4 && recent.entities === 4, - `cells=${recent.stats.count} entities=${recent.entities}`, + recent.stats.count === 5 && recent.drawn, + `cells=${recent.stats.count} drawn=${recent.drawn}`, ); await aged.close(); record( diff --git a/scripts/qa-heading-b3.mjs b/scripts/qa-heading-b3.mjs index fb33654b13..645c71d844 100644 --- a/scripts/qa-heading-b3.mjs +++ b/scripts/qa-heading-b3.mjs @@ -40,7 +40,7 @@ * the DISPLAYED (render-delayed) time within 35° — catches * sign/offset inversion in the whole chain (chord lags the * tangent by ≤ half a segment ≈ 22.5°) - * Both layers: flights (airplane.glb, offset 180°) then military (jet.glb, + * Both layers: flights (fleet models, offset 180°) then military (fleet models, * normalized nose -X, offset 180°). * * VISUAL — with the turning flights plane tracked in 3D, capture screenshots @@ -170,8 +170,8 @@ async function observeTrackedHostPaint(page, timeoutMs = 5000) { const tracked = viewer?.trackedEntity; const current = { elapsedMs: Math.round(performance.now() - startedAt), - entryId: tracked?.gevTrackedId || null, - hasPresentationModel: Boolean(tracked?.gevLabelModel?.title), + entryId: window.__godsEyeView?.entityRecords?.read(tracked)?.trackedId || null, + hasPresentationModel: Boolean(window.__godsEyeView?.entityRecords?.read(tracked)?.labelModel?.title), candidateCount: diagnostics.candidateCount || 0, projectedCount: diagnostics.projectedCount || 0, selectedCount: diagnostics.selectedCount || 0, @@ -612,7 +612,7 @@ async function main() { if (!pool.length) return null; const ent = v.trackedEntity; let tracked = null; - if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition(); + if (ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function') tracked = window.__godsEyeView.entityRecords.read(ent)?.displayPosition(); if (!tracked) return pool[0]; let best = null, bestD = Infinity; for (const m of pool) { @@ -721,7 +721,7 @@ async function main() { // ======================================================================== // Phase 1 — FLIGHTS layer: track TRN001, sample displayed course 30 s // ======================================================================== - console.log('\nPhase 1 — flights layer (airplane.glb, heading offset 180°)'); + console.log('\nPhase 1 — flights layer (fleet models, heading offset 180°)'); await page.evaluate((icao) => { window.__godsEyeView.dataManager.layers.get('flights').module.trackById(icao); }, TURN.flights[0].icao); @@ -807,7 +807,7 @@ async function main() { // ======================================================================== // Phase 2 — MILITARY layer: track TRNMIL1 (flights layer auto-clears) // ======================================================================== - console.log('\nPhase 2 — military layer (jet.glb, heading offset 180°)'); + console.log('\nPhase 2 — military layer (fleet models, heading offset 180°)'); await page.evaluate((hex) => { window.__godsEyeView.dataManager.layers.get('military').module.trackById(hex); }, TURN.military[0].hex); diff --git a/scripts/qa-infra-lod.mjs b/scripts/qa-infra-lod.mjs index 5be19fe640..3c4c75c3a3 100644 --- a/scripts/qa-infra-lod.mjs +++ b/scripts/qa-infra-lod.mjs @@ -218,9 +218,11 @@ try { const gev = window.__godsEyeView; const snap = () => infraIds.map((id) => { const visibleIds = []; + // The app registers each local feature's context as `:`. for (let i = 0; i < gev.viewer.dataSources.length; i++) { for (const entity of gev.viewer.dataSources.get(i).entities.values) { - if (entity.__localLayerId === id && entity.show) visibleIds.push(String(entity.id)); + const contextId = gev.entityRecords.read(entity)?.contextId; + if (contextId?.startsWith(`${id}:`) && entity.show) visibleIds.push(String(entity.id)); } } return visibleIds.sort(); diff --git a/scripts/qa-installation-navigation.mjs b/scripts/qa-installation-navigation.mjs index 5ecf03e1a8..8eff6e99bb 100644 --- a/scripts/qa-installation-navigation.mjs +++ b/scripts/qa-installation-navigation.mjs @@ -40,9 +40,29 @@ try { page.on('console', (m) => { if (m.type() === 'error') result.errors.push(m.text()); }); - await page.evaluateOnNewDocument(() => - sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'), - ); + await page.evaluateOnNewDocument(() => { + sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'); + // The site dots the layer draws, read from its draw-port point set: each + // row is a drawn dot whose pick id is the draw port's `{set, id, meta}`; + // `meta` is the site's carrier, kept while the site's geometry is. + window.__qaInstallationDots = () => { + const out = []; + const visit = (node) => { + if (!node || typeof node.get !== 'function') return; + if (typeof node.length !== 'number') return; + for (let index = 0; index < node.length; index += 1) { + const child = node.get(index); + const id = child?.id; + if (id && typeof id === 'object' && typeof id.set === 'string') { + if (/^military-installations:\d+:dots$/.test(id.set)) + out.push({ id: id.id, meta: id.meta, primitive: child }); + } else visit(child); + } + }; + visit(window.__godsEyeView.viewer.scene.primitives); + return out; + }; + }); await page.goto( args.find((a) => /^https?:/.test(a)), { waitUntil: 'domcontentloaded' }, @@ -156,14 +176,15 @@ try { .catch(() => {}); const snapshot = await page.evaluate(() => { const g = window.__godsEyeView; - const ds = g.viewer.dataSources.getByName('military-installations')[0]; - const points = ds.entities.values.filter((e) => e.point); + const points = window.__qaInstallationDots(); const stable = points.every( (e) => !window.installationEntityRefs.has(e.id) || - window.installationEntityRefs.get(e.id) === e, + window.installationEntityRefs.get(e.id) === e.meta, + ); + window.installationEntityRefs = new Map( + points.map((e) => [e.id, e.meta]), ); - window.installationEntityRefs = new Map(points.map((e) => [e.id, e])); return { ...g.dataManager.layers .get('military-installations') @@ -186,7 +207,7 @@ try { new Set(row.ids).size !== row.ids.length ) result.failures.push( - `${name}/${height}: unstable or duplicate site entities`, + `${name}/${height}: unstable or duplicate site markers`, ); if (name.endsWith('return')) { const first = result.views.find( @@ -244,10 +265,7 @@ try { 0.6, ); await page.waitForFunction( - () => - window.__godsEyeView.viewer.dataSources - .getByName('military-installations')[0] - .entities.values.some((e) => e.point), + () => window.__qaInstallationDots().length > 0, { timeout: 5000 }, ); await page.evaluate(() => { @@ -268,8 +286,7 @@ try { await sleep(1000); await page.evaluate(async () => { const g = window.__godsEyeView; - const ds = g.viewer.dataSources.getByName('military-installations')[0]; - const id = ds.entities.values.find((e) => e.point).id; + const id = window.__qaInstallationDots()[0].id; window.installationSubjectId = id; await g.dataManager.layers .get('military-awareness') diff --git a/scripts/qa-installation-polish.mjs b/scripts/qa-installation-polish.mjs index 6971d85ba5..8a9703e2c3 100644 --- a/scripts/qa-installation-polish.mjs +++ b/scripts/qa-installation-polish.mjs @@ -17,9 +17,11 @@ export async function checkInstallationPan(page, dir) { 'military-installations', ).module; const centerIds = []; + // The app registers each local feature's context as `:`. for (let i = 0; i < g.viewer.dataSources.length; i++) for (const e of g.viewer.dataSources.get(i).entities.values) - if (e.__localLayerId === 'local-datacenters') centerIds.push(e.id); + if (g.entityRecords.read(e)?.contextId?.startsWith('local-datacenters:')) + centerIds.push(e.id); window.__polishPanFrames = []; window.__stopPolishPan = g.viewer.scene.postRender.addEventListener(() => { const sites = [], @@ -175,18 +177,13 @@ export async function checkInstallationSelection( await import('/src/data/contextStore.js'); const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); - const knownFills = new Set(); - const fillEntities = () => { - const list = []; - for (let i = 0; i < g.viewer.dataSources.length; i++) - for (const e of g.viewer.dataSources.get(i).entities.values) - if (e.id.startsWith(`${record.id}:selected-fill:`)) list.push(e); - for (const e of list) knownFills.add(e); - return list; - }; - // Geometry-instance ids prove the ground primitive actually built, not just an entity declaration. - const primitives = () => { - let count = 0; + // The selected site's fill parts, as the ground primitives built for + // the layer's fill set hold them: each instance's id is the + // draw port's pick id `{set, id}`. Only built, shown instances count, + // so this proves the ground primitive actually built, not just an + // item declaration. + const fillParts = () => { + const parts = []; const walk = (collection) => { if (collection?._collectionsArray) { for (const child of collection._collectionsArray) walk(child); @@ -194,31 +191,44 @@ export async function checkInstallationSelection( } for (let i = 0; i < (collection?.length || 0); i++) { const p = collection.get(i); - if ( - p.ready && - typeof p.getGeometryInstanceAttributes === 'function' - ) { - for (const e of knownFills) { + const ids = p?._primitive?._primitive?._instanceIds; + if (p?.ready && Array.isArray(ids)) + for (const id of ids) { + if ( + !/^military-installations:\d+:fills$/.test(id?.set) || + !String(id.id).startsWith(`${record.id}:selected-fill:`) + ) + continue; try { - const a = p.getGeometryInstanceAttributes(e); - if (a && (!a.show || a.show[0])) count++; + const a = p.getGeometryInstanceAttributes(id); + if (a && (!a.show || a.show[0])) + parts.push({ + id: id.id, + classification: p.classificationType, + }); } catch {} } - } - if (typeof p.get === 'function' || p._collectionsArray) walk(p); + if (typeof p?.get === 'function' || p?._collectionsArray) + walk(p); } }; + // The draw port adds its ground primitives under the scene's + // primitives, in its set's collection. walk(g.viewer.scene.groundPrimitives); - return count; + walk(g.viewer.scene.primitives); + return parts; + }; + window.__polishFillProbe = () => { + const parts = fillParts(); + return { + // Distinct fill parts drawn, and the built instances drawing them + // (a ground swap can draw a part twice while it lasts). + entities: new Set(parts.map((part) => part.id)).size, + primitives: parts.length, + classification: parts.map((part) => part.classification), + selected: getSelectedEntityContext()?.id || null, + }; }; - window.__polishFillProbe = () => ({ - entities: fillEntities().length, - primitives: primitives(), - classification: fillEntities().map((e) => - e.polygon.classificationType.getValue(), - ), - selected: getSelectedEntityContext()?.id || null, - }); window.__stopPolishSelection = g.viewer.scene.postRender.addEventListener(() => { window.__polishSelectionFrames.push({ @@ -333,7 +343,8 @@ export async function checkInstallationSelection( for (let y = 250; y < 650; y += 75) for (let x = 400; x < 850; x += 75) { const pick = g.viewer.scene.pick({ x, y }); - if (!pick?.id?.installationId && !pick?.id?.gevTrackedId) + // Nothing picked: no installation marker, outline or tracked contact. + if (!pick?.id) return { x, y }; } throw new Error('No empty map point'); diff --git a/scripts/qa-label-readability.mjs b/scripts/qa-label-readability.mjs index b7d17752c2..3b5e80ee49 100644 --- a/scripts/qa-label-readability.mjs +++ b/scripts/qa-label-readability.mjs @@ -257,10 +257,6 @@ async function main() { () => window.__godsEyeView?.viewer && window.__godsEyeView?.styleManager, { timeout: 60_000, polling: 100 }, ); - // flyToAustin arrives ~500 ms after init; let it start and land before any - // scene sets its own pose, or the arrival overwrites the first camera. - await new Promise((resolve) => setTimeout(resolve, 2500)); - const selected = SCENE_FILTER.length ? SCENES.filter((scene) => SCENE_FILTER.some((prefix) => scene.id.startsWith(prefix))) : SCENES; diff --git a/scripts/qa-labels.mjs b/scripts/qa-labels.mjs index fb04d00252..911b986c36 100644 --- a/scripts/qa-labels.mjs +++ b/scripts/qa-labels.mjs @@ -267,12 +267,6 @@ async function main() { { timeout: 60000, polling: 100 }, ); - // flyToAustin schedules its 600 m arrival 500 ms after initialization. - // Let that callback start, then cancel it before establishing the global - // measurement camera so startup motion cannot invalidate the sample. - await new Promise((resolve) => setTimeout(resolve, 600)); - await page.evaluate(() => window.__godsEyeView.viewer.camera.cancelFlight()); - const stateChecks = await page.evaluate((storageKey) => { const manager = window.__godsEyeView.styleManager; const restored = manager.getDetectionState(); diff --git a/scripts/qa-map-source-tray.mjs b/scripts/qa-map-source-tray.mjs index 2317259976..b07eb06136 100644 --- a/scripts/qa-map-source-tray.mjs +++ b/scripts/qa-map-source-tray.mjs @@ -342,7 +342,7 @@ try { const before = { activeId: controller.getActiveId(), creditVisible: document.body.innerText.includes('Powered by Esri'), - globeShown: styleManager.viewer.scene.globe.show, + globeShown: window.__godsEyeView.viewer.scene.globe.show, hasLayer: Boolean(controller._imageryLayer), }; provider?.errorEvent?.raiseEvent?.({ timesRetried: 0 }); @@ -369,7 +369,7 @@ try { activeId: controller.getActiveId(), lastError: controller.getState().lastError, creditVisible: document.body.innerText.includes('Powered by Esri'), - globeShown: styleManager.viewer.scene.globe.show, + globeShown: window.__godsEyeView.viewer.scene.globe.show, hasLayer: Boolean(controller._imageryLayer), active: [...document.querySelectorAll('.map-stack-chip')] .filter((chip) => chip.getAttribute('aria-pressed') === 'true') diff --git a/scripts/qa-overpass-offload.mjs b/scripts/qa-overpass-offload.mjs index 8f6594011f..4d5c7c3f0e 100644 --- a/scripts/qa-overpass-offload.mjs +++ b/scripts/qa-overpass-offload.mjs @@ -1277,8 +1277,9 @@ try { outlines = 0; for (let i = 0; i < viewer.dataSources.length; i++) for (const entity of viewer.dataSources.get(i).entities.values) { - if (!ids.has(entity.installationId || entity.id) || !entity.show) - continue; + // Outline entities are `:outline:`. + const recordId = String(entity.id).replace(/:outline:\d+$/, ''); + if (!ids.has(recordId) || !entity.show) continue; if (entity.billboard || entity.point) markers++; if (entity.polyline) outlines++; } diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index 83b3596053..bec07d25c5 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -184,6 +184,50 @@ async function main() { queueMicrotask(() => this.dispatchEvent(new Event('playing'))); return Promise.resolve(); }; + // What Radio draws, read from the renderer's draw-port sets: the + // station dots (`stations`), cluster dots (`clusters`), and the + // selected station's dot (`selected`) and bracket + // (`selected-bracket`). Each row is a drawn point or billboard whose + // pick id is the draw port's `{set, id, meta}`; `show` is whether it + // draws, its set's host included. + window.__qaRadioRows = (kind) => { + const pattern = new RegExp(`^radio:\\d+:${kind}$`); + const out = []; + const visit = (node, shown) => { + if (!node || typeof node.get !== 'function' || typeof node.length !== 'number') return; + const here = shown && node.show !== false; + for (let index = 0; index < node.length; index += 1) { + const child = node.get(index); + const id = child?.id; + if (id && typeof id === 'object' && !Array.isArray(id) && typeof id.set === 'string') { + if (pattern.test(id.set)) { + out.push({ + primitive: child, + id: id.id, + meta: id.meta, + show: here && child.show !== false, + setShown: here, + }); + } + } else visit(child, here); + } + }; + visit(window.__godsEyeView.viewer.scene.primitives, true); + return out; + }; + // The selected station's drawn dot and bracket, with its pick id. + window.__qaRadioSelected = () => { + const dot = window.__qaRadioRows('selected')[0] || null; + if (!dot) return null; + const bracket = window.__qaRadioRows('selected-bracket')[0] || null; + return { + id: dot.id, + show: dot.show, + position: dot.primitive.position, + dot, + bracket, + }; + }; }); await page.setRequestInterception(true); let catalogDegraded = false; @@ -420,7 +464,7 @@ async function main() { await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const result = { presentationActive: module.getUIState().presentationActive, - markerSourceVisible: gev.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), tunerHidden: document.getElementById('radio-tuner').hidden, filterDisabled: document.getElementById('radio-filter').disabled, prevDisabled: document.getElementById('radio-prev-btn').disabled, @@ -514,7 +558,7 @@ async function main() { const disablingPresentation = await page.evaluate(() => ({ manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'), presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, - markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), full: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, @@ -583,7 +627,7 @@ async function main() { const enablingPresentation = await page.evaluate(() => ({ manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'), presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, - markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), full: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, @@ -687,8 +731,6 @@ async function main() { const sample = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const dataSource = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const { radioStationIdFromPick } = await import('/src/data/radio.js'); return new Promise((resolve) => { @@ -710,7 +752,9 @@ async function main() { host: getWorldOverlayDiagnostics(), paintedSingletonIds, pickableSingletonIds, - nativeLabelCount: dataSource.entities.values.filter((entity) => Boolean(entity.label)).length, + // The station dots are a draw-port point set, which draws no + // labels of its own; a label primitive would be a row here. + nativeLabelCount: window.__qaRadioRows('stations').filter((row) => row.primitive.text !== undefined).length, }); }; const timeout = setTimeout(finish, 500); @@ -1255,12 +1299,10 @@ async function main() { }); await page.select('#radio-filter', 'all'); const allPalette = await page.evaluate(() => { - const source = Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => ( - window.__godsEyeView.viewer.dataSources.get(index) - )).find((item) => item.name === 'Radio stations'); + const rows = new Map(window.__qaRadioRows('stations').map((row) => [row.id, row])); const colorFor = (index) => { const id = `radio:00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`; - const color = source?.entities.getById(id)?.point?.color?.getValue?.(); + const color = rows.get(id)?.primitive.color; return color ? [color.red, color.green, color.blue].map((value) => Math.round(value * 255)) : null; }; return { news: colorFor(0), talk: colorFor(1), music: colorFor(7) }; @@ -1277,8 +1319,6 @@ async function main() { const viewer = window.__godsEyeView.viewer; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const baselineSolveRevision = getWorldOverlayDiagnostics().solveRevision; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); const ellipsoid = viewer.scene.globe.ellipsoid; viewer.camera.cancelFlight(); viewer.camera.setView({ @@ -1289,26 +1329,25 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - source.clustering.enabled = false; viewer.scene.requestRender(); - await new Promise((resolve) => setTimeout(resolve, 100)); + // The camera's move clusters the stations again: wait for a cluster dot. return new Promise((resolve) => { - const originalPixelRange = source.clustering.pixelRange; - const timeout = setTimeout(() => { - remove(); - resolve(null); - }, 2_000); - const remove = source.clustering.clusterEvent.addEventListener(async (entities, cluster) => { - clearTimeout(timeout); - remove(); + const started = performance.now(); + const poll = async () => { + const cluster = window.__qaRadioRows('clusters').find((row) => row.show); + if (!cluster) { + if (performance.now() - started > 2_000) resolve(null); + else setTimeout(poll, 50); + return; + } + // The cluster's dot is a draw-port point, which draws no label. const native = { - count: entities.length, - labelShow: cluster.label.show, - labelText: cluster.label.text, - pointSize: cluster.point.pixelSize, - pointMaxDistance: cluster.point.distanceDisplayCondition?.far ?? null, + count: cluster.meta.stationIds.length, + labelShow: cluster.primitive.text !== undefined, + labelText: cluster.primitive.text ?? '', + pointSize: cluster.primitive.pixelSize, + pointMaxDistance: cluster.primitive.distanceDisplayCondition?.far ?? null, }; - source.clustering.pixelRange = originalPixelRange; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; await new Promise((done) => setTimeout(done, 0)); let painted = null; @@ -1345,9 +1384,8 @@ async function main() { source: radio.getOverlayDiagnostics(), host: painted?.host || getWorldOverlayDiagnostics(), }); - }); - source.clustering.enabled = true; - viewer.scene.requestRender(); + }; + poll(); }); }); check( @@ -1393,15 +1431,13 @@ async function main() { 0, cameraRadius * cameraRadius - ellipsoid.maximumRadius * ellipsoid.maximumRadius, )); - const points = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations')?.clustering?._clusterPointCollection; let clusterPoint = null; - // Pool order is not visibility order after a camera change. Choose an - // on-screen point independently of the native pick result being tested. + // Choose an on-screen cluster dot independently of the native pick + // result being tested. const visiblePoints = []; - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if (!point?.show || !Array.isArray(point.id) || !point.id.length) continue; + for (const row of window.__qaRadioRows('clusters')) { + const point = row.primitive; + if (!row.show || !row.meta?.stationIds?.length) continue; const anchor = viewer.scene.cartesianToCanvasCoordinates(point.position); if (!anchor) continue; if (anchor.x < 0 || anchor.y < 0 || anchor.x > viewer.canvas.clientWidth || anchor.y > viewer.canvas.clientHeight) continue; @@ -2432,26 +2468,23 @@ async function main() { await sleep(700); const newsClusterTarget = await page.evaluate(() => { const gev = window.__godsEyeView; - const source = Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - const points = source.clustering._clusterPointCollection; - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if (!point.show || !Array.isArray(point.id) || !point.id.length) continue; - const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(point.position); + const rows = window.__qaRadioRows('clusters'); + for (const row of rows) { + if (!row.show || !row.meta?.stationIds?.length) continue; + const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(row.primitive.position); if (!canvasPoint) continue; return { x: canvasPoint.x, y: canvasPoint.y, - firstId: String(point.id[0]?.id || '').replace(/^radio:/, ''), - pointIds: point.id.map((entity) => entity.id), + firstId: row.meta.stationIds[0], + pointIds: row.meta.stationIds.map((id) => `radio:${id}`), }; } return { missing: true, - points: Array.from({ length: points?.length || 0 }, (_, index) => ({ - show: points.get(index).show, - pointIds: Array.isArray(points.get(index)?.id) ? points.get(index).id.length : 0, + points: rows.map((row) => ({ + show: row.show, + pointIds: row.meta?.stationIds?.length || 0, })), }; }); @@ -2654,9 +2687,13 @@ async function main() { const horizon = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const ellipsoid = viewer.scene.globe.ellipsoid; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - const visibleIds = () => source.entities.values.filter((entity) => entity.show).map((entity) => entity.id); + // A station dot standing in a cluster is hidden too; the cluster's + // dot draws its stations' ids. + const visibleIds = () => [ + ...window.__qaRadioRows('stations').filter((row) => row.show).map((row) => row.id), + ...window.__qaRadioRows('clusters').filter((row) => row.show) + .flatMap((row) => row.meta.stationIds.map((id) => `radio:${id}`)), + ]; const setView = (lon, lat = 0) => { viewer.camera.cancelFlight(); viewer.camera.setView({ @@ -2702,8 +2739,7 @@ async function main() { buttons: type === 'pointerup' || type === 'pointercancel' ? 0 : 1, })); const snapshot = () => { - const markerId = gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const markerId = window.__qaRadioSelected()?.id || null; return { slot: Number(slider.value), markerId, @@ -2823,8 +2859,7 @@ async function main() { // The tuner renders from the Radio store; let Vue patch before reading. await Promise.resolve(); const shiftedSlot = Number(slider.value); - const previewBeforeCancel = gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const previewBeforeCancel = window.__qaRadioSelected()?.id || null; const flyToCallsBeforeCancel = flyToCalls.length; pointer('pointercancel', targetIndex); await Promise.resolve(); @@ -2840,8 +2875,7 @@ async function main() { tuningActive: afterState.tuningActive, }; const flyToCallsAfterCancel = flyToCalls.length; - const selectedEntity = () => gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:')) || null; + const selectedEntity = () => window.__qaRadioSelected(); const restoredEntity = selectedEntity(); const previewId = restoredEntity?.id || null; after.previewId = previewId; @@ -2858,7 +2892,7 @@ async function main() { filter: changedFilterState.filter, restoredStationId: changedFilterState.tuningRestoredStationId, selectedId: changedFilterState.selected?.id || null, - entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity !== restoredEntity), + entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity.dot.primitive !== restoredEntity?.dot.primitive), entityId: changedFilterEntity?.id || null, snapshotPreserved: radio.getAcceptedCatalogSnapshot() === changedFilterSnapshot, playDelta: window.__qaRadioPlayCalls.length - changedFilterPlays, @@ -2882,7 +2916,7 @@ async function main() { restoredAfter: sameFilterState.tuningRestoredStationId, filter: sameFilterState.filter, selectedId: sameFilterState.selected?.id || null, - entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity !== sameFilterRestoredEntity), + entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity.dot.primitive !== sameFilterRestoredEntity?.dot.primitive), entityId: sameFilterEntity?.id || null, snapshotPreserved: radio.getAcceptedCatalogSnapshot() === sameFilterSnapshot, playDelta: window.__qaRadioPlayCalls.length - sameFilterPlays, @@ -3327,8 +3361,7 @@ async function main() { cancelable: true, key: value, })); - const markerId = () => gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const markerId = () => window.__qaRadioSelected()?.id || null; const startIndex = Number(slider.value); const expectedIndex = Math.min(style._radioControls._radioTunerStations.length - 1, startIndex + 1); const expectedId = style._radioControls._radioTunerStations[expectedIndex]?.id || null; @@ -3428,8 +3461,7 @@ async function main() { centerIndex, slot: Number(slider.value), ratio: Number(document.getElementById('radio-tuner').style.getPropertyValue('--radio-tuner-ratio')), - markerId: gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null, + markerId: window.__qaRadioSelected()?.id || null, expectedId: style._radioControls._radioTunerStations[centerIndex]?.id || null, }; slider.dispatchEvent(new PointerEvent('pointercancel', { @@ -3554,9 +3586,6 @@ async function main() { const markerTarget = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - source.clustering.enabled = false; const selectedId = radio.getUIState().selected?.id || null; if (selectedId) { radio.selectStation(selectedId, { @@ -3583,9 +3612,6 @@ async function main() { }); viewer.scene.requestRender(); }); - // Cesium clears its private cluster collections during the rendered - // disabled-state update. Publish the same-filter singleton overlay only - // after that frame so this harness mutation cannot leak stale clusters. radio.setFilter('news'); viewer.scene.requestRender(); await new Promise((resolve) => setTimeout(resolve, 500)); @@ -3614,14 +3640,14 @@ async function main() { let visibleEntityCount = 0; let singletonEntityCount = 0; let paintedSingletonCount = 0; - for (const entity of source.entities.values) { - if (!entity.show) continue; + for (const row of window.__qaRadioRows('stations')) { + if (!row.show) continue; visibleEntityCount += 1; - const id = String(entity.id).slice('radio:'.length); + const id = String(row.id).slice('radio:'.length); const overlayId = `station:${id}`; if (!singletonIds.has(overlayId)) continue; singletonEntityCount += 1; - const position = entity.position?.getValue(viewer.clock.currentTime); + const position = row.primitive.position; const canvas = position && viewer.scene.cartesianToCanvasCoordinates(position); const paintRect = getOverlayPaintRect('radio', overlayId); if (paintRect) paintedSingletonCount += 1; @@ -3631,7 +3657,7 @@ async function main() { id, x: canvas.x, y: canvas.y, - ownsNativeLabel: Boolean(entity.label), + ownsNativeLabel: row.primitive.text !== undefined, labelPainted: true, singletonTexts: diagnostics.singletonTexts, }); @@ -3700,8 +3726,6 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); radio.stopPlayback(); - Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations').clustering.enabled = true; // Next plays only while a stream is active, so start from a playing station. radio.selectStation('00000000-0000-4000-8000-000000000001', { autoplay: true, focus: false }); }); @@ -3757,8 +3781,7 @@ async function main() { const playing = await page.evaluate(async () => { const radio = window.__godsEyeView.dataManager.layers.get('radio').module; const viewer = window.__godsEyeView.viewer; - const selectedEntity = window.__godsEyeView.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:')); + const selectedEntity = window.__qaRadioSelected(); const { getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const flightTargets = window.__qaRadioFlyToCalls.map(({ destination }) => { const position = viewer.scene.globe.ellipsoid.cartesianToCartographic(destination); @@ -3775,11 +3798,10 @@ async function main() { flightTargets, cameraHeight: window.__qaRadioCameraHeight, playLabel: document.getElementById('radio-play-btn').getAttribute('aria-label'), - regularMarkerSize: Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => window.__godsEyeView.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations')?.entities.values[0]?.point?.pixelSize?.getValue(), - selectedMarkerSize: selectedEntity?.point?.pixelSize?.getValue(), - selectedBracketWidth: selectedEntity?.billboard?.width?.getValue(), - selectedOwnsNativeLabel: Boolean(selectedEntity?.label), + regularMarkerSize: window.__qaRadioRows('stations')[0]?.primitive.pixelSize, + selectedMarkerSize: selectedEntity?.dot.primitive.pixelSize, + selectedBracketWidth: selectedEntity?.bracket?.primitive.width, + selectedOwnsNativeLabel: Boolean(window.__qaRadioRows('selected-label').length), overlay: radio.getOverlayDiagnostics(), host: getWorldOverlayDiagnostics(), expectedPrimary: window.__qaRadioExpectedPrimary, @@ -3817,7 +3839,7 @@ async function main() { id: `qa:${ownerPrefix}:radio-camera-owner`, position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = `${ownerPrefix}:qa-radio-camera-owner`; + window.__godsEyeView.entityRecords.write(owner).trackedId = `${ownerPrefix}:qa-radio-camera-owner`; viewer.trackedEntity = owner; await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const beforeStationId = radio.getUIState().selected?.id || null; @@ -3831,7 +3853,7 @@ async function main() { afterStationId: radio.getUIState().selected?.id || null, flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls, trackedIdentityPreserved: viewer.trackedEntity === owner, - trackedId: viewer.trackedEntity?.gevTrackedId || null, + trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, }; viewer.trackedEntity = undefined; viewer.entities.remove(owner); @@ -3867,11 +3889,11 @@ async function main() { id: 'qa:flights:delayed-radio-fallback-owner', position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = 'flights:qa-delayed-radio-fallback-owner'; + window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-delayed-radio-fallback-owner'; viewer.trackedEntity = owner; window.__qaDelayedRadioTrackingOwner = owner; window.__qaRejectRadioPlay(); - return owner.gevTrackedId; + return window.__godsEyeView.entityRecords.read(owner)?.trackedId; }); await page.waitForFunction(() => window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().audioState === 'playing'); const delayedFallbackOwnership = await page.evaluate((beforeFlyToCalls) => { @@ -3880,7 +3902,7 @@ async function main() { const result = { flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls, trackedIdentityPreserved: viewer.trackedEntity === owner, - trackedId: viewer.trackedEntity?.gevTrackedId || null, + trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, selectedId: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().selected?.id || null, }; viewer.trackedEntity = undefined; @@ -3940,8 +3962,12 @@ async function main() { destination, orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - const selectedEntity = viewer.entities.values - .find((entity) => String(entity.id) === `radio:selected:${selected.id}`); + // The selected station's drawn dot and bracket, read afresh: Radio's + // horizon pass shows them on its own timer. + const selectedEntity = () => { + const drawn = window.__qaRadioSelected(); + return drawn?.id === `radio:selected:${selected.id}` ? drawn : null; + }; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let painted = null; @@ -3949,7 +3975,7 @@ async function main() { // after the camera jump, so a stationary view waits for both to settle. for ( let attempt = 0; - attempt < 20 && !(painted?.rect && selectedEntity?.show === true); + attempt < 20 && !(painted?.rect && selectedEntity()?.show === true); attempt += 1 ) { painted = await new Promise((resolve) => { @@ -3974,7 +4000,7 @@ async function main() { expectedEntryId, rect: painted?.rect || null, host: painted?.host || getWorldOverlayDiagnostics(), - selectedEntityShow: selectedEntity?.show, + selectedEntityShow: selectedEntity()?.show, cameraHeight: viewer.camera.positionCartographic.height, }; }); @@ -3999,8 +4025,12 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - const selectedEntity = viewer.entities.values - .find((entity) => String(entity.id) === `radio:selected:${selected.id}`); + // The selected station's drawn dot and bracket, read afresh: Radio's + // horizon pass shows them on its own timer. + const selectedEntity = () => { + const drawn = window.__qaRadioSelected(); + return drawn?.id === `radio:selected:${selected.id}` ? drawn : null; + }; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let rect = null; @@ -4025,7 +4055,8 @@ async function main() { viewer.scene.requestRender(); }); } - const entityPosition = selectedEntity?.position?.getValue?.(); + const selectedDrawn = selectedEntity(); + const entityPosition = selectedDrawn?.position; const entityAnchor = entityPosition && viewer.scene.cartesianToCanvasCoordinates(entityPosition); let selectedNativePick = null; @@ -4035,13 +4066,16 @@ async function main() { // billboard satisfy the loop while the point anchor was still missing. for (let attempt = 0; entityAnchor && attempt < 8 && !selectedPointPick; attempt += 1) { const picks = viewer.scene.drillPick(entityAnchor, 16) || []; - selectedNativePick = picks.find((picked) => picked?.id === selectedEntity); + selectedNativePick = picks.find((picked) => ( + picked?.primitive === selectedDrawn.dot.primitive + || picked?.primitive === selectedDrawn.bracket?.primitive + )); selectedPointPick = picks.find((picked) => ( - picked?.id === selectedEntity + picked?.primitive === selectedDrawn.dot.primitive && String(picked?.primitive?.constructor?.name || '').includes('PointPrimitive') )); selectedBillboardPick = picks.find((picked) => ( - picked?.id === selectedEntity + picked?.primitive === selectedDrawn.bracket?.primitive && String(picked?.primitive?.constructor?.name || '').includes('Billboard') )); if (!selectedPointPick) { @@ -4054,18 +4088,15 @@ async function main() { }); } } - const selectedPointDistance = selectedEntity?.point?.distanceDisplayCondition?.getValue?.(); + const selectedPointDistance = selectedDrawn?.dot.primitive.distanceDisplayCondition; return { rect, selectedNativePickable: Boolean(selectedNativePick), selectedPointPickable: Boolean(selectedPointPick), selectedBillboardPickable: Boolean(selectedBillboardPick), selectedPointMaxDistance: selectedPointDistance?.far ?? null, - selectedEntityShow: selectedEntity?.show, - selectedBracketVisible: Boolean( - selectedEntity?.billboard - && selectedEntity.billboard.show?.getValue?.() !== false - ), + selectedEntityShow: selectedDrawn?.show, + selectedBracketVisible: Boolean(selectedDrawn?.bracket?.show), entityAnchor: entityAnchor ? { x: entityAnchor.x, y: entityAnchor.y } : null, entityDistance: entityPosition ? Math.hypot( @@ -4222,7 +4253,7 @@ async function main() { id: 'qa:flights:radio-recenter-stage-owner', position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = 'flights:qa-radio-recenter-stage-owner'; + window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-radio-recenter-stage-owner'; viewer.trackedEntity = owner; completeFlight(0); const trackingBetweenStagesCalls = calls.length; diff --git a/scripts/qa-sky-model-lighting.mjs b/scripts/qa-sky-model-lighting.mjs index 2f401506bf..6352a3be96 100644 --- a/scripts/qa-sky-model-lighting.mjs +++ b/scripts/qa-sky-model-lighting.mjs @@ -32,13 +32,15 @@ try { const results = await page.evaluate(async () => { window.CESIUM_BASE_URL = '/cesium/'; // Use StarrySky's exact Vite dependency URL, including its version query. - const source = await fetch('/src/sky/starrySky.js').then((r) => r.text()); + const source = await fetch('/src/render/cesium/starrySky.js').then((r) => + r.text(), + ); const cesiumUrl = source.match( /from ["']([^"']*\/cesium\.js[^"']*)["']/, )?.[1]; if (!cesiumUrl) throw new Error('run against the Vite dev server'); const C = await import(cesiumUrl); - const { StarrySky } = await import('/src/sky/starrySky.js'); + const { StarrySky } = await import('/src/render/cesium/starrySky.js'); const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z'); const results = {}; for (const kind of ['black', 'starry', 'white']) { @@ -75,7 +77,7 @@ try { } const position = C.Cartesian3.fromDegrees(0, 0, 10000); const model = await C.Model.fromGltfAsync({ - url: '/models/airplane.glb', + url: '/models/fleet/aircraft/a320.glb', modelMatrix: C.Transforms.eastNorthUpToFixedFrame(position), }); scene.primitives.add(model); diff --git a/scripts/qa-sprites-b5.mjs b/scripts/qa-sprites-b5.mjs index 7e5b824c0b..190a0c6513 100644 --- a/scripts/qa-sprites-b5.mjs +++ b/scripts/qa-sprites-b5.mjs @@ -15,9 +15,9 @@ * per-class glyph (image data-URI === aircraftIcon(klass), * imported from src) and per-class scale (flights: * CLASS_SCALE_2D; military: 0.7 × CLASS_SCALE_2D) - * B3 models : with 3D on, fleet Cesium.Model.scale === the layer's - * MODEL_SCALE (both 1; legacy scale is baked into the GLB) - * × CLASS_SCALE_3D[klass] per icao; tracked too + * B3 models : with 3D on, fleet Cesium.Model.scale === the life-size + * scale of the fleet model the aircraft's type or category + * selects (aircraftModelSpec) per icao; tracked too * B4 clean : no console errors * * Visual output (qa-shots/b5/, untracked): top-down 2D spreads of both rows, @@ -33,15 +33,18 @@ import fs from 'node:fs'; import path from 'node:path'; import puppeteer from 'puppeteer'; import { stubPlanespotters } from './qa-photo-stub.mjs'; -import { classifyAircraft, CLASS_SCALE_2D, CLASS_SCALE_3D, CLASS_MODEL_REAL } from '../src/data/aircraftClass.js'; -// Hangar fleet (2026-08-16): real per-class GLBs render at scale 1; military -// heavies (airliner/quadjet/glider) render airplane.glb at 1 x class; only -// fastjet/unknown keep the per-layer jet/airplane MODEL_SCALE formula. -const flightsWantScale = (klass) => (CLASS_MODEL_REAL[klass] ? 1 : FL_MODEL_SCALE * CLASS_SCALE_3D[klass]); -const MIL_PLANE_CLASSES = new Set(['airliner', 'quadjet', 'glider']); -const militaryWantScale = (klass) => (CLASS_MODEL_REAL[klass] ? 1 - : MIL_PLANE_CLASSES.has(klass) ? MIL_PLANE_MODEL_SCALE * CLASS_SCALE_3D[klass] - : MIL_MODEL_SCALE * CLASS_SCALE_3D[klass]); +import { classifyAircraft, CLASS_SCALE_2D } from '../src/data/aircraftClass.js'; +import { aircraftModelSpec } from '../src/data/fleetModels.js'; +// Every aircraft draws its fleet model life size: its type's length over the +// model's built length, chosen by type code (military) or category (flights). +const FLEET_SET = Object.freeze({ + catalog: JSON.parse(fs.readFileSync(new URL('../public/models/fleet/catalog.json', import.meta.url), 'utf8')), + types: JSON.parse(fs.readFileSync(new URL('../public/models/fleet/types.json', import.meta.url), 'utf8')), +}); +const flightsWantScale = (icao) => + aircraftModelSpec(FLEET_SET, { category: SPRITES.flights.find((p) => p.icao === icao)?.category }).scale; +const militaryWantScale = (hex) => + aircraftModelSpec(FLEET_SET, { typeCode: SPRITES.military.find((p) => p.hex === hex)?.t }).scale; import { aircraftIcon } from '../src/data/aircraftIcons.js'; // --------------------------------------------------------------------------- @@ -58,9 +61,6 @@ const APP_URL = getOpt('--url', 'http://localhost:4173'); const HEADFUL = getFlag('--headful'); const SHOT_DIR = path.resolve('qa-shots/b5'); -const FL_MODEL_SCALE = 1; // flights.js (airplane.glb is transform-applied and meter-scale) -const MIL_PLANE_MODEL_SCALE = 1; // military heavy classes share the same baked airplane.glb -const MIL_MODEL_SCALE = 1; // militaryFlights.js (jet.glb is already real-world scale, native radius ~29.8 m) const MIL_BILLBOARD_SCALE = 0.7; // militaryFlights BILLBOARD_SCALE const CHROME_EXECUTABLE_CANDIDATES = [ @@ -134,10 +134,9 @@ const SPRITES = { // course 0 like the rest — keeps the row a clean size-comparison line (2D // rotation is demoed by caa004 and gated by qa-heading-b3 anyway). { hex: 'dda008', flight: 'ML-FJ', t: 'F16', lon0: ROW_LON0 + 7 * ROW_STEP_DEG, lat0: 30.28, courseDeg: 0, speedMps: 80, altFt: 15000 }, - // 3D cluster: C17 vs F16 (tracked) vs B744 vs C130. jet.glb is a - // real-world-scale asset (native bounding radius ~29.8) rendered at - // MODEL_SCALE 1, so models are ~22–43 m radius — same 150 m spacing and - // 450–900 m shot ranges as the flights cluster. + // 3D cluster: C17 vs F16 (tracked) vs B744 vs C130, each drawn life size + // (~8–36 m radius) — same 150 m spacing and 450–900 m shot ranges as the + // flights cluster. { hex: 'ddb001', flight: '3DMWID', t: 'C17', lon0: CLUSTER_LON0 - mDegLon(150, 30.05), lat0: 30.05, courseDeg: 0, speedMps: 60, altFt: 12000 }, { hex: 'ddb002', flight: '3DMFJ', t: 'F16', lon0: CLUSTER_LON0, lat0: 30.05, courseDeg: 0, speedMps: 60, altFt: 12000 }, { hex: 'ddb003', flight: '3DMQUA', t: 'B744', lon0: CLUSTER_LON0 + mDegLon(150, 30.05), lat0: 30.05, courseDeg: 0, speedMps: 60, altFt: 12000 }, @@ -464,7 +463,7 @@ async function main() { // ======================================================================== // B3 + 3D screenshots — flights cluster // ======================================================================== - console.log('\n3D — flights cluster (airplane.glb, per-class scale)'); + console.log('\n3D — flights cluster (fleet models, life size)'); await page.evaluate(() => { const dm = window.__godsEyeView.dataManager; dm.layers.get('flights').module.setParams({ models3d: true }); @@ -481,20 +480,20 @@ async function main() { const flModels = await page.evaluate(() => window.__collectModels().filter((m) => m.ready)); const modelScaleBad = []; for (const [id, want] of [ - ['cbb001', flightsWantScale(expectedFlights.get('cbb001'))], - ['cbb003', flightsWantScale(expectedFlights.get('cbb003'))], + ['cbb001', flightsWantScale('cbb001')], + ['cbb003', flightsWantScale('cbb003')], ]) { const m = flModels.find((x) => x.id === id); if (!m || Math.abs(m.scale - want) > 1e-9) modelScaleBad.push(`${id}: ${m ? m.scale : 'missing'} != ${want}`); } const trackedM = flModels.find((x) => x.id === 'cbb002'); - const trackedWant = flightsWantScale(expectedFlights.get('cbb002')); + const trackedWant = flightsWantScale('cbb002'); if (!trackedM || Math.abs(trackedM.scale - trackedWant) > 1e-9) { modelScaleBad.push(`tracked: ${trackedM ? trackedM.scale : 'missing'} != ${trackedWant}`); } - record('B3a flights: model scales match the per-class registry (all GLBs meter-scale; shared @1×class)', + record('B3a flights: model scales match each type's life-size fleet model', modelScaleBad.length === 0, - modelScaleBad.length ? modelScaleBad.join(' ') : 'all exact per registry'); + modelScaleBad.length ? modelScaleBad.join(' ') : 'all exact'); console.log(` world bounding radii (m): ${flModels.filter((m) => m.scale !== undefined).map((m) => `${m.id ?? 'tracked'}=${m.radius?.toFixed(1)}`).join(' ')}`); await sleep(1500); @@ -509,7 +508,7 @@ async function main() { // ======================================================================== // B3 + 3D screenshots — military cluster // ======================================================================== - console.log('\n3D — military cluster (jet.glb, per-class scale)'); + console.log('\n3D — military cluster (fleet models, life size)'); await page.evaluate(() => { const dm = window.__godsEyeView.dataManager; dm.layers.get('military').module.setParams({ models3d: true }); @@ -526,25 +525,25 @@ async function main() { const milModels = await page.evaluate(() => window.__collectModels().filter((m) => m.ready)); const modelScaleBad = []; for (const [id, want] of [ - ['ddb001', militaryWantScale(expectedMilitary.get('ddb001'))], - ['ddb003', militaryWantScale(expectedMilitary.get('ddb003'))], - ['ddb004', militaryWantScale(expectedMilitary.get('ddb004'))], + ['ddb001', militaryWantScale('ddb001')], + ['ddb003', militaryWantScale('ddb003')], + ['ddb004', militaryWantScale('ddb004')], ]) { const m = milModels.find((x) => x.id === id); if (!m || Math.abs(m.scale - want) > 1e-9) modelScaleBad.push(`${id}: ${m ? m.scale : 'missing'} != ${want}`); } const trackedM = milModels.find((x) => x.id === 'ddb002'); - const trackedWant = militaryWantScale(expectedMilitary.get('ddb002')); + const trackedWant = militaryWantScale('ddb002'); if (!trackedM || Math.abs(trackedM.scale - trackedWant) > 1e-9) { modelScaleBad.push(`tracked: ${trackedM ? trackedM.scale : 'missing'} != ${trackedWant}`); } - record('B3b military: model scales match the weight-class registry (real/heavy/jet assets @1×class)', + record('B3b military: model scales match each type's life-size fleet model', modelScaleBad.length === 0, - modelScaleBad.length ? modelScaleBad.join(' ') : 'all exact per registry'); + modelScaleBad.length ? modelScaleBad.join(' ') : 'all exact'); console.log(` world bounding radii (m): ${milModels.filter((m) => m.scale !== undefined).map((m) => `${m.id ?? 'tracked'}=${m.radius?.toFixed(1)}`).join(' ')}`); await sleep(1500); - // jet.glb at MODEL_SCALE 1 is real-world size — same shot ranges as the + // Fleet models are drawn life size — same shot ranges as the // flights cluster (close zoom no longer puts the camera inside a model). await zoomToRange(900); await page.screenshot({ path: path.join(SHOT_DIR, 'b5-3d-military-far.png') }); diff --git a/scripts/qa-street-level.mjs b/scripts/qa-street-level.mjs index 18616b4ceb..3dd0a3aa5f 100644 --- a/scripts/qa-street-level.mjs +++ b/scripts/qa-street-level.mjs @@ -378,7 +378,9 @@ const findPick = (page, prefix, { box = null, step = 3 } = {}) => }; for (let py = y; py < y + h; py += stride) for (let px = x; px < x + w; px += stride) { - const id = scene.pick({ x: px, y: py })?.id; + // A drawn item's pick id names its draw set and its own id. + const picked = scene.pick({ x: px, y: py })?.id; + const id = typeof picked === 'string' ? picked : picked?.id; if (typeof id === 'string' && id.startsWith(want)) return { x: rect.left + px, diff --git a/scripts/qa-stub-boot.mjs b/scripts/qa-stub-boot.mjs new file mode 100644 index 0000000000..a3a3292ac7 --- /dev/null +++ b/scripts/qa-stub-boot.mjs @@ -0,0 +1,427 @@ +#!/usr/bin/env node +/** + * Boot the whole application on the stub renderer with only the contract's + * required members (`dev/stub-app/main.js`), headless, and check that: + * + * - it starts, with no Cesium module requested at all (no script, no + * worker, no asset it would fetch; the one Cesium stylesheet the build's + * `vite-plugin-cesium` links into every page is reported, not failed); + * - the credits show in the application's own line, and its list opens + * with the data credits; + * - each data layer named below turns on, and off, without a page error or + * a console error (a feed's failed response is reported as the feed's, + * not failed: without network access or keys a feed answers with an + * error, and the layer must take that without one of its own; the dev + * server's client's own errors are reported as the tooling's); + * - with `--strict`, each of them draws on the stub: items in its draw sets, + * imagery added through the globe port, or a field (`draw.field`). + * + * The page is the application's own (`index.html`), served with the stub + * entry in place of `src/main.js`. Without `--url` it starts a Vite dev + * server of this checkout on `--port` (default 5290) and stops it after. + * Live feeds answer through the dev server's providers, so without network + * access or keys a layer turns on with nothing to draw: the run says so, + * and only `--strict` fails it. + * + * `--all-capabilities` gives the stub every capability instead, to see what + * the layers draw where a renderer has them all. + * + * npm run qa:stub-boot [-- --url http://127.0.0.1:5280] [--strict] + * [--settle-ms 20000] [--json path] [--all-capabilities] + */ +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import puppeteer from 'puppeteer'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** The data layers the stub must run, by catalog id. */ +export const STUB_BOOT_LAYERS = Object.freeze([ + 'flights', + 'military', + 'transit', + 'traffic', + 'cctv', + 'ais-live-vessels', + 'weather-radar', + 'weather-satellite', + 'wind', + 'satellites', + 'local-firms', + 'wildlife-sightings', + 'shipwrecks', + 'news', +]); + +/** A request that is Cesium: the package, its pre-bundle, or its assets. */ +export const isCesiumRequest = (url) => + /(?:^|[/._-])cesium(?:[/._-]|$)/i.test(new URL(url).pathname); + +/** The stylesheet `vite-plugin-cesium` links into every page it serves. */ +const isPluginStylesheet = (url, type) => + type === 'stylesheet' && + new URL(url).pathname === '/cesium/Widgets/widgets.css'; + +/** + * A browser's line for a feed's response that failed: one of the dev + * server's providers (`/api/`) or another origin's. The application's own + * modules and assets failing are the page's. + */ +const isFailedResponse = (text, at, base) => { + if (!/^Failed to load resource:/.test(text)) return false; + try { + const url = new URL(at); + return ( + url.origin !== new URL(base).origin || url.pathname.startsWith('/api/') + ); + } catch { + return false; + } +}; + +/** + * An error the dev server's own client logs (its socket to the server, which + * a headless browser can refuse): the tooling's, not the application's. + */ +const isDevClient = (at) => { + try { + return new URL(at).pathname === '/@vite/client'; + } catch { + return false; + } +}; + +function parseArgs(argv) { + const args = { strict: false, port: 5290, settleMs: 20_000 }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--strict') args.strict = true; + else if (arg === '--url') args.url = argv[++i]; + else if (arg === '--port') args.port = Number(argv[++i]); + else if (arg === '--settle-ms') args.settleMs = Number(argv[++i]); + else if (arg === '--json') args.json = argv[++i]; + else if (arg === '--all-capabilities') args.allCapabilities = true; + else throw new Error(`Unknown argument: ${arg}`); + } + return args; +} + +async function startViteServer(port) { + const { createServer } = await import('vite'); + const server = await createServer({ + root: ROOT, + configFile: path.join(ROOT, 'vite.config.js'), + // No hot reload: the page is loaded once and nothing edits it. + server: { port, strictPort: true, host: '127.0.0.1', hmr: false }, + logLevel: 'warn', + }); + await server.listen(); + return server; +} + +/** + * In the page: what the stub renderer draws now, its draw sets with how many + * items each holds and the globe port's imagery layers, and how many calls + * it has had on each port member. + */ +function readDrawn() { + const renderer = window.__stubBoot?.renderers?.[0]; + if (!renderer) return null; + const testing = renderer.testing; + const calls = {}; + for (const call of testing.calls) { + const key = `${call.port}.${call.member}`; + calls[key] = (calls[key] ?? 0) + 1; + } + return { + sets: Object.fromEntries( + testing.sets().map((id) => [id, testing.setRecord(id)?.items?.size ?? 0]), + ), + imagery: renderer.globe.imagery.list().length, + calls, + }; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const server = args.url ? null : await startViteServer(args.port); + try { + await run(args); + } finally { + await server?.close(); + } +} + +async function run(args) { + const base = (args.url ?? `http://127.0.0.1:${args.port}`).replace(/\/$/, ''); + const browser = await puppeteer.launch({ + headless: true, + executablePath: + process.env.PUPPETEER_EXECUTABLE_PATH || + (await puppeteer.executablePath()), + defaultViewport: { width: 1280, height: 800 }, + protocolTimeout: 300_000, + args: ['--no-sandbox'], + }); + /** Every error the page reports, in order: `page`, `console` or `response`. */ + const errors = []; + const cesiumRequests = []; + const cesiumStylesheets = []; + const report = { url: base, layers: {}, ok: false }; + try { + const page = await browser.newPage(); + page.on('console', (message) => { + if (message.type() !== 'error') return; + const text = message.text(); + const at = message.location()?.url ?? null; + errors.push({ + kind: isFailedResponse(text, at, base) + ? 'response' + : isDevClient(at) + ? 'tooling' + : 'console', + text, + at, + }); + }); + page.on('pageerror', (error) => + errors.push({ kind: 'page', text: String(error?.stack || error) }), + ); + await page.setRequestInterception(true); + page.on('request', async (request) => { + const url = request.url(); + if (url.startsWith(base) && isCesiumRequest(url)) + (isPluginStylesheet(url, request.resourceType()) + ? cesiumStylesheets + : cesiumRequests + ).push(url); + // The application's page, with the stub entry in place of its own. + if (request.isNavigationRequest() && url.startsWith(base)) { + const response = await fetch(url); + const html = (await response.text()).replace( + 'src="/src/main.js"', + 'src="/dev/stub-app/main.js"', + ); + if (!html.includes('/dev/stub-app/main.js')) + throw new Error('The page has no /src/main.js entry to replace'); + await request.respond({ + status: response.status, + contentType: 'text/html', + body: html, + }); + return; + } + await request.continue(); + }); + await page.goto( + `${base}/${args.allCapabilities ? '?capabilities=all' : ''}`, + { waitUntil: 'load', timeout: 180_000 }, + ); + await page.waitForFunction(() => window.__stubBoot, { timeout: 180_000 }); + const started = await page.evaluate(() => window.__stubBoot.started); + report.started = started; + if (!started.ok) throw new Error(`Startup failed: ${started.error}`); + await page.waitForFunction(() => window.__godsEyeView?.dataManager, { + timeout: 60_000, + }); + report.renderer = await page.evaluate(() => { + const renderer = window.__stubBoot.renderers[0]; + return { + id: renderer.id, + capabilities: [...renderer.capabilities], + canvasInPage: document.contains(renderer.canvas), + }; + }); + report.startupErrors = errors.slice(); + // The credits show in the application's own line, with no Cesium: the + // line is on screen and its list opens with the data credits in it. + report.credits = await page.evaluate(async () => { + const line = document.getElementById('gev-credits'); + const expand = line?.querySelector('.gev-credits-expand'); + const panel = document.getElementById('gev-credits-panel'); + const box = line?.getBoundingClientRect(); + const visible = + Boolean(box && box.width > 0 && box.height > 0) && + getComputedStyle(line).visibility !== 'hidden'; + expand?.click(); + await new Promise((resolve) => requestAnimationFrame(resolve)); + const listed = + panel?.hidden === false ? panel.querySelectorAll('li').length : 0; + expand?.click(); + return { visible, line: line?.textContent ?? null, listed }; + }); + console.log( + `credits: ${report.credits.visible ? 'shown' : 'NOT shown'}; line "${report.credits.line}"; ${report.credits.listed} listed`, + ); + const known = await page.evaluate(() => + window.__godsEyeView.dataManager.getAll().map((layer) => layer.id), + ); + report.missingLayers = STUB_BOOT_LAYERS.filter((id) => !known.includes(id)); + for (const id of STUB_BOOT_LAYERS) { + if (!known.includes(id)) continue; + const errorsBefore = errors.length; + const before = await page.evaluate(readDrawn); + const enabled = await page.evaluate( + (layerId) => + window.__godsEyeView.dataManager + .setEnabled(layerId, true, { origin: 'user' }) + .then( + // It can answer false rather than throw: on is what it says. + (value) => ({ + ok: + value !== false && + window.__godsEyeView.dataManager.isEnabled(layerId), + value: value ?? null, + }), + (error) => ({ ok: false, error: String(error?.stack || error) }), + ), + id, + ); + // Feeds load on their own schedule; keep ticking until they draw. + const deadline = Date.now() + args.settleMs; + let drawn = { sets: {}, imagery: 0, calls: {}, fields: 0 }; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 1_000)); + const now = await page.evaluate(readDrawn); + drawn = { + sets: Object.fromEntries( + Object.entries(now.sets).filter( + ([setId, items]) => items > 0 && before.sets[setId] !== items, + ), + ), + imagery: Math.max(0, now.imagery - before.imagery), + calls: Object.fromEntries( + Object.entries(now.calls) + .map(([key, n]) => [key, n - (before.calls[key] ?? 0)]) + .filter(([, n]) => n > 0), + ), + }; + drawn.fields = drawn.calls['draw.field'] ?? 0; + if (Object.keys(drawn.sets).length || drawn.imagery || drawn.fields) + break; + } + const stats = await page.evaluate((layerId) => { + const row = window.__godsEyeView.dataManager + .getAll() + .find((layer) => layer.id === layerId); + return { + enabled: row?.enabled ?? null, + count: row?.stats?.count ?? null, + error: row?.stats?.error ?? null, + source: row?.stats?.source ?? null, + }; + }, id); + const disabled = await page.evaluate( + (layerId) => + window.__godsEyeView.dataManager + .setEnabled(layerId, false, { origin: 'user' }) + .then( + (value) => ({ + ok: + value !== false && + !window.__godsEyeView.dataManager.isEnabled(layerId), + }), + (error) => ({ ok: false, error: String(error?.stack || error) }), + ), + id, + ); + const layerErrors = errors.slice(errorsBefore); + report.layers[id] = { + enabled, + disabled, + stats, + drawn, + errors: layerErrors.filter( + (error) => error.kind === 'page' || error.kind === 'console', + ), + failedResponses: layerErrors + .filter((error) => error.kind === 'response') + .map((error) => error.at), + }; + const what = [ + ...Object.entries(drawn.sets).map(([setId, n]) => `${setId}=${n}`), + ...(drawn.imagery ? [`${drawn.imagery} imagery layer(s)`] : []), + ...(drawn.fields ? [`${drawn.fields} field(s)`] : []), + ]; + console.log( + `${id}: ${enabled.ok && disabled.ok ? 'ran' : 'FAILED'}; drew ${ + what.length ? what.join(', ') : 'nothing' + }${stats.error ? `; feed: ${stats.error}` : ''}${ + report.layers[id].failedResponses.length + ? `; ${report.layers[id].failedResponses.length} failed response(s)` + : '' + }`, + ); + } + report.ok = true; + } catch (error) { + // Reported with the rest below, so the report and errors are kept. + report.failure = String(error?.stack || error); + } finally { + report.cesiumRequests = cesiumRequests; + report.cesiumStylesheets = cesiumStylesheets; + report.errors = errors; + await browser.close(); + } + const pageErrors = errors.filter((error) => error.kind === 'page'); + const consoleErrors = errors.filter((error) => error.kind === 'console'); + const failedResponses = errors.filter((error) => error.kind === 'response'); + const toolingErrors = errors.filter((error) => error.kind === 'tooling'); + const problems = []; + if (report.failure) problems.push(`the run stopped: ${report.failure}`); + if (!report.started?.ok) problems.push('the application did not start'); + if (!report.renderer?.canvasInPage) + problems.push("the stub's canvas is not in the page"); + if ( + report.started?.ok && + (!report.credits?.visible || !report.credits.listed) + ) + problems.push('the credits line is not shown, or its list is empty'); + if (cesiumRequests.length) + problems.push(`Cesium was requested: ${cesiumRequests.join(', ')}`); + if (pageErrors.length) problems.push(`${pageErrors.length} page error(s)`); + if (consoleErrors.length) + problems.push(`${consoleErrors.length} console error(s)`); + if (report.missingLayers?.length) + problems.push(`layers not in the catalog: ${report.missingLayers}`); + for (const [id, layer] of Object.entries(report.layers)) { + if (!layer.enabled.ok || !layer.disabled.ok) + problems.push(`${id} failed to turn on or off`); + if ( + args.strict && + !Object.keys(layer.drawn.sets).length && + !layer.drawn.imagery && + !layer.drawn.fields + ) + problems.push(`${id} drew nothing`); + } + report.problems = problems; + if (args.json) writeFileSync(args.json, JSON.stringify(report, null, 2)); + for (const error of [...pageErrors, ...consoleErrors]) + console.error(`${error.kind} error: ${error.text} (${error.at ?? '?'})`); + if (cesiumStylesheets.length) + console.log( + `note: the build's Cesium plugin linked ${cesiumStylesheets.join(', ')}`, + ); + if (toolingErrors.length) + console.log( + `note: the dev server's client logged ${toolingErrors.length} error(s): ${[ + ...new Set(toolingErrors.map((error) => error.text)), + ].join(' | ')}`, + ); + if (failedResponses.length) + console.log( + `note: ${failedResponses.length} feed response(s) failed (keys or network)`, + ); + if (problems.length) { + console.error(`FAIL: ${problems.join('; ')}`); + process.exitCode = 1; + } else console.log('ok: the application runs on the stub renderer'); +} + +if (import.meta.url === `file://${process.argv[1]}`) + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); diff --git a/scripts/qa-terrain-429.mjs b/scripts/qa-terrain-429.mjs index 8164e34b5b..8db513d2c2 100644 --- a/scripts/qa-terrain-429.mjs +++ b/scripts/qa-terrain-429.mjs @@ -8,7 +8,7 @@ * answers HTTP 429 for most of them. This harness drives that burst, counts the * throttled responses, keeps the first 429's headers as evidence, and then * checks whether every throttled tile eventually loaded — the contract the - * client-side retry in `src/maps/terrain.js` provides. + * client-side retry in `src/render/cesium/mapTerrain.js` provides. * * Run against a keyless dev server (no Google or ion credentials): * env -u GOOGLE_MAPS_API_KEY -u CESIUM_ION_TOKEN npm run dev -- --port 4180 diff --git a/scripts/qa-traffic-baseline.mjs b/scripts/qa-traffic-baseline.mjs index 7059bf4381..57b1bea875 100644 --- a/scripts/qa-traffic-baseline.mjs +++ b/scripts/qa-traffic-baseline.mjs @@ -8,13 +8,16 @@ * 1. exact-viewport revisit (traffic module's full-road cache), * 2. adjacent 0.4–2 km pan (new exact bbox with heavy spatial overlap), * 3. cold city (no traffic-module entry for that city), - * 4. degraded upstream (synthetic delay on `/api/overpass` only). + * 4. degraded upstream (synthetic delay on the road requests: OpenFreeMap's + * host, which only traffic reads in this capture, or the Overpass proxy). * - * The proxy's actual `X-Overpass-Cache` result is printed for every network - * pass, so HIT/DISK/MISS/STALE/INFLIGHT is evidence rather than inference. - * The degraded leg delays request release in Puppeteer; it exercises the same - * fetch-start→response boundary without adding a failure switch to the - * application or proxy. Pass `--degraded-delay-ms 0` to skip that leg. + * Keyless roads come from OpenFreeMap vector tiles (`tiles.openfreemap.org`); + * a build that still reads them through the Overpass proxy has its + * `X-Overpass-Cache` result printed for every network pass, so + * HIT/DISK/MISS/STALE/INFLIGHT is evidence rather than inference ("—" for + * tiles). The degraded leg delays the road requests' release in Puppeteer; + * it exercises the same fetch-start→response boundary without adding a + * failure switch to the application or proxy. Pass `--degraded-delay-ms 0` to skip that leg. * TomTom status is intercepted as keyless so no live-flow key is required and * the capture isolates the OSM road-to-visible-dot chain. * @@ -93,9 +96,42 @@ function debugUrl(rawUrl) { return url.toString(); } -/** Position the camera and explicitly raise the boundaries the layer observes. */ +/** + * Let the camera report a move the way a user's does: traffic hears the + * camera port's `changed` at its own 5% threshold (layers/traffic/policy.js + * CAMERA_CHANGED_THRESHOLD), which the port measures on every scene tick + * (the first measurement after a listener subscribes only records its + * baseline pose). Waiting for two drawn frames after the move is the sync + * point that the port has measured it. Cesium's own moveEnd (500 ms after + * stillness) is left to Cesium, as in the app; traffic re-checks the view + * on it. Installed in the page as `window.__qaRenderAfterMove`; throws when + * the frames do not draw within 5 s. + */ +function installRenderAfterMove() { + window.__qaRenderAfterMove = (gev) => new Promise((resolve, reject) => { + const scene = gev.viewer.scene; + let frames = 0; + let remove = null; + const timer = setTimeout(() => { + remove(); + reject(new Error(`the camera move rendered ${frames} frame(s) in 5 s`)); + }, 5000); + remove = scene.postRender.addEventListener(() => { + if (++frames >= 2) { + clearTimeout(timer); + remove(); + resolve(frames); + return; + } + scene.requestRender(); + }); + scene.requestRender(); + }); +} + +/** Position the camera and render, so the layer hears the move as it would a user's. */ async function moveCamera(page, view) { - return page.evaluate((v) => { + return page.evaluate(async (v) => { const gev = window.__godsEyeView; const module = gev.dataManager.layers.get('traffic').module; const beforeLastUpdate = module.getStats().lastUpdate; @@ -115,12 +151,7 @@ async function moveCamera(page, view) { roll: 0, }, }); - // setView normally propagates through Cesium's render loop. Raising these - // explicitly makes the capture boundary deterministic across GPU speeds. - // Pairing still flows through camera.changed's schedule-time anchor; the - // synthetic moveEnd is emitted only as the same diagnostic used naturally. - gev.viewer.camera.changed.raiseEvent(); - gev.viewer.camera.moveEnd.raiseEvent(); + await window.__qaRenderAfterMove(gev); return { beforeLastUpdate, boundaryTime }; }, view); } @@ -159,14 +190,29 @@ function readTrafficMeasures(page, boundaryTime) { })), boundaryTime); } +/** + * Road requests the page sent, counted by the request interceptor: `sent` is + * every road request that reached the network, `delayed` those it held for + * the degraded leg. `requestRoads()` can be answered from decoded tiles + * already in memory, so a `fetch-to-response` measure alone does not prove + * the network was used. + */ +const roadRequests = { sent: 0, delayed: 0 }; + /** Drive one measured state and return its raw User Timing measures. */ async function captureState(page, name, view, setDelay) { setDelay(name === 'degraded-upstream' ? DEGRADED_DELAY_MS : 0); + const before = { ...roadRequests }; const { beforeLastUpdate, boundaryTime } = await moveCamera(page, view); await waitForTrafficCapture(page, beforeLastUpdate, boundaryTime); const measures = await readTrafficMeasures(page, boundaryTime); setDelay(0); - return { name, measures }; + return { + name, + measures, + sent: roadRequests.sent - before.sent, + delayed: roadRequests.delayed - before.delayed, + }; } /** Format a duration without hiding zero-duration measurements. */ @@ -318,13 +364,14 @@ async function main() { const page = await browser.newPage(); await page.setViewport({ width: 1440, height: 900 }); await page.evaluateOnNewDocument(() => localStorage.clear()); + await page.evaluateOnNewDocument(installRenderAfterMove); page.on('console', (message) => { if (message.type() === 'error') consoleErrors.push(message.text()); }); page.on('pageerror', (error) => consoleErrors.push(error.message)); - // Force keyless traffic and optionally hold Overpass requests to model a - // degraded proxy/upstream. No server key or proxy debug endpoint is needed. + // Force keyless traffic and optionally hold the road requests to model a + // degraded upstream. No server key or proxy debug endpoint is needed. await page.setRequestInterception(true); page.on('request', async (request) => { if (request.url().includes('/api/tomtom/status')) { @@ -335,7 +382,11 @@ async function main() { }); return; } - if (activeProxyDelayMs > 0 && request.url().includes('/api/overpass')) { + const roadRequest = request.url().includes('/api/overpass') + || new URL(request.url()).hostname === 'tiles.openfreemap.org'; + if (roadRequest) roadRequests.sent += 1; + if (activeProxyDelayMs > 0 && roadRequest) { + roadRequests.delayed += 1; await sleep(activeProxyDelayMs); } try { await request.continue(); } catch { /* page closed or already handled */ } @@ -363,8 +414,9 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); await gev.dataManager.setEnabled('traffic', true); - gev.viewer.camera.changed.raiseEvent(); - gev.viewer.camera.moveEnd.raiseEvent(); + // Also records the baseline pose traffic's new `changed` listener + // measures the first measured move against. + await window.__qaRenderAfterMove(gev); }, VIEWS.austin); await sleep(500); @@ -386,7 +438,7 @@ async function main() { // Clear the last-bounds gate without clearing the module's road cache, then // revisit the byte-identical camera pose for a true client-cache hit. - await page.evaluate((view) => { + await page.evaluate(async (view) => { const gev = window.__godsEyeView; const ellipsoid = gev.viewer.scene.globe.ellipsoid; const radians = Math.PI / 180; @@ -398,8 +450,7 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - gev.viewer.camera.changed.raiseEvent(); - gev.viewer.camera.moveEnd.raiseEvent(); + await window.__qaRenderAfterMove(gev); }, VIEWS.austin); await sleep(500); @@ -428,7 +479,7 @@ async function main() { } for (const capture of captures.slice(1)) { if (!capture.measures.some((entry) => entry.detail?.segment === 'fetch-to-response')) { - throw new Error(`${capture.name} did not issue an Overpass request`); + throw new Error(`${capture.name} did not issue a road request`); } } if (DEGRADED_DELAY_MS > 0) { @@ -438,20 +489,35 @@ async function main() { && entry.duration >= DEGRADED_DELAY_MS * 0.9 )); if (!delayed) throw new Error('degraded-upstream leg did not observe the synthetic delay'); + // The delay has to come from held road requests, not from processing + // that happened to run long. + if (!degraded.delayed) throw new Error('degraded-upstream leg sent no road request to hold'); } + // A city the client has never seen has no tiles in memory: it must reach + // the network. The other legs may legitimately be answered from tiles + // already decoded, so their counts are reported, not asserted. + const cold = captures.find((capture) => capture.name === 'cold city (client)'); + if (!cold?.sent) throw new Error('cold city leg sent no road request to the network'); const rows = captures.flatMap(rowsForCapture); if (!rows.length) throw new Error('no measured traffic renders were captured'); console.log('\nCausal segments (one row per visible major/full pass)'); console.table(rows); + console.log('\nRoad requests sent to the network per leg (held by the degraded leg)'); + console.table(captures.map((capture) => ({ + State: capture.name, + Sent: capture.sent, + Held: capture.delayed, + }))); console.log('\nNotes:'); console.log(' - Render→postRender is the first visible-frame boundary used by Phase 0.'); - console.log(' - Proxy cache is read from X-Overpass-Cache; “—” means the client cache avoided fetch.'); - console.log(' - response.json includes both body transfer and JSON decoding; the production path does not split them.'); - console.log(' - Last change→fetch is approximately the 320 ms FETCH_DEBOUNCE for the first fetch by construction.'); + console.log(' - Proxy cache is read from X-Overpass-Cache; “—” means the client cache avoided fetch, or the roads came from OpenFreeMap tiles.'); + console.log(' - Through the Overpass proxy, Fetch→response is the HTTP response and response.json is body transfer plus JSON decoding.'); + console.log(' - From OpenFreeMap tiles, Fetch→response spans the tile requests, body reads, decoding and composition, and response.json only hands back the built object; a held leg can stack the delay over tiles fetched in turn.'); + console.log(' - Last change→fetch is the 320 ms FETCH_DEBOUNCE for the first fetch by construction, plus timer and main-thread latency (larger under SwiftShader).'); console.log(' - Full-pass Last change→fetch also includes the intentionally sequential major pass.'); - console.log(' - Cesium moveEnd is a diagnostic raised ~500 ms after stillness, typically after fetch starts; fetch never waits for it.'); - console.log(' - Synthetic events bypass camera percentageChanged/inertia but use the same camera.changed schedule-time anchor as natural captures.'); + console.log(' - Cesium moveEnd is raised ~500 ms after stillness, typically after fetch starts; fetch never waits for it, and traffic only re-checks the view on it.'); + console.log(' - Moves are setView plus rendered frames: the camera port measures traffic\'s own 5% changed threshold as for a user move (inertia is bypassed).'); console.log(' - The keyless capture zeroes Flow race and Heat lines work; live-keyed numbers will differ.'); console.log(' - Measurement caveat: timings include instrumentation overhead (observer effect) and browser clock-floor quantization.'); console.log(' - Per-road clock observations inside road-parse-total/waypoint-materialization slightly overstate production work.'); diff --git a/scripts/qa-traffic-motion.mjs b/scripts/qa-traffic-motion.mjs index af73c8d1c2..b9c0f52d5a 100644 --- a/scripts/qa-traffic-motion.mjs +++ b/scripts/qa-traffic-motion.mjs @@ -158,9 +158,13 @@ try { (window.__motion.holdStart === null ? '' : ` | camera stopped +${((now - window.__motion.holdStart) / 1000).toFixed(1)}s`); + // A layer dot is its draw item (`pos`, hidden only when `show` is + // false); a collection's point is Cesium's. const visit = (id, roadId, point) => { - if (!point.show) return; - const s = scene.cartesianToCanvasCoordinates(point.position); + if (point.show === false) return; + const s = scene.cartesianToCanvasCoordinates( + point.pos ?? point.position, + ); if (s && s.x >= 0 && s.y >= 0 && s.x <= 1280 && s.y <= 800) points.set(id, { x: s.x, y: s.y, roadId }); }; @@ -168,7 +172,7 @@ try { offRoad = 0; if (!baseline && layer.visitMotionDots) { layer.visitMotionDots((id, roadId, point, road) => { - if (point.show) { + if (point.show !== false) { const p = road?.roadProperties; const allowed = road?.directFlow ? [ @@ -195,7 +199,7 @@ try { p?.brunnel !== 'tunnel'; if (!allowed) offRoad++; } - if (point.show) n++; + if (point.show !== false) n++; visit(id, roadId, point); }); } else { diff --git a/scripts/qa-traffic-oblique.mjs b/scripts/qa-traffic-oblique.mjs index 6ea1c953d5..a365bcd446 100644 --- a/scripts/qa-traffic-oblique.mjs +++ b/scripts/qa-traffic-oblique.mjs @@ -83,9 +83,10 @@ try { lower = 0; dataManager.layers .get('traffic') - .module.visitMotionDots((id, key, p) => { - if (!p.show) return; - const s = viewer.scene.cartesianToCanvasCoordinates(p.position); + .module.visitMotionDots((id, key, dot) => { + // A dot is its draw item: `pos`, hidden only when `show` is false. + if (dot.show === false) return; + const s = viewer.scene.cartesianToCanvasCoordinates(dot.pos); if (s && s.x >= 240 && s.x <= 1040 && s.y >= 0 && s.y <= 800) { if (s.y < 400) upper++; else lower++; @@ -197,8 +198,10 @@ try { const camera = viewer.camera.positionWC; dataManager.layers .get('traffic') - .module.visitMotionDots((id, key, p) => { - if (!p.show) return; + .module.visitMotionDots((id, key, dot) => { + // A dot is its draw item: `pos`, hidden only when `show` is false. + if (dot.show === false) return; + const p = { position: dot.pos }; const q = viewer.scene.cartesianToCanvasCoordinates(p.position); if (q && q.x >= 240 && q.x <= 1040 && q.y >= 0 && q.y <= 800) { if (q.y < 400) upper++; diff --git a/scripts/qa-transit-browser.mjs b/scripts/qa-transit-browser.mjs index 23925c7439..7b9f1ee449 100644 --- a/scripts/qa-transit-browser.mjs +++ b/scripts/qa-transit-browser.mjs @@ -177,6 +177,19 @@ export async function sampleTransitPixels(page, palette) { ]; const width = canvas.clientWidth; const height = canvas.clientHeight; + // The billboards the draw port drew for the layer's two sets, by + // vehicle key, with the collection drawing each. + const drawn = new Map(); + const setIds = layer._transitSetIdsForTest(); + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) { + const billboard = host.get(j); + if (typeof billboard?.id?.id === 'string') + drawn.set(billboard.id.id, { billboard, host }); + } + } const sprites = []; const footprints = []; const intersects = (a, b) => @@ -256,20 +269,26 @@ export async function sampleTransitPixels(page, palette) { }; for (const entry of state._vehicles.values()) { if (!entry.marker || entry.marker.show === false) continue; - const p = entry.marker.position; + const row = drawn.get(entry.key); + if (!row || row.billboard.show === false) { + skipped.push({ key: entry.key, reason: 'billboard not drawn' }); + continue; + } + const billboard = row.billboard; + const p = billboard.position; const clip = mul(proj, mul(view, [p.x, p.y, p.z, 1])); if (!(clip[3] > 0)) continue; - const screen = entry.marker.computeScreenSpacePosition?.(scene) || { + const screen = billboard.computeScreenSpacePosition?.(scene) || { x: ((clip[0] / clip[3]) * 0.5 + 0.5) * width, y: (1 - ((clip[1] / clip[3]) * 0.5 + 0.5)) * height, }; - const rect = entry.marker.constructor.getScreenSpaceBoundingBox?.( - entry.marker, + const rect = billboard.constructor.getScreenSpaceBoundingBox?.( + billboard, screen, ) || { x: screen.x - 16, y: screen.y - 16, width: 32, height: 32 }; const { x, y } = screenPoint(screen.x, screen.y); - const c = Math.abs(Math.cos(entry.marker.rotation || 0)), - sn = Math.abs(Math.sin(entry.marker.rotation || 0)); + const c = Math.abs(Math.cos(billboard.rotation || 0)), + sn = Math.abs(Math.sin(billboard.rotation || 0)); const w = rect.width * c + rect.height * sn, h = rect.height * c + rect.width * sn; const footprint = { x: x - w / 2, y: y - h / 2, w, h }; @@ -282,10 +301,7 @@ export async function sampleTransitPixels(page, palette) { rect.y + rect.height > height ) reason = 'billboard rectangle outside frame'; - if ( - entry.marker.color?.alpha < 0.95 || - entry.markerCollection?.show === false - ) + if (billboard.color?.alpha < 0.95 || row.host.show === false) reason = 'billboard not opaque/collection hidden'; const raster = rasters.get(entry.marker.image); if (!raster) reason = 'billboard alpha unavailable'; @@ -351,12 +367,12 @@ export async function sampleTransitPixels(page, palette) { bracketX: entry.detectContact?._candidateScreenX ?? screen.x, bracketY: entry.detectContact?._candidateScreenY ?? screen.y, raster, - rotation: entry.marker.rotation || 0, - halfW: Number.isFinite(entry.marker.width) - ? Math.ceil(entry.marker.width / 2) + 2 + rotation: billboard.rotation || 0, + halfW: Number.isFinite(billboard.width) + ? Math.ceil(billboard.width / 2) + 2 : 11, - halfH: Number.isFinite(entry.marker.height) - ? Math.ceil(entry.marker.height / 2) + 2 + halfH: Number.isFinite(billboard.height) + ? Math.ceil(billboard.height / 2) + 2 : 7, }); } @@ -658,12 +674,23 @@ export function readTransitFleetStyle({ key, resetSelection = false } = {}) { const entry = key ? state._vehicles.get(key) : [...state._vehicles.values()].find((e) => e.marker?.show); - return entry + // The billboard the draw port drew for it, in either of the layer's sets. + const scene = window.__godsEyeView.viewer.scene; + const setIds = layer._transitSetIdsForTest(); + let billboard = null; + for (let i = 0; entry && !billboard && i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === entry.key) billboard = host.get(j); + } + // An undrawn marker has no style to compare: no answer. + return entry && billboard ? { key: entry.key, selected: state._selectedKey === entry.key, - color: entry.marker.color.toCssColorString(), - width: entry.marker.width, + color: billboard.color.toCssColorString(), + width: billboard.width, image: entry.marker.image, } : null; diff --git a/scripts/qa-transit-recovery.mjs b/scripts/qa-transit-recovery.mjs index a54e812399..6d45e684b7 100644 --- a/scripts/qa-transit-recovery.mjs +++ b/scripts/qa-transit-recovery.mjs @@ -182,7 +182,8 @@ try { }); parts.rendering.sampleIdle(entry); parts.rendering.schedulePlayback(entry); - const V = entry.marker.position.constructor; + // Marker positions are plain records; the camera's eye is a Cartesian3. + const V = scene.camera.positionWC.constructor; const points = entry.trailSegments .filter((s) => s.toT <= entry.sample.displayT) .flatMap((s) => s.positions); diff --git a/scripts/qa-transit-scenes.mjs b/scripts/qa-transit-scenes.mjs index f325cb9f73..d75d235fdc 100644 --- a/scripts/qa-transit-scenes.mjs +++ b/scripts/qa-transit-scenes.mjs @@ -146,11 +146,7 @@ export async function runFleetBudgets({ // The retained delta is conservative: it includes concurrent page growth. const retained = await cdp.send('Runtime.getHeapUsage'); // Timing/upload acceptance runs without the allocation profiler attached. - const trace = await page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('transit') - .module._measureTransitFramesForTest(8000), - ); + const trace = await page.evaluate(measureTransitFrames, 8000); await page.evaluate(() => window.__godsEyeView.dataManager.layers .get('transit') @@ -166,11 +162,7 @@ export async function runFleetBudgets({ page, `${count} budget visibility before allocation trace`, ); - const allocationTrace = await page.evaluate(() => - window.__godsEyeView.dataManager.layers - .get('transit') - .module._measureTransitFramesForTest(6000), - ); + const allocationTrace = await page.evaluate(measureTransitFrames, 6000); const { profile } = await cdp.send('HeapProfiler.stopSampling'); const allocations = allocationTotals(profile); const retainedBytes = retained.usedSize - before.usedSize; @@ -361,13 +353,23 @@ export async function runBostonMatrix({ const modes = await page.evaluate(() => { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; + // The billboards the draw port drew for the markers, by key. + const scene = window.__godsEyeView.viewer.scene; + const setIds = layer._transitSetIdsForTest(); + const drawn = new Map(); + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + drawn.set(host.get(j)?.id?.id, host.get(j)); + } return [...layer._transitStateForTest()._vehicles.values()].map( (e) => ({ key: e.key, route: e.record.routeId, image: e.marker.image, - width: e.marker.width, - color: e.marker.color.toCssHexString(), + width: drawn.get(e.key)?.width ?? null, + color: drawn.get(e.key)?.color.toCssHexString() ?? null, }), ); }); @@ -418,15 +420,29 @@ export async function runBostonMatrix({ window.__godsEyeView.dataManager.layers.get('transit').module; layer._transitPartsForTest().selection.clearSelection(); const e = layer._transitStateForTest()._vehicles.get(key); + // The billboard the draw port drew for it: the last under its key, + // as the fleet sample above reads it (the fleet-models set draws + // one under the same key first). + const scene = window.__godsEyeView.viewer.scene; + const setIds = layer._transitSetIdsForTest(); + let drawn = null; + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === key) drawn = host.get(j); + } return { + drawn: Boolean(drawn), image: e.marker.image, - width: e.marker.width, - color: e.marker.color.toCssHexString(), + width: drawn?.width ?? null, + color: drawn?.color.toCssHexString() ?? null, }; }, target.key); check( `Boston ${background.name}/${look.name}/${target.route}: deselect restores fleet styling`, - restored.image === target.image && + restored.drawn && + restored.image === target.image && restored.width === target.width && restored.color === target.color, ); @@ -727,6 +743,15 @@ export async function runTrailVisibility({ bodyUploadMax = 0, frames = 0; const headCpu = []; + // The Cesium primitives drawing one of the trail's draw-port sets: one, + // or while a rebuild builds, the retiring one and its replacement. + const hostsOf = (set) => { + const hosts = []; + for (let i = 0; set && i < scene.primitives.length; i++) + if (scene.primitives.get(i).drawSetId === set.id) + hosts.push(scene.primitives.get(i)); + return hosts; + }; const wrap = (primitive, kind) => { if (!primitive || wrapped.has(primitive)) return; const update = primitive.update; @@ -767,8 +792,8 @@ export async function runTrailVisibility({ const pre = scene.preRender.addEventListener(() => { headBytes = bodyBytes = 0; const trail = parts.trails.diagnostics(); - wrap(trail?.body, 'body'); - wrap(trail?.headPrimitive || trail?.head?._polylineCollection, 'head'); + for (const host of hostsOf(trail?.body)) wrap(host, 'body'); + for (const host of hostsOf(trail?.headLines)) wrap(host, 'head'); }); const post = scene.postRender.addEventListener(() => { frames++; @@ -807,6 +832,26 @@ export async function runTrailVisibility({ const trail = parts.trails.diagnostics(); if (!entry || !trail) return { ...setup, present: 0, reason: 'selection disappeared' }; + // The Cesium primitives drawing one of the trail's draw-port sets: one, + // or while a rebuild builds, the retiring one and its replacement. + const hostsOf = (set) => { + const hosts = []; + for (let i = 0; set && i < scene.primitives.length; i++) + if (scene.primitives.get(i).drawSetId === set.id) + hosts.push(scene.primitives.get(i)); + return hosts; + }; + // Each part of a set's primitive, for readiness and height exclusion. + const partsOf = (set) => { + const out = []; + for (const host of hostsOf(set)) + for (let i = 0; i < host.length; i++) out.push(host.get(i)); + return out; + }; + // One host (no rebuild under way) whose parts have all built. + const drawnReady = (set) => + hostsOf(set).length === 1 && + partsOf(set).every((part) => part.ready !== false); const { setRate } = await import('/src/data/contactPlayback.js'); setRate(entry.track, 0, { wallNowMs: Date.now(), @@ -819,8 +864,8 @@ export async function runTrailVisibility({ app.tileset?.show !== false && app.tileset?.tilesLoaded === true && (scene.globe?.show === false || scene.globe?.tilesLoaded === true) && - trail.body?.ready === true && - (!trail.headPrimitive || trail.headPrimitive.ready === true); + drawnReady(trail.body) && + (!trail.headLines?.show || drawnReady(trail.headLines)); // Require sustained readiness after freezing playback, before projecting // onto the refined surface. Repeated captures still check pixel stability. const tilesReady = await new Promise((resolve) => { @@ -855,7 +900,18 @@ export async function runTrailVisibility({ if (points.length < 2) return { ...setup, present: 0, reason: 'no completed path' }; const C = scene.camera.positionCartographic.constructor; - const V = entry.marker.position.constructor; + // Marker positions are plain records; the camera's eye is a Cartesian3. + const V = scene.camera.positionWC.constructor; + // The billboard the draw port drew for the marker, seen through. + const setIds = layer._transitSetIdsForTest(); + const markerBillboards = []; + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === entry.key) + markerBillboards.push(host.get(j)); + } const lengths = [0]; for (let i = 1; i < points.length; i++) lengths.push(lengths.at(-1) + V.distance(points[i - 1], points[i])); @@ -875,10 +931,11 @@ export async function runTrailVisibility({ new V(), ); const cart = C.fromCartesian(p); - const height = scene.sampleHeight( - cart, - [entry.marker, trail.body, trail.headPrimitive].filter(Boolean), - ); + const height = scene.sampleHeight(cart, [ + ...markerBillboards, + ...partsOf(trail.body), + ...partsOf(trail.headLines), + ]); if (Number.isFinite(height)) cart.height = height; const surface = C.toCartesian(cart); const q = mul( @@ -943,13 +1000,12 @@ export async function runTrailVisibility({ }); const bodyShow = trail.body?.show, headShow = trail.head?.show, - headPrimitiveShow = trail.headPrimitive?.show, + headLinesShow = trail.headLines?.show, backingShow = trail.backing?.show; let showTrail = false; const applyVisibility = () => { if (trail.body) trail.body.show = showTrail && bodyShow; - if (trail.headPrimitive) - trail.headPrimitive.show = showTrail && headPrimitiveShow; + if (trail.headLines) trail.headLines.show = showTrail && headLinesShow; if (trail.head) trail.head.show = showTrail && headShow; if (trail.backing) trail.backing.show = showTrail && backingShow; }; @@ -966,13 +1022,13 @@ export async function runTrailVisibility({ const current = parts.trails.diagnostics(); captureReady &&= ready() && - current?.body === trail.body && - current?.headPrimitive === trail.headPrimitive; + current?.rebuilds === trail.rebuilds && + current?.headRebuilds === trail.headRebuilds; } } finally { removeVisibility(); if (trail.body) trail.body.show = bodyShow; - if (trail.headPrimitive) trail.headPrimitive.show = headPrimitiveShow; + if (trail.headLines) trail.headLines.show = headLinesShow; if (trail.head) trail.head.show = headShow; if (trail.backing) trail.backing.show = backingShow; await frame(); @@ -994,7 +1050,7 @@ export async function runTrailVisibility({ tilesReady: captureReady, elapsedDisplayMs: entry.sample.displayT - setup.startDisplayT, movedMetres: Math.abs(entry.sample.lat - setup.startLat) * 111320, - body: trail.body?.constructor.name, + body: hostsOf(trail.body)[0]?.constructor.name, headStrategy: trail.headStrategy || 'PolylineCollection', headRebuilds: trail.headRebuilds ?? null, }; @@ -1048,3 +1104,24 @@ export async function runTrailVisibility({ .selection.clearSelection(), ); } + +/** + * The transit frame probe over the bytes the renderer uploads for the + * layer's marker sets (the Cesium renderer's upload probe), in the page. + * @param {number} durationMs + */ +async function measureTransitFrames(durationMs) { + const { countDrawSetUploads } = + await import('/src/render/cesium/uploadProbe.js'); + const app = window.__godsEyeView; + const layer = app.dataManager.layers.get('transit').module; + const uploads = countDrawSetUploads( + app.viewer, + layer._transitSetIdsForTest(), + ); + try { + return await layer._measureTransitFramesForTest(durationMs, uploads); + } finally { + uploads.stop(); + } +} diff --git a/scripts/qa-transit.mjs b/scripts/qa-transit.mjs index 32bfb596a6..c73a0cafc6 100644 --- a/scripts/qa-transit.mjs +++ b/scripts/qa-transit.mjs @@ -98,7 +98,7 @@ const renderingSource = await readFile( ); const frameSource = renderingSource .split('function onPreRender()')[1] - .split('const occluder')[0]; + .split('const candidatePosition')[0]; check( 'frame pass does not scan the fleet or copy the moving set', !/_vehicles\.values|\[\.\.\.state\._moving\]/.test(frameSource), @@ -815,25 +815,38 @@ try { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; const state = layer._transitStateForTest(); - const entry = state._vehicles.get(key); + const scene = window.__godsEyeView.viewer.scene; + // The billboard the draw port drew for it, and the set drawing it. + const setIds = layer._transitSetIdsForTest(); + let billboard = null, + setId = null; + for (let i = 0; !billboard && i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (!setIds.includes(host?.drawSetId)) continue; + for (let j = 0; j < host.length; j++) + if (host.get(j)?.id?.id === key) { + billboard = host.get(j); + setId = host.drawSetId; + } + } + const set = layer._transitPartsForTest().rendering.setNameOf(setId); return { selected: state._selectedKey === key, - color: entry?.marker.color.toCssColorString(), - width: entry?.marker.width, + color: billboard?.color.toCssColorString(), + width: billboard?.width, pickOwner: (() => { - const p = window.__godsEyeView.viewer.scene.pick( - entry.marker.computeScreenSpacePosition( - window.__godsEyeView.viewer.scene, - ), - ); + const p = billboard + ? scene.pick(billboard.computeScreenSpacePosition(scene)) + : null; return { - id: typeof p?.id === 'string' ? p.id : null, - primitiveId: - typeof p?.primitive?.id === 'string' ? p.primitive.id : null, + id: typeof p?.id?.id === 'string' ? p.id.id : null, + set: typeof p?.id?.set === 'string' ? p.id.set : null, collection: - entry.markerCollection === state._animatedMarkers + set === 'moving' ? 'animated' - : 'stationary', + : set === 'still' + ? 'stationary' + : null, }; })(), }; @@ -1596,7 +1609,8 @@ try { key: entry.key, x, y, - pickKey: picked?.id ?? picked?.primitive?.id ?? null, + // A draw-port pick carries {set, id, meta}; the vehicle is its id. + pickKey: picked?.id?.id ?? picked?.id ?? picked?.primitive?.id ?? null, }; }); let anchor = null; @@ -1849,19 +1863,33 @@ try { await page.$eval(row, (element) => element.scrollIntoView({ block: 'center' }), ); + // The marker sets drawn while on, to look for after disable. + const markerSets = await page.evaluate(() => + window.__godsEyeView.dataManager.layers + .get('transit') + .module._transitSetIdsForTest(), + ); await page.click(`${row} .data-toggle-btn`); await page.waitForFunction( () => !window.__godsEyeView.dataManager.isEnabled('transit'), { timeout: 20_000 }, ); const afterDisable = transitRequests.length; - const teardown = await page.evaluate(() => { + const teardown = await page.evaluate((setIds) => { const layer = window.__godsEyeView.dataManager.layers.get('transit').module; const state = layer._transitStateForTest(); return { vehicles: state._vehicles.size, - primitives: - (state._markers?.length || 0) + (state._animatedMarkers?.length || 0), + // Billboards still drawn in the sets drawn while on. + primitives: (() => { + const scene = window.__godsEyeView.viewer.scene; + let count = 0; + for (let i = 0; i < scene.primitives.length; i++) { + const host = scene.primitives.get(i); + if (setIds.includes(host?.drawSetId)) count += host.length || 0; + } + return count; + })(), visible: state._visible.size, moving: state._moving.size, detect: state._detectCache, @@ -1873,12 +1901,12 @@ try { ], trailPending: layer._transitPartsForTest().trails.requestDiagnostics() .pending, - shown: state._markers ? state._markers.show : null, + shown: state._markersShown ?? null, inFlight: state._inFlight.size, activeFeeds: state._activeFeeds.size, holds: window.__godsEyeView.getRenderGovernorDiagnostics().holds, }; - }); + }, markerSets); check( 'disable leaves no vehicles and no point primitives', teardown.vehicles === 0 && diff --git a/scripts/qa-visual-effects.mjs b/scripts/qa-visual-effects.mjs index f3b9ab8bd3..3c96e66547 100644 --- a/scripts/qa-visual-effects.mjs +++ b/scripts/qa-visual-effects.mjs @@ -169,7 +169,7 @@ try { result.bloom.intensityPct === 98 && snapshot.bloom.intensity === 98 && manager._visualEffects.bloomIntensity === 98 && - manager._bloomStage.enabled + window.__godsEyeView.viewer.scene.postProcessStages.bloom.enabled ); }), ); @@ -183,7 +183,11 @@ try { result.sharpen.intensityPct === 61 && manager.getVisualState().sharpen.intensity === 61 && manager._visualEffects.sharpenIntensity === 0.61 && - Math.abs(manager._sharpenStage.uniforms.amount - 1.32) < 1e-9 + Math.abs( + window.__godsEyeView.viewer.scene.postProcessStages.getStageByName( + 'effects_sharpen', + ).uniforms.amount - 1.32, + ) < 1e-9 ); }), ); @@ -199,9 +203,10 @@ try { const manager = window.__godsEyeView.styleManager; const effects = manager._visualEffects; manager.setStyle('retro'); - const owned = [...Object.values(effects.stages), effects.sharpenStage]; - const collection = manager.viewer.scene.postProcessStages; - const previousBloom = effects.previousBloom; + const collection = window.__godsEyeView.viewer.scene.postProcessStages; + const owned = Object.keys(effects.stages).map((name) => + collection.getStageByName(`effects_style_${name}`), + ); const pending = manager.dispose(); const stoppedBeforeAwait = effects.stopped && @@ -210,12 +215,15 @@ try { await pending; return { stoppedBeforeAwait, - removed: owned.every((stage) => !collection.contains(stage)), - restored: - effects.bloomStage.enabled === previousBloom.enabled && - Object.entries(previousBloom.uniforms).every( - ([name, value]) => effects.bloomStage.uniforms[name] === value, + removed: + owned.every(Boolean) && + Object.keys(effects.stages).every( + (name) => !collection.getStageByName(`effects_style_${name}`), ), + // The renderer gives the scene's bloom back when it goes. + restored: + !collection.bloom.enabled && + !collection.getStageByName('effects_sharpen')?.enabled, }; }); check( @@ -223,7 +231,7 @@ try { teardown.stoppedBeforeAwait, ); check( - 'UI teardown removes owned stages and restores borrowed bloom', + 'UI teardown removes its styles and turns bloom and sharpen off', teardown.removed && teardown.restored, ); check( diff --git a/scripts/qa-visual-input.mjs b/scripts/qa-visual-input.mjs index 3c096acdc1..914476aeb3 100644 --- a/scripts/qa-visual-input.mjs +++ b/scripts/qa-visual-input.mjs @@ -150,7 +150,9 @@ try { manager._bloomSlider.focus(); return { value: Number(manager._bloomSlider.value), - contrast: manager._bloomStage.uniforms.contrast, + contrast: + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast, }; }); await page.keyboard.press('ArrowRight'); @@ -160,7 +162,8 @@ try { const manager = window.__godsEyeView.styleManager; return ( Number(manager._bloomSlider.value) > before.value && - manager._bloomStage.uniforms.contrast < before.contrast + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast < before.contrast ); }, displayBefore), ); @@ -267,13 +270,16 @@ try { const manager = window.__godsEyeView.styleManager; manager._displayBindings._detachDisplayControls(); const before = manager.bloomEnabled; - const contrast = manager._bloomStage.uniforms.contrast; + const contrast = + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast; manager._bloomBtn.click(); manager._bloomSlider.value = '15'; manager._bloomSlider.dispatchEvent(new Event('input', { bubbles: true })); return ( manager.bloomEnabled === before && - manager._bloomStage.uniforms.contrast === contrast + window.__godsEyeView.viewer.scene.postProcessStages.bloom.uniforms + .contrast === contrast ); }), ); diff --git a/scripts/qa-zoom-out-guard.mjs b/scripts/qa-zoom-out-guard.mjs index 770a4148d8..5faf70b9f0 100644 --- a/scripts/qa-zoom-out-guard.mjs +++ b/scripts/qa-zoom-out-guard.mjs @@ -36,7 +36,8 @@ try { ); const renderer = await page.evaluate(async () => { const C = await import('/node_modules/cesium/Build/Cesium/index.js'); - const { maxPitchForHeight } = await import('/src/app/zoomOutGuard.js'); + const { maxPitchForHeight } = + await import('/src/render/cesium/zoomOutGuard.js'); const { readCameraTargetFrame } = await import('/src/ui/cameraOrientationControls.js'); const viewer = window.__godsEyeView.viewer; @@ -86,7 +87,7 @@ try { }; viewer.camera.setView = (options) => { // Cesium itself also calls setView while processing touch movement. - if (new Error().stack.includes('/src/app/zoomOutGuard.js')) + if (new Error().stack.includes('/src/render/cesium/zoomOutGuard.js')) qa.guardWrites++; return original(options); }; diff --git a/scripts/record-camera-goldens.mjs b/scripts/record-camera-goldens.mjs new file mode 100644 index 0000000000..17f4131bc7 --- /dev/null +++ b/scripts/record-camera-goldens.mjs @@ -0,0 +1,28 @@ +#!/usr/bin/env node +// Writes the reference camera traces the conformance suite compares a +// renderer against: src/render/conformance/goldens/camera.json. Run it after +// a Cesium upgrade or a change to the camera scripts, and review the diff. +// +// node scripts/record-camera-goldens.mjs [--check] +// +// With --check it writes nothing and exits 1 when the file is out of date. +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { recordCameraGoldens } from '../src/render/cesium/cameraGoldens.js'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const OUT = path.join(ROOT, 'src/render/conformance/goldens/camera.json'); + +const text = `${JSON.stringify(await recordCameraGoldens(), null, 2)}\n`; +if (process.argv.includes('--check')) { + const current = fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8') : ''; + if (current !== text) { + console.error(`${path.relative(ROOT, OUT)} is out of date`); + process.exit(1); + } +} else { + fs.mkdirSync(path.dirname(OUT), { recursive: true }); + fs.writeFileSync(OUT, text); + console.log(`wrote ${path.relative(ROOT, OUT)}`); +} diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs index f872504301..4e163cd398 100644 --- a/scripts/track-regression.mjs +++ b/scripts/track-regression.mjs @@ -33,7 +33,8 @@ * moves the camera — it stays in the follow band). * 3. NO CROSS-LAYER — tracking military then commercial (and vice versa) * ORPHAN clears the FIRST layer (its getTrackedInfo()===null), - * via the per-layer viewer.trackedEntityChanged listener. + * via each layer's follow-changed listener (the follow + * service, data/followed.js: onFollowChanged). * 4. INIT CLEAN — app loads, all 12 layers present, no console errors, * [Detection] Initialized + [TrackedReadout] Initialized. * @@ -44,8 +45,8 @@ * M3. AGE-OUT RELEASE — when the tracked plane's fixes stop arriving * it stays tracked (STALE, then SIGNAL LOST) until * 10 min after its newest fix; then tracking clears - * and the camera is RELEASED IN PLACE: viewer.trackedEntity - * undefined, NO jump (owner decision 2026-07-02 — + * and the camera is RELEASED IN PLACE: the camera + * follows nothing (data/followed.js), NO jump (owner decision 2026-07-02 — * the old ~80 km overview flyTo is gone). * * And the landing-ghost polish (2026-07-02): a LOW+SLOW (landed) plane that @@ -74,11 +75,16 @@ * the TRACKED grounded plane gets the standalone tracked model too (the * owner's "tracked SWA143 at 0 kts showed a 2D billboard" case). * - * And arrival-rotation freshness (2026-07-03 ground-polish): camera.moveEnd - * forces a full rotation pass on the next frame (fly-to settles the - * pose-signature gate can eat), and a billboard flipping INTO view while the - * camera idles re-aims the same tick instead of wearing a stale nose for up - * to ROTATION_REFRESH_MS. Both layers. + * And arrival-rotation freshness (2026-07-03 ground-polish): the nose is right + * on the first settled frame after a camera move and on the first frame a + * hidden contact is shown again. Both layers. (The CPU rotation passes that + * once guaranteed it are gone: the icon sets turn every icon along its drawn + * course on the GPU each frame, so the group reads the drawn rows.) + * + * The probes read what the app draws through its own seams: what the camera + * follows through the follow service (data/followed.js), icons from the draw + * port's icon sets as the renderer holds them, models by their `{set, id}` + * pick ids. * * Run: npm run test:track (assumes dev server already up on :4173) * node scripts/track-regression.mjs @@ -97,9 +103,15 @@ import fs from 'node:fs'; import puppeteer from 'puppeteer'; import { respondToPlanespotters } from './qa-photo-stub.mjs'; import { arrivalAngleViolated, arrivalRotationPassed } from '../src/tooling/trackArrivalObservation.mjs'; -import { classifyAircraft, CLASS_SCALE_3D, CLASS_MODEL_REAL } from '../src/data/aircraftClass.js'; +import { aircraftModelSpec } from '../src/data/fleetModels.js'; import { ensureGeoidReady, geoidHeight } from '../src/data/geoid.js'; +/** The fleet model set the aircraft layers draw from, read from disk. */ +const FLEET_SET = Object.freeze({ + catalog: JSON.parse(fs.readFileSync(new URL('../public/models/fleet/catalog.json', import.meta.url), 'utf8')), + types: JSON.parse(fs.readFileSync(new URL('../public/models/fleet/types.json', import.meta.url), 'utf8')), +}); + // --------------------------------------------------------------------------- // Args // --------------------------------------------------------------------------- @@ -266,6 +278,98 @@ async function main() { try { const page = await browser.newPage(); await page.evaluateOnNewDocument((base) => { window.__gevQaSourceBase = base; }, SOURCE_BASE); + // What the camera follows, read through the app's follow service + // (data/followed.js) rather than Cesium's `trackedEntity`: the follow + // camera runs through the renderer's camera port, whose Cesium adapter + // tracks a hidden helper entity, and the tracked aircraft is no longer an + // entity at all. `__qaFollowed()` is null until the app is up (and the + // module loaded), so every wait that reads it simply keeps polling. + await page.evaluateOnNewDocument(() => { + window.__qaFollowed = () => { + // A probe that cannot read the follow service must not read as + // "follows nothing". + if (window.__qaFollowedError) throw new Error(`followed.js: ${window.__qaFollowedError}`); + return window.__qaFollowedOf?.(window.__godsEyeView?.viewer) ?? null; + }; + const timer = setInterval(() => { + if (!window.__godsEyeView?.viewer) return; + clearInterval(timer); + import(`${window.__gevQaSourceBase || '/src'}/data/followed.js`) + .then((module) => { window.__qaFollowedOf = module.followedOf; }) + .catch((error) => { window.__qaFollowedError = String(error?.message || error); }); + }, 100); + // A contact's id from a drawn model's pick id: the draw port's models + // carry `{set, id}`; older builds stamped the bare id. + window.__qaModelIcao = (model) => { + const id = model?.id; + if (id && typeof id === 'object') return id.id == null ? null : String(id.id); + return id == null ? null : String(id); + }; + // A contact's FLEET icon as the renderer draws it, shaped like the + // billboard the probes below were written against: `show`, `scale`, + // `color` (the row's colour with its alpha column applied; focus and + // limb recession, which the shader also folds in, are not), + // `disableDepthTestDistance` and `position` (where the last frame drew + // it). The draw port's icon sets draw on the GPU (one IconSetPrimitive + // per set, rows keyed by item id; before the draw port, one a layer + // drew itself); a set off the GPU draws Cesium + // billboards whose pick id is `{set, id}`. The tracked icon's own set + // (`-tracked-icon:`) is left out: the fleet icon is what these + // probes always read. + window.__qaFindIcon = (wanted) => { + const scene = window.__godsEyeView?.viewer?.scene; + if (!scene) return null; + const trackedSet = (setId) => typeof setId === 'string' && setId.includes('-tracked-icon:'); + let found = null; + const walk = (coll) => { + const n = coll.length; + for (let i = 0; i < n; i++) { + let p; + try { p = coll.get(i); } catch { continue; } + if (!p) continue; + if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } + if (p.set && typeof p.set.row === 'function' && typeof p.set.has === 'function') { + if (!p.set.has(wanted)) continue; + // A primitive a layer drew itself (before the draw port) names + // no set. + const setId = typeof p._pickObject === 'function' + ? p._pickObject(wanted, p.set, p)?.id?.set ?? null + : null; + if (trackedSet(setId)) continue; + const set = p.set; + const row = set.row(wanted); + const color = set.color(row); + color.alpha *= set.alpha(row); + // (A set without the column draws over depth by default.) + const depth = typeof set.depthTestDistance === 'function' + ? set.depthTestDistance(row) + : Number.POSITIVE_INFINITY; + found = { + id: wanted, + setId, + show: set.shown(row), + scale: set.scale(row), + color, + disableDepthTestDistance: depth >= 1e30 ? Number.POSITIVE_INFINITY : depth, + position: set.position(row, p._tau), + // Degrees clockwise from north: the course the last frame + // turned the icon along (its rotation is derived from it on + // the GPU each frame). + course: set.course(row, p._tau), + // Whether the row turns along that course at all (ICON_ROTATES + // in data/iconSet.js); one that does not is drawn upright. + rotates: (set.flags(row) & 2) !== 0, + }; + } else if (p.image !== undefined && p.alignedAxis !== undefined) { + const id = p.id && typeof p.id === 'object' ? p.id : { id: p.id }; + if (id.id === wanted && !trackedSet(id.set)) found = p; + } + } + }; + walk(scene.primitives); + return found; + }; + }); await page.setViewport({ width: 1280, height: 800 }); await page.setRequestInterception(true); page.on('request', (request) => { @@ -547,13 +651,13 @@ async function main() { // Independent GLB capability control. Product model absence cannot prove // that the browser backend is incapable: that is the condition this - // harness is meant to catch. Load the already-approved airplane asset + // harness is meant to catch. Load one of the shipped fleet models // directly through Cesium, outside the Flights/Military model pipelines, // then remove the control before exercising product behavior. const glbControlStarted = await evalPage(async () => { window.__qaGlbControl = null; window.__qaGlbControlError = null; - const asset = await fetch('/models/airplane.glb'); + const asset = await fetch('/models/fleet/aircraft/a320.glb'); const assetBytes = asset.ok ? (await asset.arrayBuffer()).byteLength : 0; if (!asset.ok || assetBytes === 0) { throw new Error(`GLB control asset unavailable: HTTP ${asset.status}`); @@ -564,7 +668,7 @@ async function main() { Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 9000), ); void Cesium.Model.fromGltfAsync({ - url: '/models/airplane.glb', + url: '/models/fleet/aircraft/a320.glb', modelMatrix, scale: 1, }).then((model) => { @@ -719,7 +823,7 @@ async function main() { const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.(); return manager?.isEnabled?.('flights') && tracked?.icao24 === 'aaa001' - && window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001'; + && window.__qaFollowed()?.key === 'flights:aaa001'; }, { timeout: 30000, polling: 100 }, ); @@ -730,7 +834,7 @@ async function main() { flightsEnabled: manager.isEnabled('flights'), trackedId: flights.getTrackedInfo()?.icao24 || null, durableId: flights.getParams()?.selectedFlightsTrackingId || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__qaFollowed()?.key || null, }; }); record( @@ -760,7 +864,7 @@ async function main() { const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.(); return manager?.isEnabled?.('flights') && tracked?.icao24 === 'aaa001' - && window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001'; + && window.__qaFollowed()?.key === 'flights:aaa001'; }, { timeout: 30000, polling: 100 }, ); @@ -771,7 +875,7 @@ async function main() { flightsEnabled: manager.isEnabled('flights'), trackedId: flights.getTrackedInfo()?.icao24 || null, durableId: flights.getParams()?.selectedFlightsTrackingId || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__qaFollowed()?.key || null, }; }); record( @@ -833,7 +937,7 @@ async function main() { const latchedShare = await evalPage(() => ({ tracked: window.__godsEyeView.dataManager.layers .get('flights').module.getTrackedInfo()?.icao24 || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__qaFollowed()?.key || null, })); record( 'share-v2: the pending subject latches on when it arrives on a later poll', @@ -1347,8 +1451,8 @@ async function main() { ); } - // NOTE: we do NOT manually reposition the camera. Tracking sets - // viewer.trackedEntity + a calibrated viewFrom, so the follow camera lands + // NOTE: we do NOT manually reposition the camera. Tracking follows the + // plane with a calibrated viewFrom, so the follow camera lands // in the few-km band (altitude*1.1+2500, clamped 3–30 km) — far below the // MODEL_ALT_CEIL_M = 800 km ceiling, so _modelRegimeActive() is true and the // standalone tracked model renders. That's the exact path the invariants @@ -1393,12 +1497,12 @@ async function main() { // report the neighbor's id even though the correct tracked model is up. const trackedInfo = fl.getTrackedInfo(); const exactPickModel = trackedInfo - ? pool.find((model) => String(model.id) === trackedInfo.icao24) + ? pool.find((model) => window.__qaModelIcao(model) === trackedInfo.icao24) : null; if (exactPickModel) return exactPickModel; - const ent = window.__godsEyeView.viewer.trackedEntity; + const followed = window.__qaFollowed(); let tracked = null; - if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition(); + if (typeof followed?.displayPosition === 'function') tracked = followed.displayPosition(); if (!tracked) return pool[0]; let best = null, bestD = Infinity; for (const m of pool) { @@ -1416,7 +1520,7 @@ async function main() { }; }); - // Track a synthetic commercial plane. Tracking sets viewer.trackedEntity + + // Track a synthetic commercial plane. Tracking follows it with a // viewFrom, so the follow camera lands in the few-km band and the standalone // 3D model renders (model regime active below the 800 km ceiling). const trackedIcao = SYNTH.flights[0].icao; @@ -1431,7 +1535,7 @@ async function main() { const ti = fl.getTrackedInfo(); if (!ti || ti.icao24 !== icao) return false; const found = window.__findTrackedModel ? window.__findTrackedModel() : null; - return !!(found && found.ready && found.show && String(found.id) === icao); + return !!(found && found.ready && found.show && window.__qaModelIcao(found) === icao); }, { timeout: 60000, polling: 250 }, trackedIcao).then(() => true).catch(() => false); record('3D: tracked commercial model becomes ready through the DISPLAY toggle', modelUp, modelUp ? `ready+shown id=${trackedIcao}` : 'tracked product model never became ready+shown'); @@ -1444,8 +1548,8 @@ async function main() { jitterResult = await sampleFrames(page, 30, (icao) => { const dm = window.__godsEyeView.dataManager; const fl = dm.layers.get('flights').module; - const ent = window.__godsEyeView.viewer.trackedEntity; - const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const followed = window.__qaFollowed(); + const disp = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null; const dets = fl.getDetectableObjects({ maxCount: 1000 }); const me = dets.find((d) => d.id === icao || d.id === (fl.getTrackedInfo() && fl.getTrackedInfo().callsign)); if (!disp || !me || !me.position) return null; @@ -1454,8 +1558,8 @@ async function main() { }, trackedIcao); console.log(' (3D model did not render under SwiftShader; testing the shared display-position contract directly)'); } else { - // Full check: independently transform airplane.glb's measured AABB centre - // through the actual 3D model matrix, then compare it with detection. + // Full check: independently transform the fleet model's visual centre + // (its origin) through the actual 3D model matrix, then compare it with detection. // glTF [x,y,z] → Cesium-local [x,-z,y]. The effective rendered // computedScale is separate from modelMatrix and includes any // minimumPixelSize enlargement, so include it just as the renderer does. @@ -1469,7 +1573,7 @@ async function main() { const scale = Number.isFinite(model.computedScale) ? model.computedScale : (Number.isFinite(model.scale) ? model.scale : 1); - // airplane.glb is now bounding-box centred with transforms applied. + // Fleet models are drawn about their origin, transforms applied. const x = 0 * scale; const y = 0 * scale; const z = 0 * scale; @@ -1694,7 +1798,7 @@ async function main() { mil.trackById(hex); await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const milTrackedBefore = !!mil.getTrackedInfo(); - fl.trackById(icao); // tracking commercial flips viewer.trackedEntity → military listener fires + fl.trackById(icao); // tracking commercial changes what the camera follows → military listener fires await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); return { milTrackedBefore, @@ -1749,16 +1853,22 @@ async function main() { const ti = fl.getTrackedInfo(); if (!ti || ti.icao24 !== icao) return false; const found = window.__findTrackedModel ? window.__findTrackedModel() : null; - return !!(found && found.ready && found.show && String(found.id) === icao); + return !!(found && found.ready && found.show && window.__qaModelIcao(found) === icao); }, { timeout: 60000, polling: 250 }, h1Icao).then(() => true).catch(() => false); if (h1ModelUp) { const modelPickId = await evalPage(() => { const m = window.__findTrackedModel(); - return m && m.id !== undefined && m.id !== null ? String(m.id) : null; + if (!m || m.id === undefined || m.id === null) return null; + // The draw port's pick id is `{set, id}`: the click resolver keys on + // both, so the set must be this layer's tracked model set. + if (typeof m.id === 'object') return { set: String(m.id.set), id: String(m.id.id) }; + return { set: null, id: String(m.id) }; }); - record('H1: tracked standalone model exposes its pick id', modelPickId === h1Icao, - `model.id=${JSON.stringify(modelPickId)} (want "${h1Icao}")`); + record('H1: tracked standalone model exposes its pick id', + modelPickId?.id === h1Icao + && (modelPickId.set === null || modelPickId.set.startsWith('flights-tracked-model:')), + `model.id=${JSON.stringify(modelPickId)} (want id "${h1Icao}" in the flights tracked-model set)`); } else if (!glbBackendCapable) { skip('H1: tracked standalone model exposes its pick id', `independent GLB control unavailable (${glbControlDetail})`); @@ -1777,15 +1887,21 @@ async function main() { const fl = window.__godsEyeView.dataManager.layers.get('flights').module; const ti = fl.getTrackedInfo(); if (!ti) return null; - const ent = v.trackedEntity; - const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const followed = window.__qaFollowed(); + const disp = typeof followed?.displayPosition === 'function' ? followed.displayPosition() : null; const pos = disp || ti.position; if (!pos) return null; const center = v.scene.cartesianToCanvasCoordinates(pos); if (!center) return null; + // The tracked plane is drawn by the layer's own tracked icon and + // tracked model sets; a pick on either names `{set, id}`. const isTrackedPick = (picked) => { if (!picked) return null; - if (picked.id === ent) return 'entity'; + const hit = picked.id && typeof picked.id === 'object' ? picked.id : null; + if (hit && String(hit.id) === ti.icao24 && typeof hit.set === 'string') { + if (hit.set.startsWith('flights-tracked-icon:')) return 'tracked-icon'; + if (hit.set.startsWith('flights-tracked-model:')) return 'tracked-model'; + } const raw = typeof picked.id === 'string' ? picked.id : (picked.primitive && picked.primitive.id); return raw === ti.icao24 ? 'icao-pick' : null; }; @@ -1843,7 +1959,7 @@ async function main() { }, 45); const h1StillTracking = await evalPage((icao) => { const ti = window.__godsEyeView.dataManager.layers.get('flights').module.getTrackedInfo(); - return !!(ti && ti.icao24 === icao) && !!window.__godsEyeView.viewer.trackedEntity; + return !!(ti && ti.icao24 === icao) && !!window.__qaFollowed(); }, h1Icao); record('H1: click on tracked plane keeps tracking (no deselect)', h1StillTracking, `picked via ${h1ClickPoint.via}; still tracking=${h1StillTracking}`); @@ -1856,8 +1972,8 @@ async function main() { // REGRESSION M3 (rewritten 2026-07-02 — deliberate behavior change): // when the TRACKED plane ages out (10 min after its newest fix, past the // 3 missed polls that remove an untracked plane), tracking must clear - // and the camera must be RELEASED IN PLACE — viewer.trackedEntity - // undefined and NO jump (the old contract flew an ~80 km overview; the + // and the camera must be RELEASED IN PLACE — following nothing + // and NO jump (the old contract flew an ~80 km overview; the // owner field-ruled that wrong: "it randomly zooms way up and loses my // context"). The M3 ordering fix stays: tracking is cleared BEFORE the // removal loop deletes the plane's state, so we never sit mid-follow @@ -1908,7 +2024,7 @@ async function main() { trackedThroughMisses, atAgeOut, stillTrackedAfter: !!fl.getTrackedInfo(), - viewerStillTracking: !!v.trackedEntity, + viewerStillTracking: !!window.__qaFollowed(), }; } finally { Date.now = realNow; @@ -1921,7 +2037,7 @@ async function main() { record('M3: tracking cleared after the tracked plane ages out (getTrackedInfo null)', m3.beforeTracking && !m3.stillTrackedAfter, `before=${m3.beforeTracking} trackedAfter=${m3.stillTrackedAfter}`); - record('M3: camera released after age-out (viewer.trackedEntity undefined)', + record('M3: camera released after age-out (the camera follows nothing)', !m3.viewerStillTracking, `viewerTracked=${m3.viewerStillTracking}`); @@ -2046,16 +2162,17 @@ async function main() { const v = window.__godsEyeView.viewer; const fl = window.__godsEyeView.dataManager.layers.get('flights').module; const labelText = () => { - const ent = v.trackedEntity; + const ent = window.__qaFollowed(); if (!ent) return null; // Post overlay-unification the tracked text lives in the host // presentation model (entities are asserted native-label-free); // the native read stays as a fallback so this probe still fails // loudly if BOTH surfaces are ever absent. - const model = ent.gevLabelModel; + const model = ent.labelModel; if (model) return [model.title, ...(model.details || [])].filter(Boolean).join('\n'); - if (!ent.label || !ent.label.text) return null; - const t = ent.label.text; + const label = ent.entity?.label; + if (!label || !label.text) return null; + const t = label.text; return typeof t === 'string' ? t : (t.getValue ? String(t.getValue(v.clock.currentTime)) : null); }; // Track a cruise plane that IS in the feed (aaa003: 8700 m, 250 m/s — @@ -2100,19 +2217,7 @@ async function main() { const fl = dm.layers.get('flights').module; const mil = dm.layers.get('military').module; const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const snap = (id) => { const bb = findBB(id); @@ -2229,18 +2334,12 @@ async function main() { // ============================================================ console.log('\nGround 3D — grounded planes are model-eligible + snapped to the sampled skin'); const GROUND3D_STUB_H = 187.5; // stubbed tile-skin height (m, ellipsoid) - // Expected belly offsets (m): native origin-above-lowest-vertex × MODEL_SCALE - // × CLASS_SCALE_3D[klass] — constants match the layers' MODEL_BELLY_OFFSET_NATIVE - // / MODEL_SCALE pairs, which modelScale.test.mjs locks against the GLBs. - // Class is computed with the REAL classifier on the synthetic feed fields. - const g3dFlKlass = classifyAircraft({ typeCode: null, category: null }); - const g3dMilKlass = classifyAircraft({ typeCode: 'C130', category: undefined }); - const g3dFlOffset = 6.719 * 1 * (CLASS_SCALE_3D[g3dFlKlass] || 1); // airplane.glb, flights - // Hangar fleet (2026-08-16): military C130 → turboprop → the real atr72.glb, - // whose belly offset is the registry's measured bellyM (meters, scale 1) — - // NOT the jet.glb 5.631 × class formula. Pinned by modelScale.test.mjs. - const g3dMilOffset = CLASS_MODEL_REAL[g3dMilKlass]?.bellyM - ?? 5.631 * 1 * (CLASS_SCALE_3D[g3dMilKlass] || 1); // jet.glb fallback classes + // Expected belly offsets (m): the fleet model's wheel clearance at its + // life-size scale, the model chosen as the layers choose it + // (aircraftModelSpec) from the synthetic feed's fields: no type for the + // flights contact (the default airliner), a C130 for the military one. + const g3dFlOffset = aircraftModelSpec(FLEET_SET, { typeCode: null }).clearanceM; + const g3dMilOffset = aircraftModelSpec(FLEET_SET, { typeCode: 'C130' }).clearanceM; // Height-datum fix (Task 6): the flights-layer billboard for a grounded synthetic // (no geo_altitude in this stub feed, no warm terrain-height cache in a headless // run) now renders at baroM + geoidHeight(lat, lon) rather than the raw baro @@ -2393,19 +2492,7 @@ async function main() { await fl.update(v); await mil.update(v); const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const flBB = findBB('aaa077'); const milBB = findBB('bbb177'); @@ -2440,7 +2527,7 @@ async function main() { try { p = coll.get(i); } catch { continue; } if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.modelMatrix && typeof p.ready !== 'undefined' && p.id === id) found = p; + if (p.modelMatrix && typeof p.ready !== 'undefined' && window.__qaModelIcao(p) === id) found = p; } }; walk(v.scene.primitives); @@ -2469,19 +2556,7 @@ async function main() { const g3dState = await evalPage(() => { const v = window.__godsEyeView.viewer; const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const modelRadius = (id) => { const m = window.__g3dFindModel(id); @@ -2509,10 +2584,10 @@ async function main() { const flDelta = g3dState.flModelRadius - g3dIngest.flBBRadius; const milDelta = g3dState.milModelRadius - g3dIngest.milBBRadius; const HEIGHT_TOL_M = 1.0; - record(`ground-3d: flights model height = sampled skin + belly offset (${g3dFlKlass})`, + record(`ground-3d: flights model height = sampled skin + belly offset (default airliner)`, Math.abs(flDelta - flWantDelta) <= HEIGHT_TOL_M, `Δradial=${flDelta.toFixed(2)} m want=${flWantDelta.toFixed(2)} m (stub ${GROUND3D_STUB_H} + offset ${g3dFlOffset.toFixed(2)} − alt ${(150 + g3dFlGeoidN).toFixed(2)} [150 baro + ${g3dFlGeoidN.toFixed(2)} geoidN])`); - record(`ground-3d: military model height = sampled skin + belly offset (${g3dMilKlass})`, + record(`ground-3d: military model height = sampled skin + belly offset (C130)`, Math.abs(milDelta - milWantDelta) <= HEIGHT_TOL_M, `Δradial=${milDelta.toFixed(2)} m want=${milWantDelta.toFixed(2)} m (stub ${GROUND3D_STUB_H} + offset ${g3dMilOffset.toFixed(2)} − alt 0)`); record('ground-3d: billboard→model handoff holds on the ground (icons hidden once models render)', @@ -2697,7 +2772,7 @@ async function main() { } // WELD (tracked): the tracked CARD anchors to the model you can see. - // `gevVisualPosition` is a SEPARATE accessor from `gevDisplayPosition` on + // the record's `visualPosition` is a SEPARATE accessor from its `displayPosition` on // purpose — the latter carries the follow-camera anti-jitter contract and // must keep returning the cached dead-reckoned value the camera settled // on. So this asserts both halves: the visual accessor is welded to the @@ -2705,14 +2780,14 @@ async function main() { // dead-reckoned position rather than having been quietly repurposed. if (g3dTrackedUp) { const trackedWeld = await evalPage(() => { - const ent = window.__godsEyeView.viewer.trackedEntity; + const ent = window.__qaFollowed(); const m = window.__g3dFindModel('aaa077'); if (!m) return { error: 'no tracked model' }; const matrix = m.modelMatrix; const scale = Number.isFinite(m.computedScale) ? m.computedScale : (Number.isFinite(m.scale) ? m.scale : 1); - // airplane.glb is now bounding-box centred with transforms applied. + // Fleet models are drawn about their origin, transforms applied. const x = 0 * scale; const y = 0 * scale; const z = 0 * scale; @@ -2724,10 +2799,10 @@ async function main() { const at = (p) => (p ? Math.hypot( p.x - anchor.x, p.y - anchor.y, p.z - anchor.z, ) : null); - const visual = typeof ent?.gevVisualPosition === 'function' ? ent.gevVisualPosition() : null; - const display = typeof ent?.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const visual = typeof ent?.visualPosition === 'function' ? ent?.visualPosition() : null; + const display = typeof ent?.displayPosition === 'function' ? ent?.displayPosition() : null; return { - hasVisualAccessor: typeof ent?.gevVisualPosition === 'function', + hasVisualAccessor: typeof ent?.visualPosition === 'function', visualDelta: at(visual), displayDelta: at(display), }; @@ -2743,7 +2818,7 @@ async function main() { // anti-jitter accessor has been repurposed and the follow camera is at // risk. Skipped (not failed) when the DR cache is momentarily invalid. const displayDelta = trackedWeld.displayDelta; - record('weld: gevDisplayPosition still reports the dead-reckoned position (anti-jitter intact)', + record('weld: the record displayPosition still reports the dead-reckoned position (anti-jitter intact)', !Number.isFinite(displayDelta) || displayDelta > ACCESSOR_SEPARATION_EPSILON_M, Number.isFinite(displayDelta) ? `displayΔ=${displayDelta.toFixed(3)} m (must stay > ${ACCESSOR_SEPARATION_EPSILON_M} m — the ground-snap split)` @@ -2832,6 +2907,21 @@ async function main() { // CHANGE 4 (2026-07-03): arrival rotation freshness. Field test: "planes // look weird when you first come to them — rotations are weird". Two // repaired holes, both layers: + // + // SINCE THE GPU ICON SETS (2c4c66c71) there is no CPU rotation pass to + // tamper with or repair: each frame the shader turns every icon along the + // course its row's motion segment carries at that frame's time. The + // invariant — the nose is right on the first settled frame after a + // camera move and on the first frame a hidden contact is shown again — + // is now observed on the drawn rows: the on-screen nose the drawn course + // projects to, against the one the plane's feed course projects to, at + // the same position, on exactly those two frames (same 10° bound, same + // per-frame budgets). That the shader turns an icon to the screen angle + // its course projects to is the renderer's own contract, which the + // renderer conformance reference scenes draw (course-rotated arrows, + // top and tilted views); a CPU readback cannot see the GPU's rotation. The reveal hides and re-shows the row through the + // layer's own icon book, the only thing that hides a fleet icon. + // The two holes the passes repaired, for the record: // (a) SETTLE PASS — camera.moveEnd forces a full rotation pass on the // next frame (the pose-signature gate can eat a fly-to's settle: // the final easing frames land inside one 10 m/0.06° quantization @@ -2840,39 +2930,25 @@ async function main() { // idles gets its rotation refreshed the same tick (it used to // reappear wearing its stale/creation-north nose for up to 1 s). // Staged deterministically: park the camera nadir over the synthetic - // cluster, let rotations settle, TAMPER a billboard's rotation, then - // trigger each path with the camera idle. The fleet runs every 80 ms, - // independently of rendered FPS. Observe the first completed settle frame - // within 500 ms of forcing moveEnd and the first reveal frame within - // 500 ms of that settle frame: each budget sits inside the 1 s idle - // rotation refresh that could otherwise repair an incorrect first reveal, - // and a ~300 ms headless SwiftShader frame fits inside each of them. + // cluster, let it settle, then trigger each path with the camera idle. + // Observe the first completed settle frame within 500 ms of forcing + // moveEnd and the first reveal frame within 500 ms of that settle frame + // (the budgets once sat inside the 1 s idle rotation refresh; they are + // kept as they were). // ============================================================ - console.log('\nChange 4 — arrival rotation: moveEnd settle pass + horizon-reveal pass'); + console.log('\nChange 4 — arrival rotation: the drawn nose on the settle frame and the first reveal'); const arrival = await evalPage(async () => { const v = window.__godsEyeView.viewer; const dm = window.__godsEyeView.dataManager; - const { screenProjectedRotation } = await import(`${window.__gevQaSourceBase || '/src'}/data/iconOrientation.js`); + const { screenProjectedRotation } = await import(`${window.__gevQaSourceBase || '/src'}/render/cesium/iconOrientation.js`); const { observeArrivalRotationWithRetry } = await import(`${window.__gevQaSourceBase || '/src'}/tooling/trackArrivalObservation.mjs`); - // 3D models OFF for this phase: a model-handed-off billboard is hidden - // and skips rotation updates entirely — the probes need live billboards - // (this is also the app's default state the field report came from). + // 3D models OFF for this phase: a model-handed-off icon is hidden, and + // the probes need shown icons (this is also the app's default state the + // field report came from). dm.layers.get('flights').module.setParams({ models3d: false }); dm.layers.get('military').module.setParams({ models3d: false }); const findBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; - try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; const nextFrames = (n) => new Promise((res) => { let count = 0; @@ -2896,8 +2972,8 @@ async function main() { }); // Park the camera straight above the flights cluster (lift a live // billboard's position radially — no Cesium global needed in-page) so - // every probe plane projects on-screen, then let rotations settle at - // the new pose (the setView pose change forces a pass on the next tick). + // every probe plane projects on-screen, then let a few frames draw at + // the new pose. // aaa002 — aaa001 was evicted for good by the M3 age-out phase. const anchor = findBB('aaa002'); if (!anchor) return { error: 'anchor aaa002 missing' }; @@ -2911,62 +2987,99 @@ async function main() { }); await nextFrames(3); const angDiff = (a, b) => Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b))); - const probe = async (id, course) => { + const probe = async (layer, id, course) => { const bb = findBB(id); if (!bb || !bb.show) return { error: `${id} missing/hidden` }; - const r0 = bb.rotation; // settled tamper origin; correctness uses a fresh projection below + if (!Number.isFinite(bb.course) && !Number.isFinite(bb.rotation)) { + return { error: `${id} has no drawn course or rotation` }; + } + const setIconShown = layer.testing?._setIconForTest; + if (typeof setIconShown !== 'function') return { error: `${id}: the layer has no icon test seam` }; + // The on-screen nose the drawn row shows now, against the feed's. + const drawnError = () => { + const now = findBB(id); + if (!now) return { shown: false, rotationError: NaN }; + // A GPU row is turned along its drawn course, or drawn upright; a + // billboard carries its screen rotation itself. + const drawn = Number.isFinite(now.course) + ? (now.rotates ? screenProjectedRotation(v.scene, now.position, now.course, null) : 0) + : now.rotation; + return { + shown: !!now.show, + rotationError: angDiff(drawn, screenProjectedRotation(v.scene, now.position, course, null)), + }; + }; const hasModel = !!(window.__g3dFindModel && window.__g3dFindModel(id)); - // A wall-clock timeout is inconclusive, not a wrong angle: the frame - // landed where the 1 s idle refresh could already have repaired it - // (seen once on headless SwiftShader: a 926 ms first frame). Such an - // observation gets one more attempt; one that measured a wrong angle — - // a wrong first reveal, or a wrong settle frame before a reveal - // timeout — never does. + // The settle/reveal budgets and the retry were written for the removed + // CPU passes (a frame late enough for the 1 s idle refresh to repair + // it was inconclusive); they are kept unchanged as a guard. A + // wall-clock timeout gets one more attempt; one that measured a wrong + // angle — a wrong first reveal, or a wrong settle frame before a + // reveal timeout — never does. + // + // The reveal: the row is hidden right after the settle frame, frames + // must actually draw it hidden, and only then is it shown again, so + // the frame measured is the first one that draws it after a hidden + // frame. It stays hidden for two drawn frames, past the frame that + // follows the settle frame, so the reveal is timed on an ordinary + // frame rather than on whether that one was pipelined; each hidden + // frame restarts the reveal's clock, and the setup is `hiddenMs`. + const REVEAL_HIDDEN_FRAMES = 2; + let revealArmed = false; + let hiddenFrames = 0; const observed = await observeArrivalRotationWithRetry({ async prepare() { - // Freshen both layers' rotation passes right before the probe, so - // the settle frame is measured against a pass that just ran rather - // than one left over from the previous probe — with the camera - // idle, a layer otherwise runs a pass only every - // ROTATION_REFRESH_MS. + // One settled camera move and a frame before each attempt, as the + // passes once needed (the layers' moveEnd now runs their fleet + // pass on the next frame). + revealArmed = false; + hiddenFrames = 0; v.camera.moveEnd.raiseEvent(); await nextFrames(1); }, scene: v.scene, startMoveEnd() { - // Only moveEnd can repair the tampered angle at the idle pose. - bb.rotation = r0 + 1.5; v.camera.moveEnd.raiseEvent(); }, startReveal() { - // Hide immediately after the confirmed settle frame. The next - // eligible fleet tick must reveal AND re-aim in that same tick. - bb.rotation = r0 + 1.5; - bb.show = false; + // Hide immediately after the confirmed settle frame, through the + // layer's icon book (written to the draw set as this task ends). + setIconShown(id, { shown: false }); + revealArmed = true; }, read() { - return { - shown: bb.show, - rotationError: angDiff(bb.rotation, - screenProjectedRotation(v.scene, bb.position, course, null)), - }; + const sample = drawnError(); + // A frame drew it hidden: after the last one, show it again for + // the next frame; the reveal is measured from here. + if (revealArmed && sample.shown === false) { + hiddenFrames += 1; + if (hiddenFrames >= REVEAL_HIDDEN_FRAMES) { + revealArmed = false; + setIconShown(id, { shown: true }); + } + return { ...sample, revealStartsNow: true }; + } + return sample; }, }); - return { r0, ...observed, hasModel }; + // A reveal is only one after a frame drew the row hidden. + if (!observed.error && hiddenFrames === 0) { + return { ...observed, error: 'no frame drew the row hidden before its reveal', hasModel }; + } + return { ...observed, hiddenFrames, hasModel }; }; const flightCourse = window.__SYNTH.flights.find((f) => f.icao === 'aaa002')?.track ?? 0; const militaryCourse = window.__SYNTH.military.find((m) => m.hex === 'bbb101')?.track ?? 0; return { - flights: await probe('aaa002', flightCourse), - military: await probe('bbb101', militaryCourse), + flights: await probe(dm.layers.get('flights').module, 'aaa002', flightCourse), + military: await probe(dm.layers.get('military').module, 'bbb101', militaryCourse), }; }); const fmtArr = (a) => (!a ? `no result (${arrival?.error || 'phase error'})` : a.error ? `${a.error}; ${arrivalAngleViolated(a) ? 'angle violation (not retried); ' : ''}${Number.isFinite(a.dMoveEnd) ? `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° ` : ''}${Number.isFinite(a.dReveal) ? `reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° ` : ''}elapsed=${Number(a.elapsedMs).toFixed(1)} ms attempts=${a.attempts}` - : `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} settle=${a.moveEndMs.toFixed(1)} ms reveal=${a.revealMs.toFixed(1)} ms total=${a.elapsedMs.toFixed(1)} ms attempts=${a.attempts} hasModel=${a.hasModel}`); - const TAMPER_DEG = 1.5 * 180 / Math.PI; // ≈ 86° — an uncorrected nose stays this far off - record(`arrival: moveEnd + first reveal both re-aim before idle refresh, flights (tamper was ${TAMPER_DEG.toFixed(0)}°)`, + : `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} settle=${a.moveEndMs.toFixed(1)} ms reveal=${a.revealMs.toFixed(1)} ms hidden=${a.hiddenMs.toFixed(1)} ms total=${a.elapsedMs.toFixed(1)} ms attempts=${a.attempts} hasModel=${a.hasModel}`); + record('arrival: the drawn nose is right on the settle frame and the first reveal, flights', arrivalRotationPassed(arrival.flights), fmtArr(arrival.flights)); - record(`arrival: moveEnd + first reveal both re-aim before idle refresh, military (tamper was ${TAMPER_DEG.toFixed(0)}°)`, + record('arrival: the drawn nose is right on the settle frame and the first reveal, military', arrivalRotationPassed(arrival.military), fmtArr(arrival.military)); // ============================================================ @@ -3027,18 +3140,7 @@ async function main() { }; fl.setParams({ models3d: false }); // billboards own the visual (T7 gate open) window.__dfFindBB = (id) => { - let found = null; - const walk = (coll) => { - const n = coll.length; - for (let i = 0; i < n; i++) { - let p; try { p = coll.get(i); } catch { continue; } - if (!p) continue; - if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.image !== undefined && p.alignedAxis !== undefined && p.id === id) found = p; - } - }; - walk(v.scene.primitives); - return found; + return window.__qaFindIcon(id); }; window.__dfCarto = (pos) => { const c = Cesium.Cartographic.fromCartesian(pos, Cesium.Ellipsoid.WGS84); @@ -3124,7 +3226,7 @@ async function main() { if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined) { - if (icao !== undefined && p.id !== icao) continue; + if (icao !== undefined && window.__qaModelIcao(p) !== icao) continue; if (p.show) { shown += 1; if (p.ready === true) rendering += 1; @@ -3149,7 +3251,7 @@ async function main() { if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined - && p.id === icao && p.modelMatrix) { + && window.__qaModelIcao(p) === icao && p.modelMatrix) { const m = p.modelMatrix; // Cesium's default is the IDENTITY matrix — translation (0,0,0), // the Earth's centre, which `Cartographic.fromCartesian` refuses. @@ -3167,23 +3269,18 @@ async function main() { walk(v.scene.primitives); return h; }; - // Tracked-contact model regime (2026-08-20). The tracked contact's model - // is NOT governed by the DISPLAY-rail 3D toggle — that toggle owns the - // FLEET's draw-call budget. The tracked model is default-on and driven by - // camera distance, entering below TRACKED_MODEL_ENTER_ALT_M and handing - // back to the billboard only above TRACKED_MODEL_EXIT_ALT_M (the - // anti-flap band). The CAMERA is therefore what decides whether a model - // or a billboard is the visual for a tracked contact, which is exactly - // what the display floor stands aside for — so these pins drive the - // camera explicitly instead of the toggle. + // Tracked-contact model regime. The tracked contact draws as a model + // exactly when the fleet's rule would draw it so: 3D on, the camera + // below the fleet ceiling, and the contact inside the nearest-first + // add/keep band from the eye. These pins drive the camera across that + // band: a model inside the ADD radius, the billboard past the KEEP one. // - // Read the thresholds from the app's own policy module so a later retune - // of the swap distance moves these pins with it rather than stranding - // them on stale numbers. - const reg = await import(`${window.__gevQaSourceBase || '/src'}/data/trackedModelRegime.js`); + // Read the radii from the app's own policy module so a retune moves + // these pins with it rather than stranding them on stale numbers. + const reg = await import(`${window.__gevQaSourceBase || '/src'}/layers/flights/policy.js`); window.__dfRegime = { - enter: reg.TRACKED_MODEL_ENTER_ALT_M, - exit: reg.TRACKED_MODEL_EXIT_ALT_M, + enter: reg.MODEL_PROX_ADD_M, + exit: reg.MODEL_PROX_KEEP_M, }; // Zooming while following is safe: the tracked-camera framer positions // the camera ONCE per selection and is deliberately read-only on normal @@ -3529,9 +3626,29 @@ async function main() { // after d0 was read; a lower seed makes the negative model-ownership // assertion impossible even when the clamp correctly stands aside. const seeded = Math.max(d0.h, 400) + 40; - for (let dy = -1; dy <= 1; dy++) { - for (let dx = -1; dx <= 1; dx++) { - gf.reportMeshFloorCell(cell(d0.lat) + dy * 0.001, cell(d0.lon) + dx * 0.001, seeded); + // The contact keeps taxiing while the regimes below are driven (the + // model wait alone can run to 20 s), so the planted floor reaches + // along its heading as well: the 3×3 cells around it, and the same + // three cells across the track every ~100 m for 600 m ahead. A + // contact that left a 3×3 patch was read over an unplanted cell, + // where a DEM floor that had already landed under its raw height + // decided the assertion instead of the regime. + const headingDeg = window.__SYNTH.flights.find((f) => f.icao === 'aaa097')?.track ?? 0; + const headingRad = headingDeg * Math.PI / 180; + const metresPerDegLat = 111320; + const metresPerDegLon = metresPerDegLat * Math.cos(d0.lat * Math.PI / 180); + const plantedCells = new Set(); + for (let aheadM = 0; aheadM <= 600; aheadM += 100) { + const lat = d0.lat + (aheadM * Math.cos(headingRad)) / metresPerDegLat; + const lon = d0.lon + (aheadM * Math.sin(headingRad)) / metresPerDegLon; + for (let dy = -1; dy <= 1; dy++) { + for (let dx = -1; dx <= 1; dx++) { + const c = [cell(lat) + dy * 0.001, cell(lon) + dx * 0.001]; + const key = `${c[0].toFixed(3)},${c[1].toFixed(3)}`; + if (plantedCells.has(key)) continue; + plantedCells.add(key); + gf.reportMeshFloorCell(c[0], c[1], seeded); + } } } const fleetClampDeadline = Date.now() + 5000; @@ -3549,7 +3666,7 @@ async function main() { // the sensor value the data APIs report, at whatever regime the camera // is currently in. const readTracked = () => { - const pos = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const pos = window.__qaFollowed()?.position?.(); if (!pos) return null; const c = window.__dfCarto(pos); const info = fl.getTrackedInfo(); @@ -3624,19 +3741,19 @@ async function main() { for (let i = 0; i < collection.length; i++) { const item = collection.get(i); if (typeof item?.get === 'function' && typeof item.length === 'number') walk(item); - else if (item?.id === 'aaa097' && item.activeAnimations !== undefined + else if (window.__qaModelIcao(item) === 'aaa097' && item.activeAnimations !== undefined && item.minimumPixelSize !== undefined) found = item; } }; walk(v.scene.primitives); return found; }; - const trackedEntity = v.trackedEntity; + const trackedEntity = window.__qaFollowed(); const trackedModel = findOwnModel(); const achievedOut = await window.__dfZoomAbove(window.__dfRegime.exit + 5000); const zoomedOut = await window.__dfObserveTrackedExit({ scene: v.scene, trackedEntity, trackedModel, getTrackedModel: findOwnModel, - getTrackedEntity: () => v.trackedEntity, + getTrackedEntity: () => window.__qaFollowed(), getTrackedId: () => fl.getTrackedInfo()?.icao24, getCameraHeight: window.__dfCamH, exitHeight: window.__dfRegime.exit, read: readTracked, @@ -3722,8 +3839,8 @@ async function main() { // WARM ground, camera IN: the placement. The model is not merely visible, // it is standing ON the floor — within one class belly offset above it, - // never under it. MAX_BELLY_M clears the largest offset any class adds - // (widebody b789, 7.81 m in CLASS_MODEL_REAL); the floor itself is the + // never under it. MAX_BELLY_M clears the largest wheel clearance any + // fleet aircraft stands on at life size; the floor itself is the // hard lower bound, and a model placed at the raw feed altitude is ~240 m // under it. const MAX_BELLY_M = 12; @@ -3804,7 +3921,7 @@ async function main() { return { skipped: 'no tracked model rendered in this browser' }; } // While the model IS the visual the clamp must stand aside (T7). - const entWith = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const entWith = window.__qaFollowed()?.position?.(); const withModelH = entWith ? window.__dfCarto(entWith).h : null; // Close the deterministic skin again for the rest of the group. The // model is up on a snap that is already cached, so it stays up until the @@ -3819,7 +3936,7 @@ async function main() { // contact's primitive, and an unrelated model in the scene must not be // able to answer it either way. const afterOut = window.__dfCountModels('aaa097'); - const ent = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const ent = window.__qaFollowed()?.position?.(); const c = ent ? window.__dfCarto(ent) : null; // Plant a floor above wherever it now renders so "floored" is decisive. // Mesh cells latch ONE-SHOT, so the earlier scenario's seed would win @@ -3840,7 +3957,7 @@ async function main() { // from mistaking a cached same-frame position for a failed clamp. v.scene.requestRender(); await window.__dfSettle(900); - const ent2 = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const ent2 = window.__qaFollowed()?.position?.(); const c2 = ent2 ? window.__dfCarto(ent2) : null; const out = { toggleOff, @@ -3932,7 +4049,7 @@ async function main() { let p; try { p = coll.get(i); } catch { continue; } if (!p) continue; if (typeof p.length === 'number' && typeof p.get === 'function') { walk(p); continue; } - if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined && p.id === id) found = p; + if (p.activeAnimations !== undefined && p.minimumPixelSize !== undefined && window.__qaModelIcao(p) === id) found = p; } }; walk(v.scene.primitives); @@ -3948,19 +4065,30 @@ async function main() { fl.setParams({ models3d: false }); return { skipped: 'no fleet model for aaa097 in this browser' }; } + // The layer decides who owns the visual from its OWN record of the + // model (data/modelRecord.js: `ready` from the draw set's ready event, + // `show` as it last sent it), not from the renderer's model object, so + // the shown-but-not-ready state is planted on that record. The record + // is the registered layer's own, reached through its test seam. + const fleetRecord = await fl.testing?._ensureFleetModelForTest?.('aaa097'); + if (!fleetRecord || typeof fleetRecord !== 'object') { + fl.setParams({ models3d: false }); + return { error: 'the flights layer has no model record for aaa097' }; + } // Accessors with SWALLOWING setters, not data properties: the fleet tick - // assigns `model.show = false` for a not-ready model, and assigning to a + // assigns `show = false` for a not-ready model, and assigning to a // non-writable own property throws in strict mode — which lands inside - // Cesium's render loop and stops rendering for the rest of the run. - const priorReady = Object.getOwnPropertyDescriptor(fleetModel, 'ready'); - const priorShow = Object.getOwnPropertyDescriptor(fleetModel, 'show'); + // the render loop and stops rendering for the rest of the run. + const priorReady = Object.getOwnPropertyDescriptor(fleetRecord, 'ready'); + const priorShow = Object.getOwnPropertyDescriptor(fleetRecord, 'show'); let armed = false; let processedFrame = null; let sample = null; + let sampledRecord = null; let removePostRender = null; try { - Object.defineProperty(fleetModel, 'ready', { get: () => false, set: () => {}, configurable: true }); - Object.defineProperty(fleetModel, 'show', { + Object.defineProperty(fleetRecord, 'ready', { get: () => false, set: () => {}, configurable: true }); + Object.defineProperty(fleetRecord, 'show', { get: () => true, set: (value) => { // Both the not-ready handoff and horizon cull clear show AFTER @@ -3974,7 +4102,10 @@ async function main() { }); const bb = window.__dfFindBB('aaa097'); if (!bb) return { error: 'aaa097 billboard missing' }; - bb.show = true; // the handoff would not have hidden it: the model is not ready + // (The icon is not forced shown here, as the old billboard fixture did: + // the renderer draws what the layer sends, so the handoff the record + // drives is the only thing that decides it.) + const sameIcon = (a, b) => !!a && !!b && (a === b || (a.setId === b.setId && a.id === b.id)); const d0 = window.__dfCarto(bb.position); gf._clearMeshFloorCellsForTest(); // Earlier display-floor scenarios deliberately leave this contact's @@ -3997,13 +4128,18 @@ async function main() { sample = { fleetTickCompleted: true, fleetFrame: v.scene.frameState.frameNumber, - fleetModelReady: fleetModel.ready, - fleetModelShow: fleetModel.show, + fleetModelReady: fleetRecord.ready, + fleetModelShow: fleetRecord.show, fleetBillboardVisible: !!currentBb?.show, fleetSeeded: seededFleet, fleetH: currentBb ? window.__dfCarto(currentBb.position).h : null, }; - if (currentBb !== bb || currentModel !== fleetModel || fleetModel.isDestroyed() + // (An older build's seam answers asynchronously: its answer is + // checked once the frame is done, below.) + const currentRecord = fl.testing._ensureFleetModelForTest('aaa097'); + if (typeof currentRecord?.then === 'function') sampledRecord = currentRecord; + else if (currentRecord !== fleetRecord) sample.error = 'fleet loading fixture changed before its completed frame'; + if (!sameIcon(currentBb, bb) || currentModel !== fleetModel || fleetModel.isDestroyed() || fl.getTrackedInfo()) sample.error = 'fleet loading fixture changed before its completed frame'; }); armed = true; @@ -4014,14 +4150,17 @@ async function main() { await window.__dfSettle(50); } while (!sample && Date.now() < tickDeadline); if (!sample) return { error: 'fleet loading fixture did not complete an aircraft update within 5000 ms' }; + if (sampledRecord && (await sampledRecord) !== fleetRecord) { + sample.error = 'fleet loading fixture changed before its completed frame'; + } Object.assign(out, sample); } finally { armed = false; removePostRender?.(); - if (priorReady) Object.defineProperty(fleetModel, 'ready', priorReady); - else delete fleetModel.ready; - if (priorShow) Object.defineProperty(fleetModel, 'show', priorShow); - else delete fleetModel.show; + if (priorReady) Object.defineProperty(fleetRecord, 'ready', priorReady); + else delete fleetRecord.ready; + if (priorShow) Object.defineProperty(fleetRecord, 'show', priorShow); + else delete fleetRecord.show; fl.setParams({ models3d: false }); } await window.__dfSettle(400); @@ -4032,7 +4171,7 @@ async function main() { // it finishes. Sample within that window. if (!fl.trackById('aaa097')) return { ...out, error: 'trackById(aaa097) failed' }; await window.__dfSettle(500); - const entBefore = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const entBefore = window.__qaFollowed()?.position?.(); const cBefore = entBefore ? window.__dfCarto(entBefore) : null; gf._clearMeshFloorCellsForTest(); fl._clearDisplayFloorStateForTest(); @@ -4054,7 +4193,7 @@ async function main() { // billboard-owned. The shared helper keys models by their pick id and // uses the production ownership pair (`show && ready`). out.renderingModelsDuringLoad = window.__dfCountModels('aaa097').rendering; - const entLoad = v.trackedEntity?.position?.getValue(Cesium.JulianDate.now()); + const entLoad = window.__qaFollowed()?.position?.(); out.trackedSeeded = seededTracked; out.trackedLoadH = entLoad ? window.__dfCarto(entLoad).h : null; fl.setParams({ models3d: false }); @@ -4174,7 +4313,12 @@ async function main() { const taxiCarto = window.__dfCarto(taxiPos); const baseMeshM = gfns?.cachedMeshFloor?.(baseCarto.lat, baseCarto.lon) ?? null; const taxiMeshM = gfns?.cachedMeshFloor?.(taxiCarto.lat, taxiCarto.lon) ?? null; + // The layer writes its icon changes to the draw set together once the + // current task's microtasks run (data/aircraftIconLayer.js), so the + // drawn row is read after that write, with no frame in between. + const iconWrites = () => Promise.resolve(); const heldOwns = ns._driveFleetModelHandoffForTest({ icao24: holdIcao, position: taxiPos, course: 90 }); + await iconWrites(); const heldH = window.__dfModelHeight(holdIcao); const heldBb = !!window.__dfFindBB(holdIcao)?.show; @@ -4182,6 +4326,7 @@ async function main() { // been. It is released rather than stretched, and the gate takes over. const farPos = Cesium.Cartesian3.fromDegrees(base.lon + 0.004, base.lat, base.h); const releasedOwns = ns._driveFleetModelHandoffForTest({ icao24: holdIcao, position: farPos, course: 90 }); + await iconWrites(); const releasedBb = !!window.__dfFindBB(holdIcao)?.show; fl.setParams({ models3d: false }); diff --git a/scripts/viewer-access-baseline.mjs b/scripts/viewer-access-baseline.mjs new file mode 100644 index 0000000000..4a2614a9bd --- /dev/null +++ b/scripts/viewer-access-baseline.mjs @@ -0,0 +1,63 @@ +/** + * Lower `src/render/viewerAccessAllowList.json` to the Cesium-shaped viewer + * accesses the files off the Cesium list still hold + * (`src/render/viewerAccess.test.mjs`). It only lowers counts and drops + * entries (files with none left, gone, or back on the Cesium list); it never + * adds a file or raises a count. A file over its count is reported and the + * script exits 1: port that access instead. + * + * `--check` reports what it would change without writing, and exits 1 when + * there is anything to lower. + */ +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { + BASELINE, + countedFiles, + currentHits, + readBaseline, + ROOT, +} from '../src/testSupport/viewerAccess.mjs'; + +const check = process.argv.includes('--check'); +const baseline = readBaseline(); +const hits = currentHits(); +const counted = new Set(countedFiles()); + +const next = {}; +const changes = []; +for (const [file, allowed] of Object.entries(baseline)) { + const found = counted.has(file) ? (hits.get(file)?.length ?? 0) : 0; + const count = Math.min(allowed, found); + if (count > 0) next[file] = count; + if (count !== allowed) changes.push(`${file}: ${allowed} → ${count}`); +} +const over = [...hits] + .filter(([file, found]) => found.length > (baseline[file] ?? 0)) + .map( + ([file, found]) => + `${file}: ${found.length} found, ${baseline[file] ?? 0} recorded`, + ); + +if (changes.length) { + console.log( + `${check ? 'Would lower' : 'Lowered'}:\n ${changes.join('\n ')}`, + ); + if (!check) { + const sorted = Object.fromEntries( + Object.keys(next) + .sort() + .map((file) => [file, next[file]]), + ); + writeFileSync( + path.join(ROOT, BASELINE), + `${JSON.stringify(sorted, null, 2)}\n`, + ); + } else process.exitCode = 1; +} else console.log(`${BASELINE} is as low as it goes.`); +if (over.length) { + console.error( + `Over their counts (never raised; port these):\n ${over.join('\n ')}`, + ); + process.exitCode = 1; +} diff --git a/server/providers/transitHistory.test.mjs b/server/providers/transitHistory.test.mjs index 551fee7a70..aeed8308a2 100644 --- a/server/providers/transitHistory.test.mjs +++ b/server/providers/transitHistory.test.mjs @@ -202,3 +202,25 @@ test('a feed fleet-number mode outranks its route mode in the epoch context', (t assert.equal(h.get('ttc', '4507', 100000).epochs[0].mode, 'tram'); assert.equal(h.get('ttc', 'x1', 100000).epochs[0].mode, 'tram'); }); +test('the epoch mode is the live mode: a route type, else hints, else the default', (t) => { + const h = history(t); + const pid = { + id: 'pid', + historyRetention: true, + defaultMode: 'bus', + routeMode: (route) => (route === 'L22' ? 'tram' : 'unknown'), + }; + h.ingest( + pid, + [ + row(100000, 'a', { routeId: 'L58', routeType: 11 }), + row(100000, 'b', { routeId: 'L22' }), + row(100000, 'c', { routeId: 'L9999' }), + ], + 100000, + ); + assert.equal(h.get('pid', 'a', 100000).epochs[0].mode, 'trolleybus'); + assert.equal(h.get('pid', 'b', 100000).epochs[0].mode, 'tram'); + // A hint that knows nothing leaves the default, as the live layer does. + assert.equal(h.get('pid', 'c', 100000).epochs[0].mode, 'bus'); +}); diff --git a/server/providers/vessels/ais-live.js b/server/providers/vessels/ais-live.js index cb1dd36b05..e525763efc 100644 --- a/server/providers/vessels/ais-live.js +++ b/server/providers/vessels/ais-live.js @@ -27,6 +27,8 @@ const AISSTREAM_DEFAULT_MESSAGE_TYPES = [ 'ExtendedClassBPositionReport', 'ShipStaticData', 'StaticDataReport', + // Buoys, beacons and other aids to navigation (AIS message 21). + 'AidsToNavigationReport', ]; // Watchdog budgets (policy lives in src/data/aisWatchdog.js). Silence is // REPORTED quickly and ACTED ON slowly: a dead feed must read as dead within diff --git a/server/providers/vessels/ais-store.js b/server/providers/vessels/ais-store.js index 71cefceed3..6c4d8a57ac 100644 --- a/server/providers/vessels/ais-store.js +++ b/server/providers/vessels/ais-store.js @@ -1,4 +1,8 @@ import { isRecognizedAisEnvelope } from '../../../src/data/aisStreamAdapter.js'; +import { + aidToNavigationTypeName, + isAidToNavigation, +} from '../../../src/data/vesselTypes.js'; export const AISSTREAM_CACHE_MAX = 50000; export const AISSTREAM_STALE_MS = 30 * 60 * 1000; // Per-MMSI recent-path ring buffers (PRD WS-F F3). Float32 lat/lon (~1m @@ -57,8 +61,13 @@ export function ingestAisStreamEnvelope(envelope) { message.ReportB?.Valid === false ? undefined : message.ReportB?.ShipType, + Dimension: + message.ReportB?.Valid === false + ? undefined + : message.ReportB?.Dimension, } : message; + const dimensions = aisDimensions(fields.Dimension); // Static reports may be partial (including Class B's separate A/B parts). // Keep known values in the cache as well as in the current live row. const staticData = { @@ -84,6 +93,8 @@ export function ingestAisStreamEnvelope(envelope) { staticCode(live?.imo) || staticCode(previous.imo) || '', + length: dimensions.length ?? live?.length ?? previous.length ?? null, + beam: dimensions.beam ?? live?.beam ?? previous.beam ?? null, }; _aisStreamStatic.set(mmsi, staticData); mergeAisStaticIntoLiveVessel(mmsi, staticData); @@ -105,14 +116,24 @@ export function ingestAisStreamEnvelope(envelope) { if (!Number.isFinite(lat) || !Number.isFinite(lon)) return true; const staticData = _aisStreamStatic.get(mmsi) || {}; + const aidReport = messageType === 'AidsToNavigationReport'; _aisStreamVessels.set(mmsi, { lat, lon, - name: vesselNameFromAis(metadata, message, staticData) || `MMSI ${mmsi}`, + name: + (aidReport && aidNameFromAis(message)) || + vesselNameFromAis(metadata, message, staticData) || + `MMSI ${mmsi}`, mmsi, imo: stringValue(message.ImoNumber ?? message.IMO ?? staticData.imo), - type: vesselTypeFromAis(message, staticData), + // An aid-to-navigation report's type is the kind of aid (0 to 31), not + // a ship type: it is carried as the aid's name ("Cardinal Mark N"). + type: aidReport + ? aidToNavigationTypeName(message.Type) + : vesselTypeFromAis(message, staticData), destination: stringValue(message.Destination ?? staticData.destination), + length: staticData.length ?? null, + beam: staticData.beam ?? null, speed: normalizedSpeedOverGround(message.Sog ?? message.SOG), course: normalizedCourseOverGround(message.Cog ?? message.COG), heading: normalizedHeading(message.TrueHeading ?? message.Heading), @@ -122,6 +143,9 @@ export function ingestAisStreamEnvelope(envelope) { // Use the AIS message's own report time, not server ingest wall-clock — // trail spacing and dead reckoning depend on true fix epochs. last_position_epoch: aisEpochSeconds(metadata.time_utc ?? metadata.TimeUtc), + // A virtual aid is broadcast where nothing physical stands. Only such a + // row carries the field, so ship rows stay their size. + ...(aidReport && message.VirtualAtoN === true && { virtual: true }), _updatedAt: Date.now(), }); @@ -236,6 +260,25 @@ function mergeAisStaticIntoLiveVessel(mmsi, staticData) { if (staticData.type) existing.type = staticData.type; if (staticData.destination) existing.destination = staticData.destination; if (staticData.imo) existing.imo = staticData.imo; + if (staticData.length) existing.length = staticData.length; + if (staticData.beam) existing.beam = staticData.beam; +} + +/** + * A static report's hull size from its AIS dimensions: the antenna's + * distances to bow (A), stern (B), port (C) and starboard (D), in metres. + * Zero is AIS's "not available", so a side missing its two parts has none. + * @param {{A?: number, B?: number, C?: number, D?: number}|undefined} dimension + * @returns {{length: number|null, beam: number|null}} + */ +function aisDimensions(dimension) { + const part = (value) => { + const number = numberValue(value); + return number !== null && number > 0 ? number : 0; + }; + const length = part(dimension?.A) + part(dimension?.B); + const beam = part(dimension?.C) + part(dimension?.D); + return { length: length > 0 ? length : null, beam: beam > 0 ? beam : null }; } function vesselNameFromAis(metadata, message, staticData = {}) { @@ -248,6 +291,15 @@ function vesselNameFromAis(metadata, message, staticData = {}) { ); } +/** + * An aid's whole name: an aid-to-navigation report carries the first 20 + * characters in `Name` and the rest, up to 14 more, in `NameExtension`. + */ +function aidNameFromAis(message) { + const name = stringValue(message.Name); + return name ? stringValue(name + stringValue(message.NameExtension)) : ''; +} + function vesselTypeFromAis(message, staticData = {}) { return stringValue( message.Type ?? @@ -257,14 +309,25 @@ function vesselTypeFromAis(message, staticData = {}) { ); } +/** + * The current rows, newest first, with every vessel ahead of every aid to + * navigation: a capped request never gives up a ship for a buoy. + */ export function aisStreamRows(maxRows) { const cutoff = Date.now() - AISSTREAM_STALE_MS; - const rows = []; + const vessels = []; + const aids = []; for (const row of _aisStreamVessels.values()) { - if (row._updatedAt >= cutoff) rows.push(row); + if (row._updatedAt >= cutoff) + (isAidToNavigation(row) ? aids : vessels).push(row); } - rows.sort((a, b) => b._updatedAt - a._updatedAt); - return rows.slice(0, maxRows).map(({ _updatedAt, ...row }) => row); + const newestFirst = (a, b) => b._updatedAt - a._updatedAt; + vessels.sort(newestFirst); + if (vessels.length < maxRows) aids.sort(newestFirst); + return vessels + .concat(aids) + .slice(0, maxRows) + .map(({ _updatedAt, ...row }) => row); } function pruneAisStreamCache() { diff --git a/server/standalone/conformance-references.js b/server/standalone/conformance-references.js new file mode 100644 index 0000000000..669fef616a --- /dev/null +++ b/server/standalone/conformance-references.js @@ -0,0 +1,59 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +const DIR = fileURLToPath( + new URL('../../src/render/conformance/goldens/visual/', import.meta.url), +); +const NAME = /^[a-z0-9-]+\.(png|json)$/; +const MAX_BYTES = 8 * 1024 * 1024; + +/** + * Dev server only: lets `/dev/conformance/` save the visual references it + * records into `src/render/conformance/goldens/visual/`. Takes a PUT of one + * PNG or the manifest, named in the path; nothing else is written. + */ +export function conformanceReferencesPlugin() { + return { + name: 'conformance-references', + apply: 'serve', + configureServer(server) { + server.middlewares.use('/__conformance/references/', (req, res) => { + const name = decodeURIComponent((req.url ?? '').replace(/^\//, '')); + // Only the page on this machine: a loopback peer, sent from the + // dev server's own origin. + const peer = req.socket.remoteAddress ?? ''; + const loopback = /^(127\.|::1$|::ffff:127\.)/.test(peer); + let sameOrigin = false; + try { + sameOrigin = new URL(req.headers.origin).host === req.headers.host; + } catch { + // No Origin, or not a URL. + } + if (!loopback || !sameOrigin) { + res.writeHead(403).end(); + return; + } + if (req.method !== 'PUT' || !NAME.test(name)) { + res.writeHead(400).end(); + return; + } + const chunks = []; + let size = 0; + req.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_BYTES) req.destroy(); + else chunks.push(chunk); + }); + req.on('end', async () => { + try { + await mkdir(DIR, { recursive: true }); + await writeFile(DIR + name, Buffer.concat(chunks)); + res.writeHead(204).end(); + } catch (error) { + res.writeHead(500).end(String(error?.message ?? error)); + } + }); + }); + }, + }; +} diff --git a/server/standalone/vite.config.js b/server/standalone/vite.config.js index 76d26ba5d2..f660bfbd33 100644 --- a/server/standalone/vite.config.js +++ b/server/standalone/vite.config.js @@ -5,6 +5,7 @@ import { createBrowserViteConfig } from '../../build/vite.js'; import { localProviderPlugins } from '../providers/local.js'; import { localMcpPlugin } from '../mcp/plugin.js'; import { apiNotFoundPlugin } from './api-not-found.js'; +import { conformanceReferencesPlugin } from './conformance-references.js'; import { googleTokenUnavailablePlugin } from './google-token-unavailable.js'; import { standaloneVoiceTools } from './voiceTools.js'; import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js'; @@ -30,6 +31,7 @@ export function standaloneConfig( }), localMcpPlugin(), googleTokenUnavailablePlugin(), + conformanceReferencesPlugin(), apiNotFoundPlugin(), unwatchedRuntimeDirsPlugin(), ], diff --git a/src/agent/worldPacket.js b/src/agent/worldPacket.js index 4f8dad144c..9217bd9b39 100644 --- a/src/agent/worldPacket.js +++ b/src/agent/worldPacket.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { findCamera } from '../render/rendererOf.js'; import { feedProvenanceEnvelope, layerSnapshot, @@ -104,14 +104,12 @@ export function getWorldPacket(options = {}) { // A default parameter only covers undefined; null or NaN would age every // feed against the epoch and report stale data as "just now". const now = Number.isFinite(requestedNow) ? requestedNow : Date.now(); - if (!viewer?.camera?.positionWC) - throw new TypeError('World Packet requires a viewer camera'); + const pose = findCamera(viewer)?.pose(); + if (!pose) throw new TypeError('World Packet requires a viewer camera'); if (!dataManager || typeof dataManager.getAll !== 'function') throw new TypeError('World Packet requires a data manager'); - const cartographic = Cesium.Cartographic.fromCartesian( - viewer.camera.positionWC, - ); + const eye = { lon: pose.lon, lat: pose.lat, height: pose.height }; // Read the roster once. Voice must not rewalk disabled layers: preserving the // current enabled-only view keeps the model's context budget bounded. const rows = dataManager.getAll(); @@ -126,9 +124,9 @@ export function getWorldPacket(options = {}) { ok: true, action: 'get_current_view_state', camera: { - latitude: Cesium.Math.toDegrees(cartographic.latitude), - longitude: Cesium.Math.toDegrees(cartographic.longitude), - heightM: cartographic.height, + latitude: eye.lat, + longitude: eye.lon, + heightM: eye.height, }, style: styleManager?.activeStyle || 'normal', context: contextState diff --git a/src/agent/worldPacket.test.mjs b/src/agent/worldPacket.test.mjs index 063e3652c2..a10b407da6 100644 --- a/src/agent/worldPacket.test.mjs +++ b/src/agent/worldPacket.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { getWorldPacket } from './worldPacket.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { createStubRenderer } from '../render/stub/index.js'; import { createGevActionRunner } from '../voice/gevActions.js'; function withoutVoicePresentation(result) { @@ -18,6 +20,9 @@ function harness() { const viewer = { trackedEntity: undefined, clock: { onTick: { addEventListener: () => () => {} } }, + get canvas() { + return this.scene.canvas; + }, scene: { canvas: { clientWidth: 1200, @@ -60,6 +65,14 @@ function harness() { getCockpitState: () => null, getControlState: () => ({ hud: { visible: 'auto' } }), }; + // The packet reads the eye from the camera port of the renderer bound to + // the scene object. + const renderer = createStubRenderer(); + renderer.camera.setView({ + destination: { lon: -97.74, lat: 30.26, height: 500 }, + orientation: { heading: 0, pitch: Cesium.Math.toRadians(-45), roll: 0 }, + }); + bindRenderer(viewer, renderer); return { viewer, dataManager, styleManager }; } diff --git a/src/annotations/adminOutline.test.mjs b/src/annotations/adminOutline.test.mjs index 2028fe711f..4bb5cba35e 100644 --- a/src/annotations/adminOutline.test.mjs +++ b/src/annotations/adminOutline.test.mjs @@ -4,11 +4,13 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js'; import { createAnnotationResolver } from './resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { createAnnotationEngine } from './annotationEngine.js'; import { _resetRenderGovernorForTest } from '../renderGovernor.js'; function viewerAt(lat, lon, height = 20_000) { - return { + // The resolver reads the camera through the renderer's camera port. + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: (lat * Math.PI) / 180, @@ -16,7 +18,7 @@ function viewerAt(lat, lon, height = 20_000) { height, }, }, - }; + }); } /** A resolver whose boundary lookups and geocoder record every call. */ diff --git a/src/annotations/annotationEngine.js b/src/annotations/annotationEngine.js index c8cda0bf0d..352d65f4fd 100644 --- a/src/annotations/annotationEngine.js +++ b/src/annotations/annotationEngine.js @@ -1,6 +1,9 @@ import { isUnavailableCapability } from '../sources/capability.js'; import { defaultGeospatial } from '../search/defaults.js'; -import * as Cesium from 'cesium'; +import { cameraOf, findCamera, findQuery } from '../render/rendererOf.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { sphereFromPoints } from '../geo/sphere.js'; +import { distance, toRadians } from '../geo/vector.js'; import { greatCircleMeters } from '../geoDistance.js'; import { holdContinuousRender, @@ -20,11 +23,6 @@ import { } from '../sources/phaseTiming.js'; import { formatDistanceText } from '../data/distanceFormat.js'; -// Dev convenience: expose the app's Cesium instance for console/preview probing -// (single shared module instance — avoids dual-Cesium state bugs when testing). -if (typeof window !== 'undefined' && !window.__CESIUM__) - window.__CESIUM__ = Cesium; - /** * Annotation engine — the voice agent's "whiteboard" over the 3D world. * @@ -1717,18 +1715,20 @@ export function createAnnotationEngine({ frameAnnotation(marks[0]); return; } - const cart = points.map((p) => - Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0), + const cart = points.map((p) => fromDegrees(p.lon, p.lat, p.height || 0)); + const sphere = sphereFromPoints(cart); + const camera = cameraOf(viewer); + camera.flyToBounds( + { center: sphere.center, radius: sphere.radius }, + { + offset: { + heading: camera.pose().heading, + pitch: toRadians(-35), + range: Math.max(900, sphere.radius * 2.6), + }, + durationS: 1.6, + }, ); - const sphere = Cesium.BoundingSphere.fromPoints(cart); - viewer.camera.flyToBoundingSphere(sphere, { - offset: new Cesium.HeadingPitchRange( - viewer.camera.heading, - Cesium.Math.toRadians(-35), - Math.max(900, sphere.radius * 2.6), - ), - duration: 1.6, - }); } catch { /* camera assist is best-effort */ } @@ -1738,23 +1738,35 @@ export function createAnnotationEngine({ * globe. On any API hiccup, report visible — bad data must never move the camera. */ function isPointOnScreen(p) { try { - const camera = viewer.camera; - const pos = Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0); - const cv = camera.frustum.computeCullingVolume( - camera.position, - camera.direction, - camera.up, - ); - if ( - cv.computeVisibility(new Cesium.BoundingSphere(pos, 1)) === - Cesium.Intersect.OUTSIDE - ) - return false; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - camera.position, - ); - return occluder.isPointVisible(pos); + const camera = findCamera(viewer); + const query = findQuery(viewer); + if (!camera || !query) return true; + const pos = fromDegrees(p.lon, p.lat, p.height || 0); + // Inside the view frustum: a 1 m sphere at the point is not wholly + // outside any of its six planes, read off the view-projection (depth + // runs -1..1). An invalid matrix measures no distance and reads as + // visible. + const { view, projection } = camera.matrices(); + const m = new Float64Array(16); + for (let col = 0; col < 4; col++) + for (let row = 0; row < 4; row++) { + let sum = 0; + for (let k = 0; k < 4; k++) + sum += projection[k * 4 + row] * view[col * 4 + k]; + m[col * 4 + row] = sum; + } + const at = (row, col) => m[col * 4 + row]; + for (const [axis, sign] of FRUSTUM_PLANES) { + const a = at(3, 0) + sign * at(axis, 0); + const b = at(3, 1) + sign * at(axis, 1); + const c = at(3, 2) + sign * at(axis, 2); + const d = at(3, 3) + sign * at(axis, 3); + const distanceM = + (a * pos.x + b * pos.y + c * pos.z + d) / Math.hypot(a, b, c); + if (distanceM < -1) return false; + } + // On the near side of the globe. + return !query.isOccluded(pos); } catch { return true; } @@ -1778,22 +1790,23 @@ export function createAnnotationEngine({ : anno.ring, ) : viewportRange(anno.viewport) || 600; - viewer.camera.flyToBoundingSphere( - new Cesium.BoundingSphere( - Cesium.Cartesian3.fromDegrees( - target.lon, - target.lat, - anno.anchor.height || 0, - ), - range, - ), + const camera = cameraOf(viewer); + camera.flyToBounds( { - offset: new Cesium.HeadingPitchRange( - viewer.camera.heading, - Cesium.Math.toRadians(-35), - range * 2.4, - ), - duration: 1.8, + center: { + lon: target.lon, + lat: target.lat, + height: anno.anchor.height || 0, + }, + radius: range, + }, + { + offset: { + heading: camera.pose().heading, + pitch: toRadians(-35), + range: range * 2.4, + }, + durationS: 1.8, }, ); } catch { @@ -2005,15 +2018,17 @@ export function createAnnotationEngine({ }) { if (destroyed) return; try { - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees(lon, lat, height), - orientation: { - heading: Cesium.Math.toRadians(heading), - pitch: Cesium.Math.toRadians(pitch), - roll: 0, + cameraOf(viewer).flyTo( + { lon, lat, height }, + { + orientation: { + heading: toRadians(heading), + pitch: toRadians(pitch), + roll: 0, + }, + durationS: duration, }, - duration, - }); + ); } catch { /* camera flight best-effort */ } @@ -2175,13 +2190,23 @@ function pendingAnimation(anno, now) { // fly_to_location natural-region heuristic uses (owner field test 2026-07-23). const VIEWPORT_ASSIST_RANGE_CAP_M = 120000; +/** The view frustum's planes as `row 3 ± row axis` of the view-projection. */ +const FRUSTUM_PLANES = [ + [0, 1], + [0, -1], + [1, 1], + [1, -1], + [2, 1], + [2, -1], +]; + /** flyTo range from a Places viewport box (low/high lat-lng corners), or null. */ function viewportRange(vp) { if (!vp?.low || !vp?.high) return null; try { - const span = Cesium.Cartesian3.distance( - Cesium.Cartesian3.fromDegrees(vp.low.longitude, vp.low.latitude), - Cesium.Cartesian3.fromDegrees(vp.high.longitude, vp.high.latitude), + const span = distance( + fromDegrees(vp.low.longitude, vp.low.latitude), + fromDegrees(vp.high.longitude, vp.high.latitude), ); return Number.isFinite(span) && span > 0 ? Math.max(300, Math.min(span * 0.7, VIEWPORT_ASSIST_RANGE_CAP_M)) @@ -2206,9 +2231,9 @@ function ringRange(ring) { if (lon < minLon) minLon = lon; if (lon > maxLon) maxLon = lon; } - const span = Cesium.Cartesian3.distance( - Cesium.Cartesian3.fromDegrees(minLon, minLat), - Cesium.Cartesian3.fromDegrees(maxLon, maxLat), + const span = distance( + fromDegrees(minLon, minLat), + fromDegrees(maxLon, maxLat), ); return Math.max(300, span * 0.7); } diff --git a/src/annotations/annotationEngine.test.mjs b/src/annotations/annotationEngine.test.mjs index da7e4ae06d..c545ac988c 100644 --- a/src/annotations/annotationEngine.test.mjs +++ b/src/annotations/annotationEngine.test.mjs @@ -1,3 +1,4 @@ +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { createStandalonePlaceSearch } from '../standalone/placeSearch.js'; // Voice-annotation resilience contract tests — pure logic, no network, no browser. // @@ -25,6 +26,7 @@ import { installRenderGovernor, _resetRenderGovernorForTest, } from '../renderGovernor.js'; +import { framePortFor } from '../testSupport/fakeFramePort.mjs'; // A resolver that replays a scripted sequence of outcomes (undefined = transient, // null = definitive miss, object = footprint) and counts its invocations. @@ -1471,7 +1473,7 @@ test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and const { renderer, calls } = fakeRenderer(); const flights = []; const engine = createAnnotationEngine({ - viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }, + viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }), renderer, }); let changes = 0; @@ -1540,12 +1542,12 @@ test('hand-drawn marks: remove, hide, clear, expiry and framing have their effec const { renderer, calls } = fakeRenderer(); const flights = []; const engine = createAnnotationEngine({ - viewer: { + viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere), }, - }, + }), renderer, }); let changes = 0; @@ -1757,7 +1759,7 @@ test('hand-drawn marks: with every mark hidden the scene idles, and showing one _resetRenderGovernorForTest(); t.after(() => _resetRenderGovernorForTest()); let renders = 0; - installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } }); + installRenderGovernor(framePortFor({ requestRenderMode: true, requestRender: () => (renders += 1) })); const { renderer } = fakeRenderer(); const engine = createAnnotationEngine({ viewer: {}, renderer }); await engine.annotate([ @@ -1898,3 +1900,67 @@ test('plain recaption keeps the old mark addressable when its removal throws', a ); assert.equal(engine.count(), 0); }); + +// The camera assist frames a fresh mark only when none of it is in view: +// off the frustum or behind the globe, as the renderer's camera and query +// ports see it. A camera that cannot answer leaves the view alone. +test('camera assist frames marks out of view and leaves visible ones alone', async (t) => { + installAnimationFrameStubs(t); + const { bindRenderer } = await import('../render/rendererOf.js'); + const { horizonFrom } = await import('../geo/horizon.js'); + const viewerOver = (lon, lat, height, { broken = false } = {}) => { + const position = Cesium.Cartesian3.fromDegrees(lon, lat, height); + const direction = Cesium.Cartesian3.negate( + Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const right = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(direction, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()); + const view = Cesium.Matrix4.computeView(position, direction, up, right, new Cesium.Matrix4()); + const frustum = new Cesium.PerspectiveFrustum({ + fov: Cesium.Math.toRadians(60), aspectRatio: 16 / 9, near: 1, far: 5e7, + }); + const flights = []; + const viewer = {}; + const horizon = horizonFrom(position); + bindRenderer(viewer, { + camera: { + pose: () => ({ heading: 0 }), + matrices() { + if (broken) throw new Error('no camera'); + return { + view: Float64Array.from(Cesium.Matrix4.toArray(view)), + projection: Float64Array.from(Cesium.Matrix4.toArray(frustum.projectionMatrix)), + }; + }, + flyTo: (...args) => flights.push(['flyTo', ...args]), + flyToBounds: (...args) => flights.push(['flyToBounds', ...args]), + }, + query: { isOccluded: (p) => !horizon.isPointVisible(p) }, + }); + return { viewer, flights }; + }; + const pinAt = async (viewer, lon, lat) => { + const engine = createAnnotationEngine({ viewer, renderer: fakeRenderer().renderer }); + await engine.annotate([{ type: 'pin', manual: true, latitude: lat, longitude: lon }], { persist: true, flyTo: false }); + }; + + const inView = viewerOver(-97.74, 30.27, 9000); + await pinAt(inView.viewer, -97.742, 30.268); + assert.equal(inView.flights.length, 0, 'a mark in view is left alone'); + + const aside = viewerOver(-97.74, 30.27, 9000); + await pinAt(aside.viewer, -97.5, 30.6); + assert.equal(aside.flights.length, 1, 'a mark off the frustum is framed'); + + const behind = viewerOver(60, 30, 9_000_000); + await pinAt(behind.viewer, -120, -30); + assert.equal(behind.flights.length, 1, 'a mark behind the globe is framed'); + + const broken = viewerOver(-97.74, 30.27, 9000, { broken: true }); + await pinAt(broken.viewer, -97.5, 30.6); + assert.equal(broken.flights.length, 0, 'a camera that cannot answer moves nothing'); +}); diff --git a/src/annotations/annotationResolver.test.mjs b/src/annotations/annotationResolver.test.mjs index 2c51213c19..acd84e878e 100644 --- a/src/annotations/annotationResolver.test.mjs +++ b/src/annotations/annotationResolver.test.mjs @@ -13,6 +13,7 @@ import { createPlaceSearch } from '../search/placeSearch.js'; // Run with: npm test (node --test) import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { resolveAnnotationTarget as resolveTarget, selectFootprint, @@ -157,7 +158,8 @@ test('refineScope: entityKind refines only an unresolved (auto) scope', () => { }); function closeViewportViewer() { - return { + // The resolver reads the camera through the renderer's camera port. + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: 30.2672 * Math.PI / 180, @@ -165,7 +167,7 @@ function closeViewportViewer() { height: 1000, }, }, - }; + }); } function geocodePayload({ lat, lon, types, label }) { @@ -369,11 +371,11 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township // Synthetic footprints reproduce the real Capitol/YOTEL selection without live APIs. const CAPITOL_ANCHOR = { lat: 38.8899389, lon: -77.0090505 }; function capitolViewer() { - return { camera: { positionCartographic: { + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: CAPITOL_ANCHOR.lat * Math.PI / 180, longitude: CAPITOL_ANCHOR.lon * Math.PI / 180, height: 1000, - } } }; + } } }); } function installCapitolMocks(t, elements, components = [ { long_name: 'Washington', types: ['locality', 'political'] }, diff --git a/src/annotations/drawTool.js b/src/annotations/drawTool.js index f44d30753d..b1f8d1d05a 100644 --- a/src/annotations/drawTool.js +++ b/src/annotations/drawTool.js @@ -1,5 +1,5 @@ /** - * Manual whiteboard drawing: the Cesium + DOM half. + * Manual whiteboard drawing: the scene + DOM half. * * UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a * shape (area, line or pin) and a colour, click the vertices on the real world, @@ -15,12 +15,13 @@ * (`src/data/inputOwnership.js`), and every ambient selection handler yields, * so a vertex clicked on top of an aircraft or a camera is a vertex and * nothing else. It is one claim consulted by all of them, not a list of - * exceptions inside each. + * exceptions inside each. Turning Draw on takes the pointer from any tool + * holding it; a newer tool taking it turns Draw off. * - Cesium's Viewer binds its OWN left click (select the entity under the * pointer) and double click (track it) on the viewer's handler, outside every - * layer and therefore outside the shared claim. Both are borrowed for the + * layer and therefore outside the shared claim. Both are suppressed for the * session and given back on the way out, and `destroy()` gives back every - * listener, the Cesium handler, the preview data source and the window + * listener, the pointer subscriptions, the preview draw sets and the window * handle, so the tool can be turned off or the shell disposed without leaving * anything behind. * @@ -30,14 +31,13 @@ * drapes finished areas and routes onto the surface, so the height is dropped * at finish, deliberately and in one place — see `finishSpec` in drawMode.js. */ -import * as Cesium from 'cesium'; import { pickWorldFromScreen } from './annotationResolver.js'; import { claimPointer, pointerOwner, releasePointer, } from '../data/inputOwnership.js'; -import { pointerOwnerName } from '../data/pointerOwnerNames.js'; +import { inputFor } from '../input/dispatcher.js'; import { DRAW_SHAPES, MAX_VERTICES, @@ -59,7 +59,14 @@ import { presentDrawMarks, } from './drawMarks.js'; -import { onLocaleChange, t, translateKnown } from '../i18n/index.js'; +import { onLocaleChange, t } from '../i18n/index.js'; +import { fromDegrees } from '../geo/index.js'; +import { cssColor } from '../render/color.js'; +import { + canvasOf as sceneCanvasOf, + drawOf, + findFrame, +} from '../render/rendererOf.js'; /** The longest note a row action leaves under its row, in characters. */ const NOTE_MAX = 200; /** An action's answer as a row note: trimmed, and cut at a word with an ellipsis. */ @@ -74,7 +81,15 @@ function noteText(text) { /** The id this tool claims the pointer under. */ const DRAW_POINTER_OWNER = 'draw'; -const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview'; +/** Each tool's preview sets get their own ids. */ +let previewSerial = 0; +/** + * Preview sets drawn on each viewer by its live tools, so a tool left + * undestroyed beside its replacement shows up in `diagnostics()`. + */ +const livePreviewSets = new WeakMap(); +const countPreviewSets = (viewer, delta) => + livePreviewSets.set(viewer, (livePreviewSets.get(viewer) ?? 0) + delta); const PREVIEW = DRAW_COLOR_CSS; @@ -89,7 +104,7 @@ const PREVIEW = DRAW_COLOR_CSS; * `markActions` are the application's own buttons on an area's or a line's * row (drawMarks.js `drawMarkActions`); a press runs the action with the * shape's id, kind, name and geometry (drawMarks.js `drawMarkGeometry`). - * @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps + * @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps * @returns {{destroy: Function}|null} */ export function initDrawTool({ @@ -115,16 +130,13 @@ export function initDrawTool({ let shape = 'area'; let color = 'primary'; let hint = ''; - let handler = null; + let unbindScene = null; let lease = null; - let savedDoubleClick = null; - let savedSingleClick = null; let cursor = null; // last mouse position on the canvas, for the rubber band // Bumped by anything that supersedes an in-flight finish: cancelling, clearing // the board, leaving draw mode, teardown. An `annotate()` that resolves after // one of those must not write its outcome over the newer state. let generation = 0; - const previewEntities = []; // Every DOM listener this tool adds (the session's keydown), so teardown is // one loop rather than a list that can fall out of step with the bindings. const domListeners = []; @@ -133,14 +145,26 @@ export function initDrawTool({ domListeners.push([target, type, listener, options]); }; - const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME); - // `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would - // remove a source that had not been attached yet and leave the attachment to - // land afterwards — a preview data source nobody owns. Chain the removal onto - // the attachment instead of racing it. - let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch( - () => null, - ); + // The preview: one dashed rubber band and a dot per vertex, drawn through + // the renderer's draw port. Both sets live as long as the tool. + const draw = drawOf(viewer); + const previewId = `draw-preview:${++previewSerial}`; + const previewLines = draw.lines({ id: `${previewId}:line` }); + const previewPoints = draw.points({ id: `${previewId}:vertices` }); + countPreviewSets(viewer, 2); + let previewReleased = false; + const releasePreview = () => { + if (previewReleased) return; + previewReleased = true; + countPreviewSets(viewer, -2); + previewLines.dispose(); + previewPoints.dispose(); + }; + /** The canvas the renderer draws in (the viewer's own when none is bound). */ + const canvasOf = () => sceneCanvasOf(viewer); + const requestRender = () => findFrame(viewer)?.requestRender('draw-preview'); + // Teardown finishes synchronously; `whenSettled()` keeps its promise. + const attaching = Promise.resolve(); const present = () => { const marks = annotations.list?.() || []; @@ -169,70 +193,71 @@ export function initDrawTool({ // ---- preview --------------------------------------------------------- const vertexPositions = () => - session.vertices.map((v) => - Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0), - ); - const previewLine = dataSource.entities.add({ - show: false, - polyline: { - positions: new Cesium.CallbackProperty(() => { - if (!session) return []; - const pts = vertexPositions(); - if (cursor && session.shape !== 'pin') pts.push(cursor); - if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]); - return pts; - }, false), - width: 3, - material: new Cesium.PolylineDashMaterialProperty({ - color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9), - dashLength: 16, - }), - depthFailMaterial: new Cesium.PolylineDashMaterialProperty({ - color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35), - dashLength: 16, - }), - clampToGround: false, - }, - }); - const syncPreview = () => { + session.vertices.map((v) => fromDegrees(v.lon, v.lat, v.height || 0)); + /** The rubber band, from the vertices to the pointer (and closed for an area). */ + const syncPreviewLine = () => { if (destroyed) return; - previewEntities.forEach((e) => dataSource.entities.remove(e)); - previewEntities.length = 0; - if (!session) { - previewLine.show = false; - setHint(() => drawHint(null)); - viewer.scene.requestRender(); + if (!session || session.shape === 'pin') { + previewLines.clear(); return; } - const stroke = Cesium.Color.fromCssColorString( - PREVIEW[color] || PREVIEW.primary, - ); - previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({ - color: stroke.withAlpha(0.9), - dashLength: 16, - }); - previewLine.show = session.shape !== 'pin'; - for (const v of session.vertices) { - previewEntities.push( - dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0), - point: { - pixelSize: 8, - color: stroke, - outlineColor: Cesium.Color.BLACK.withAlpha(0.6), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }), - ); + const pts = vertexPositions(); + if (cursor) pts.push(cursor); + if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]); + if (pts.length < 2) { + previewLines.clear(); + return; } + previewLines.upsert([ + { + id: 'band', + positions: pts, + widthPx: 3, + // Along the ellipsoid between vertices, as the entity polyline was. + mode: 'geodesic', + style: { + kind: 'dash', + color: withAlpha(cssColor(PREVIEW[color] || PREVIEW.primary), 0.9), + length: 16, + }, + // Dashed behind the surface too, as the band in front of it is. + depthFail: { + kind: 'dash', + color: withAlpha(cssColor(PREVIEW.primary), 0.35), + length: 16, + }, + }, + ]); + }; + const syncPreview = () => { + if (destroyed) return; + if (!session) { + previewPoints.clear(); + previewLines.clear(); + setHint(() => drawHint(null)); + requestRender(); + return; + } + const stroke = cssColor(PREVIEW[color] || PREVIEW.primary); + previewPoints.set( + session.vertices.map((v, index) => ({ + id: String(index), + pos: { lon: v.lon, lat: v.lat, height: v.height || 0 }, + pixelSize: 8, + color: stroke, + outlineColor: [0, 0, 0, 0.6], + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, + })), + ); + syncPreviewLine(); setHint(() => drawHint(session)); - viewer.scene.requestRender(); + requestRender(); }; // ---- vertices from clicks -------------------------------------------- const worldAt = (position) => { - const canvas = viewer.scene.canvas; + const canvas = canvasOf(); const w = canvas.clientWidth || canvas.width || 1; const h = canvas.clientHeight || canvas.height || 1; return pickWorldFromScreen(viewer, position.x / w, position.y / h); @@ -260,11 +285,12 @@ export function initDrawTool({ }; const onMove = (event) => { if (!session || session.shape === 'pin' || destroyed) return; - const p = worldAt(event.endPosition); - cursor = p - ? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0) - : null; - viewer.scene.requestRender(); + // The click's own position is sensor-corrected; the rubber band must + // follow the same point the click would place. + const p = worldAt(event.pickPosition ?? event.endPosition); + cursor = p ? fromDegrees(p.lon, p.lat, p.height || 0) : null; + syncPreviewLine(); + requestRender(); }; // ---- finish / cancel ------------------------------------------------- @@ -344,9 +370,7 @@ export function initDrawTool({ t.closest('button, a, select, [role="button"], [role="radio"]') ) return false; - return ( - t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS' - ); + return t === document.body || t === canvasOf() || t.tagName === 'CANVAS'; }; const onKey = (event) => { if (!active || destroyed || typingElsewhere(event)) return; @@ -383,18 +407,15 @@ export function initDrawTool({ function setActive(next) { if (destroyed || next === active) return active; if (next) { - lease = claimPointer(DRAW_POINTER_OWNER); - if (!lease) { - // Somebody else is using the pointer — possibly an older instance of - // this same tool that has not finished tearing down. Say so instead of - // half-starting. - setHint(() => - t('{owner} is using the pointer — close it first.', { - owner: translateKnown(pointerOwnerName(pointerOwner())), - }), - ); - return active; - } + // The newest claim takes over: a tool holding the pointer is told and + // turns itself off, and a newer one turns Draw off as if the person had. + const claimed = claimPointer(DRAW_POINTER_OWNER, { + onLost: () => { + if (lease === claimed) setActive(false); + }, + }); + if (!claimed) return active; + lease = claimed; } active = next; present(); @@ -416,50 +437,29 @@ export function initDrawTool({ } function bindSceneHandler() { - if (handler) return; - handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); - handler.setInputAction(onClick, Cesium.ScreenSpaceEventType.LEFT_CLICK); - handler.setInputAction(onMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE); - handler.setInputAction(() => { - void finish(); - }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); - // Cesium's Viewer binds BOTH stock click actions on its own handler: the - // single click picks an entity into `viewer.selectedEntity`, the double - // click tracks it. Neither goes through a layer, so neither can be fixed by - // the shared pointer claim — they have to be borrowed outright for the - // session and given back on the way out. Borrowing the single click is what - // stops a vertex placed on a contact from also selecting it. - const stock = viewer.screenSpaceEventHandler; - savedSingleClick = - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null; - savedDoubleClick = - stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) || - null; - stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK); - stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); + if (unbindScene) return; + const input = inputFor(viewer); + const held = { lease: () => lease }; + const offs = [ + input.onPointer('click', onClick, held), + input.onPointer('move', onMove, held), + input.onPointer('dblclick', () => void finish(), held), + // Cesium's Viewer binds BOTH stock click actions on its own handler: the + // single click picks an entity into `viewer.selectedEntity`, the double + // click tracks it. Neither goes through a layer, so neither yields to the + // shared pointer claim — they are suppressed for the session and given + // back on the way out. Suppressing the single click is what stops a + // vertex placed on a contact from also selecting it. + input.suppressStockClicks(), + ]; + unbindScene = () => offs.forEach((off) => off()); listen(document, 'keydown', onKey, true); } function releaseSceneHandler() { - if (handler) { - handler.destroy(); - handler = null; - } - if (savedSingleClick) { - viewer.screenSpaceEventHandler.setInputAction( - savedSingleClick, - Cesium.ScreenSpaceEventType.LEFT_CLICK, - ); - savedSingleClick = null; - } - if (savedDoubleClick) { - viewer.screenSpaceEventHandler.setInputAction( - savedDoubleClick, - Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, - ); - savedDoubleClick = null; - } - // Drop the keydown listener bound alongside this handler. + unbindScene?.(); + unbindScene = null; + // Drop the keydown listener bound alongside the pointer subscriptions. for (let i = domListeners.length - 1; i >= 0; i -= 1) { const [target, type, listener, options] = domListeners[i]; if (listener !== onKey) continue; @@ -608,26 +608,18 @@ export function initDrawTool({ return { active, destroyed, - sceneHandler: Boolean(handler), + sceneHandler: Boolean(unbindScene), domListeners: domListeners.length, - previewDataSources: countPreviewDataSources(viewer), - previewEntities: destroyed ? 0 : dataSource.entities.values.length, + // Every live tool's on this viewer: 2 while one tool lives. + previewSets: livePreviewSets.get(viewer) ?? 0, + previewItems: previewReleased + ? 0 + : previewLines.size() + previewPoints.size(), pointerOwner: pointerOwner(), - // The viewer's OWN click actions. While a session is open both are - // borrowed (absent here); after it closes both are back. A harness can - // compare the restored functions by identity with what it captured - // before, which is the only way to prove they were given back rather - // than replaced. - stockSingleClick: Boolean( - viewer.screenSpaceEventHandler?.getInputAction?.( - Cesium.ScreenSpaceEventType.LEFT_CLICK, - ), - ), - stockDoubleClick: Boolean( - viewer.screenSpaceEventHandler?.getInputAction?.( - Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, - ), - ), + // The viewer's own select and follow, which the input port runs: off + // while a session is open, back on after it closes. + stockSingleClick: inputFor(viewer).stockEnabled('select'), + stockDoubleClick: inputFor(viewer).stockEnabled('dblclickFollow'), }; }, /** Resolves once every deferred teardown step has run. */ @@ -649,18 +641,7 @@ export function initDrawTool({ for (const [target, type, listener, options] of domListeners.splice(0)) { target.removeEventListener(type, listener, options); } - previewEntities.length = 0; - dataSource.entities.removeAll(); - // Wait for the pending add() before removing: a destroy() in the same - // tick as init would otherwise remove nothing and let the attachment land - // behind it. - attaching = attaching.then(() => { - try { - viewer.dataSources.remove(dataSource, true); - } catch { - /* viewer already disposed — nothing to detach from */ - } - }); + releasePreview(); document.body.classList.remove('gev-drawing'); hint = ''; present(); @@ -672,13 +653,7 @@ export function initDrawTool({ return api; } -/** How many draw previews are attached — more than one means a leaked tool. */ -function countPreviewDataSources(viewer) { - const sources = viewer?.dataSources; - if (!sources) return 0; - let found = 0; - for (let index = 0; index < sources.length; index += 1) { - if (sources.get(index)?.name === PREVIEW_DATA_SOURCE_NAME) found += 1; - } - return found; +/** `color` at `alpha`. */ +function withAlpha(color, alpha) { + return [color[0], color[1], color[2], alpha]; } diff --git a/src/annotations/drawTool.test.mjs b/src/annotations/drawTool.test.mjs index 67ff94cfa3..2d7b2a6013 100644 --- a/src/annotations/drawTool.test.mjs +++ b/src/annotations/drawTool.test.mjs @@ -205,11 +205,8 @@ test('draped marks classify onto terrain as well as 3D tiles', () => { // rendered proof is in scripts/qa-draw-tool.mjs, which counts stroke pixels // against a keyless server; this stops the constant being narrowed again. const renderer = read('src/annotations/worldAnnotationRenderer.js'); - assert.match(renderer, /const CLASSIFY = Cesium\.ClassificationType\.BOTH;/); - assert.doesNotMatch( - renderer, - /classificationType: Cesium\.ClassificationType\.CESIUM_3D_TILE/, - ); + assert.match(renderer, /const CLAMP_TO = 'both';/); + assert.doesNotMatch(renderer, /clampTo: '(tiles|terrain)'/); }); test('the draw modules are registered for formatting and boundary checks', () => { diff --git a/src/annotations/drawToolBehaviour.test.mjs b/src/annotations/drawToolBehaviour.test.mjs index 4cef4d4fe0..862cae6574 100644 --- a/src/annotations/drawToolBehaviour.test.mjs +++ b/src/annotations/drawToolBehaviour.test.mjs @@ -13,6 +13,8 @@ import { releasePointer, resetPointerOwnership, } from '../data/inputOwnership.js'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; /* ── DOM doubles ───────────────────────────────────────────────────────── */ @@ -68,9 +70,17 @@ class FakeElement { } closest(selector) { // Only what the tool asks: "am I inside an activatable control?" - const activatable = ['button', 'a', 'select', '[role="button"]', '[role="radio"]']; + const activatable = [ + 'button', + 'a', + 'select', + '[role="button"]', + '[role="radio"]', + ]; if (!activatable.some((part) => selector.includes(part))) return null; - return this.tagName === 'BUTTON' || this.tagName === 'A' || this.tagName === 'SELECT' + return this.tagName === 'BUTTON' || + this.tagName === 'A' || + this.tagName === 'SELECT' ? this : null; } @@ -143,39 +153,22 @@ function fakeViewer() { setInputAction: (action, type) => actions.set(type, action), removeInputAction: (type) => actions.delete(type), }; - const attached = []; - const pendingAdds = []; - const dataSources = { - get length() { - return attached.length; - }, - get: (index) => attached[index], - add(source) { - // Cesium resolves this on a later tick — the whole point of finding 7. - const promise = Promise.resolve().then(() => { - attached.push(source); - return source; - }); - pendingAdds.push(promise); - return promise; - }, - remove(source) { - const at = attached.indexOf(source); - if (at >= 0) attached.splice(at, 1); - return at >= 0; - }, - }; return { scene: { canvas, requestRender() {} }, screenSpaceEventHandler: stockHandler, - dataSources, - _attached: attached, _actions: actions, }; } function fakeAnnotations() { - const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] }; + const calls = { + annotate: [], + clear: 0, + restyle: [], + setHidden: [], + frame: [], + remove: [], + }; const marks = []; const listeners = new Set(); const changed = () => listeners.forEach((listener) => listener()); @@ -223,10 +216,21 @@ function fakeAnnotations() { } /** Stand up a tool against fresh doubles, with globals restored afterwards. */ -function harness({ navigation = null, markActions = [] } = {}) { +function harness({ + navigation = null, + beforeInput = () => {}, + markActions = [], +} = {}) { resetPointerOwnership(); const { byId, documentDouble } = fakeDom(); const viewer = fakeViewer(); + // The viewer's own actions are bound before its input port takes them. + beforeInput(viewer); + const input = fakeInput(viewer); + // The renderer the tool draws its preview with, drawing in the viewer's canvas. + const { draw, unbind: unbindDraw } = bindFakeDraw(viewer, { + canvas: viewer.scene.canvas, + }); const annotations = fakeAnnotations(); const previousDocument = globalThis.document; const previousWindow = globalThis.window; @@ -250,6 +254,7 @@ function harness({ navigation = null, markActions = [] } = {}) { tool, shown, viewer, + draw, annotations, byId, documentDouble, @@ -257,7 +262,10 @@ function harness({ navigation = null, markActions = [] } = {}) { controls, /** A control's change, as the view sends it. */ act: (name, ...args) => controls.actions?.[name]?.(...args), + input, restore() { + input.destroy(); + unbindDraw(); resetPointerOwnership(); if (previousDocument === undefined) delete globalThis.document; else globalThis.document = previousDocument; @@ -288,23 +296,42 @@ test('turning Draw on takes a lease and turning it off gives it back', async () } }); -test('Draw refuses to start when something else holds the pointer', async () => { +test('Draw takes the pointer from another tool, which is told', async () => { const h = harness(); try { - const other = claimPointer('directions'); + let lost = 0; + claimPointer('directions', { onLost: () => (lost += 1) }); h.act('toggleDraw'); - assert.equal(h.tool.active, false, 'it must not half-start'); - assert.equal(pointerOwner(), 'directions', 'and must not steal the claim'); - // Named by its tool, not by the internal owner id. - assert.equal( - h.shown.view.hint, - 'Directions is using the pointer — close it first.', - ); - assert.equal(h.tool.diagnostics().sceneHandler, false, 'no handler was bound'); + assert.equal(h.tool.active, true, 'the newest claim takes over'); + assert.equal(pointerOwner(), 'draw'); + assert.equal(lost, 1, 'the other tool is told once'); + } finally { + h.restore(); + } +}); +test('Draw turns off, as if toggled off, when a newer tool takes the pointer', async () => { + const h = harness({ + beforeInput(viewer) { + viewer.screenSpaceEventHandler.setInputAction(() => {}, LEFT_CLICK); + }, + }); + try { + h.act('toggleDraw'); + assert.equal(h.tool.diagnostics().stockSingleClick, false); + assert.ok(h.tool.addVertex(10, 20), 'a shape is under way'); + const other = claimPointer('directions'); + assert.equal(h.tool.active, false); + assert.equal(h.tool.session, null, 'the half-drawn shape is dropped'); + assert.equal(h.shown.view.active, false, 'the Draw control reads off'); + const after = h.tool.diagnostics(); + assert.equal(after.sceneHandler, false, 'its subscriptions are gone'); + assert.equal(after.stockSingleClick, true, 'the stock clicks are back'); + assert.equal(after.previewItems, 0, 'the preview is cleared'); + assert.equal(pointerOwner(), 'directions', 'the newer tool keeps it'); releasePointer(other); h.act('toggleDraw'); - assert.equal(h.tool.active, true, 'and it starts once the pointer is free'); + assert.equal(h.tool.active, true, 'and it turns on again when asked'); } finally { h.restore(); } @@ -336,30 +363,36 @@ test('a destroyed instance cannot free the pointer its replacement holds', async } }); -test('both stock viewer click actions are borrowed for the session and given back', async () => { - const h = harness(); +test('both stock viewer click actions are held off for the session and given back', async () => { + const stockClick = () => 'viewer picks and selects'; + const stockDouble = () => 'viewer tracks'; + const h = harness({ + beforeInput(viewer) { + viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK); + viewer.screenSpaceEventHandler.setInputAction( + stockDouble, + LEFT_DOUBLE_CLICK, + ); + }, + }); try { - const stockClick = () => 'viewer picks and selects'; - const stockDouble = () => 'viewer tracks'; - h.viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK); - h.viewer.screenSpaceEventHandler.setInputAction(stockDouble, LEFT_DOUBLE_CLICK); - + assert.equal(h.input.stockEnabled('select'), true); h.act('toggleDraw'); assert.equal( - h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK), - undefined, + h.input.stockEnabled('select'), + false, "the viewer's own selecting click must not run while drawing", ); - assert.equal( - h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK), - undefined, - ); + assert.equal(h.input.stockEnabled('dblclickFollow'), false); h.act('toggleDraw'); + assert.equal(h.input.stockEnabled('select'), true); + assert.equal(h.input.stockEnabled('dblclickFollow'), true); + h.input.destroy(); assert.equal( h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK), stockClick, - 'the exact function is restored, not a replacement', + 'the exact function goes back to the viewer, not a replacement', ); assert.equal( h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK), @@ -380,20 +413,55 @@ test('Enter finishes from the canvas and the label field, never from a focused b h.tool.addVertex(-97.74, 30.27); // Enter while the Clear button has keyboard focus means "press Clear". - h.documentDouble.emit('keydown', { key: 'Enter', target: h.element('draw-clear') }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.element('draw-clear'), + }); await Promise.resolve(); assert.equal( h.annotations.calls.annotate.length, 0, 'a focused button keeps its own Enter', ); - assert.equal(h.tool.session.vertices.length, 3, 'and the shape is untouched'); + assert.equal( + h.tool.session.vertices.length, + 3, + 'and the shape is untouched', + ); // Enter from the page body (the canvas has focus in practice) finishes it. - h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.documentDouble.body, + }); await Promise.resolve(); await Promise.resolve(); - assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the map finishes'); + assert.equal( + h.annotations.calls.annotate.length, + 1, + 'Enter on the map finishes', + ); + assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area'); + } finally { + h.restore(); + } +}); + +test('Enter on the globe canvas finishes, as after the render failure notice hands focus back', async () => { + const h = harness(); + try { + h.act('toggleDraw'); + h.tool.setShape('area'); + h.tool.addVertex(-97.75, 30.26); + h.tool.addVertex(-97.74, 30.26); + h.tool.addVertex(-97.74, 30.27); + + // src/ui/views/panels/RenderFailure.vue focuses the canvas when the globe + // draws again and the control that had focus is gone. + h.documentDouble.emit('keydown', { key: 'Enter', target: h.viewer.scene.canvas }); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the canvas finishes'); assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area'); } finally { h.restore(); @@ -408,21 +476,29 @@ test('the live preview hangs at the height the click landed on', async () => { h.tool.addVertex(-97.75, 30.26, 187.5); h.tool.addVertex(-97.74, 30.26, 212.25); - await h.tool.whenSettled(); - const source = h.viewer._attached[0] ?? null; - assert.ok(source, 'the preview data source is attached'); - const points = source.entities.values.filter((entity) => entity.point); - assert.equal(points.length, 2, 'one preview dot per vertex'); - const heights = points.map((entity) => { - const position = entity.position.getValue(Cesium.JulianDate.now()); - return Cesium.Cartographic.fromCartesian(position).height; - }); + const dots = [...h.draw.sets.values()].find( + (set) => !set.disposed && set.kind === 'points', + ); + assert.equal(dots.items.size, 2, 'one preview dot per vertex'); + const heights = [...dots.items.values()].map((item) => item.pos.height); + const band = [...h.draw.sets.values()] + .find((set) => !set.disposed && set.kind === 'lines') + .items.get('band'); + assert.equal( + band.positions.length, + 2, + 'the rubber band joins the vertices', + ); + assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped'); assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`); assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`); // …and the finished shape is still flattened, deliberately: the renderer // drapes, so a height carried further would be discarded out of sight. - h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.documentDouble.body, + }); await Promise.resolve(); await Promise.resolve(); const spec = h.annotations.calls.annotate[0].specs[0]; @@ -435,17 +511,60 @@ test('the live preview hangs at the height the click landed on', async () => { } }); -test('destroy in the same tick as init still removes the preview data source', async () => { +test('the rubber band follows the pointer, closes an area and takes the chosen colour', async () => { const h = harness(); try { - // Nothing has been attached yet — dataSources.add() resolves later. - assert.equal(h.viewer._attached.length, 0, 'the add is still pending'); - await h.tool.destroy(); - await Promise.resolve(); + const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed); + const band = () => + sets() + .find((set) => set.kind === 'lines') + .items.get('band'); + h.act('toggleDraw'); + h.tool.setShape('area'); + h.tool.addVertex(-97.75, 30.26); + assert.equal(band(), undefined, 'one vertex and no pointer draw no band'); + h.tool.addVertex(-97.74, 30.26); + h.tool.addVertex(-97.74, 30.27); assert.equal( - h.viewer._attached.length, + band().positions.length, + 4, + 'an area of three closes back to its first vertex', + ); + assert.deepEqual(band().positions[3], band().positions[0]); + + h.tool.setColor('red'); + assert.deepEqual( + band().style.color, + [1, 107 / 255, 107 / 255, 0.9], + 'the band takes the colour', + ); + assert.deepEqual( + band().depthFail, + { kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 }, + 'behind the surface it stays the primary colour, dashed, as before', + ); + assert.equal(band().style.kind, 'dash'); + assert.equal(band().style.length, 16); + assert.equal(band().widthPx, 3); + + h.tool.setShape('pin'); + assert.equal(band(), undefined, 'a pin has no rubber band'); + } finally { + h.restore(); + } +}); + +test('destroy in the same tick as init disposes the preview sets', async () => { + const h = harness(); + try { + const live = () => [...h.draw.sets.values()].filter((set) => !set.disposed); + assert.equal(live().length, 2, 'the rubber band and the vertex dots'); + await h.tool.destroy(); + assert.equal(live().length, 0, 'nothing is left drawn behind the teardown'); + assert.equal( + h.tool.diagnostics().previewSets, 0, - 'the preview must not be left attached behind the teardown', + 'no live tool draws a preview', ); } finally { h.restore(); @@ -469,7 +588,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act assert.equal(isPointerFree(), true, 'the pointer is free'); const after = h.tool.diagnostics(); assert.equal(after.destroyed, true); - assert.equal(after.sceneHandler, false, 'the Cesium handler is gone'); + assert.equal( + after.sceneHandler, + false, + 'the pointer subscriptions are gone', + ); assert.equal(after.domListeners, 0, 'every DOM listener came off'); assert.equal(h.documentDouble.listeners.length, 0, 'including the keydown'); assert.equal(h.controls.actions, null, 'and the controls are disconnected'); @@ -478,8 +601,12 @@ test('destroy releases the pointer, the handler, the listeners and the stock act stockClick, 'the viewer got its selecting click back', ); - assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached'); - assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board'); + assert.equal(after.previewSets, 0, 'the preview sets are disposed'); + assert.equal( + h.annotations.listeners.size, + 0, + 'and it no longer follows the board', + ); // Idempotent: a second destroy is harmless. await h.tool.destroy(); @@ -498,7 +625,11 @@ test('Clear wipes the board and the shape in progress', async () => { h.act('clearDraw'); assert.equal(h.annotations.calls.clear, 1, 'placed marks are removed'); - assert.equal(h.tool.session.vertices.length, 0, 'and so is the shape in progress'); + assert.equal( + h.tool.session.vertices.length, + 0, + 'and so is the shape in progress', + ); } finally { h.restore(); } @@ -512,7 +643,13 @@ test('the controls choose the shape and colour the next shape is drawn with; it h.act('setDrawColor', 'amber'); assert.deepEqual( { ...h.shown.view, hint: undefined }, - { active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] }, + { + active: true, + shape: 'line', + color: 'amber', + hint: undefined, + marks: [], + }, 'the view shows what the controls chose', ); h.act('setDrawColor', 'purple'); @@ -524,7 +661,10 @@ test('the controls choose the shape and colour the next shape is drawn with; it assert.equal(h.tool.session.vertices.length, 0); h.tool.addVertex(-97.75, 30.26); h.tool.addVertex(-97.74, 30.26); - h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Enter', + target: h.documentDouble.body, + }); await Promise.resolve(); await Promise.resolve(); const spec = h.annotations.calls.annotate[0].specs[0]; @@ -549,12 +689,31 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n try { const board = h.annotations; board.marks.push( - { id: 'a1', type: 'route', manual: true, name: null, label: '950 m', color: 'amber', hidden: false }, - { id: 'a2', type: 'pin', manual: false, label: 'Voice pin', color: 'primary', hidden: false }, + { + id: 'a1', + type: 'route', + manual: true, + name: null, + label: '950 m', + color: 'amber', + hidden: false, + }, + { + id: 'a2', + type: 'pin', + manual: false, + label: 'Voice pin', + color: 'primary', + hidden: false, + }, ); board.changed(); assert.deepEqual( - h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ id, placeholder, hidden })), + h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ + id, + placeholder, + hidden, + })), [{ id: 'a1', placeholder: 'Line · 950 m', hidden: false }], 'only hand-drawn marks are listed, an unnamed line by its length', ); @@ -569,7 +728,11 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n ]); assert.deepEqual(board.calls.setHidden, [['a1', true]]); assert.deepEqual(board.calls.frame, ['a1']); - assert.deepEqual(navigations, ['drawing'], 'fly-to goes through the navigation policy'); + assert.deepEqual( + navigations, + ['drawing'], + 'fly-to goes through the navigation policy', + ); assert.deepEqual(board.calls.remove, ['a1']); assert.deepEqual(h.shown.view.marks, [], 'the row goes with its mark'); } finally { @@ -577,7 +740,7 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n } }); -test('an application\'s row actions show on the shapes they are for and run with the shape', async () => { +test("row actions given to the tool show on the shapes they are for and run with the shape", async () => { const ran = []; const h = harness({ markActions: [ @@ -601,30 +764,102 @@ test('an application\'s row actions show on the shapes they are for and run with try { const board = h.annotations; board.marks.push( - { id: 'r1', type: 'area', manual: true, name: 'Strait', color: 'primary', hidden: false, ring: [[29, 41], [29.1, 41], [29.1, 41.1]] }, - { id: 'l1', type: 'route', manual: true, name: null, label: '9 km', color: 'amber', hidden: false, path: [{ lon: 29, lat: 41.05, height: 0 }, { lon: 29.1, lat: 41.05, height: 0 }] }, - { id: 'p1', type: 'pin', manual: true, name: 'Camp', color: 'red', hidden: false }, + { + id: 'r1', + type: 'area', + manual: true, + name: 'Strait', + color: 'primary', + hidden: false, + ring: [ + [29, 41], + [29.1, 41], + [29.1, 41.1], + ], + }, + { + id: 'l1', + type: 'route', + manual: true, + name: null, + label: '9 km', + color: 'amber', + hidden: false, + path: [ + { lon: 29, lat: 41.05, height: 0 }, + { lon: 29.1, lat: 41.05, height: 0 }, + ], + }, + { + id: 'p1', + type: 'pin', + manual: true, + name: 'Camp', + color: 'red', + hidden: false, + }, ); board.changed(); assert.deepEqual( h.shown.view.marks.map(({ id, actions }) => [id, actions]), [ - ['r1', [ - { id: 'tag', icon: 'sell', label: 'Tag Strait' }, - { id: 'measure', icon: 'straighten', label: 'Measure Strait' }, - ]], + [ + 'r1', + [ + { id: 'tag', icon: 'sell', label: 'Tag Strait' }, + { id: 'measure', icon: 'straighten', label: 'Measure Strait' }, + ], + ], ['l1', [{ id: 'tag', icon: 'sell', label: 'Tag Line · 9 km' }]], ['p1', []], ], ); assert.equal(h.act('runDrawMarkAction', 'l1', 'tag'), true); - assert.equal(h.act('runDrawMarkAction', 'l1', 'measure'), false, 'a line is not offered an area action'); + assert.equal( + h.act('runDrawMarkAction', 'l1', 'measure'), + false, + 'a line is not offered an area action', + ); assert.equal(h.act('runDrawMarkAction', 'p1', 'tag'), false); assert.equal(h.act('runDrawMarkAction', 'gone', 'tag'), false); assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true); assert.deepEqual(ran, [ - ['tag', { id: 'l1', shape: 'line', name: '', title: 'Line · 9 km', geometry: { type: 'LineString', coordinates: [[29, 41.05], [29.1, 41.05]] } }], - ['measure', { id: 'r1', shape: 'area', name: 'Strait', title: 'Strait', geometry: { type: 'Polygon', coordinates: [[[29, 41], [29.1, 41], [29.1, 41.1], [29, 41]]] } }], + [ + 'tag', + { + id: 'l1', + shape: 'line', + name: '', + title: 'Line · 9 km', + geometry: { + type: 'LineString', + coordinates: [ + [29, 41.05], + [29.1, 41.05], + ], + }, + }, + ], + [ + 'measure', + { + id: 'r1', + shape: 'area', + name: 'Strait', + title: 'Strait', + geometry: { + type: 'Polygon', + coordinates: [ + [ + [29, 41], + [29.1, 41], + [29.1, 41.1], + [29, 41], + ], + ], + }, + }, + ], ]); } finally { h.restore(); @@ -634,16 +869,40 @@ test('an application\'s row actions show on the shapes they are for and run with test('an action that throws is reported and leaves the row alone', async () => { const h = harness({ markActions: [ - { id: 'boom', icon: 'bolt', label: () => { throw new Error('label'); }, shapes: ['area'], run: () => { throw new Error('run'); } }, + { + id: 'boom', + icon: 'bolt', + label: () => { + throw new Error('label'); + }, + shapes: ['area'], + run: () => { + throw new Error('run'); + }, + }, ], }); const warn = console.warn; const warned = []; console.warn = (...args) => warned.push(args[0]); try { - h.annotations.marks.push({ id: 'r1', type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] }); + h.annotations.marks.push({ + id: 'r1', + type: 'area', + manual: true, + name: null, + color: 'primary', + hidden: false, + ring: [ + [0, 0], + [1, 0], + [1, 1], + ], + }); h.annotations.changed(); - assert.deepEqual(h.shown.view.marks[0].actions, [{ id: 'boom', icon: 'bolt', label: 'boom' }]); + assert.deepEqual(h.shown.view.marks[0].actions, [ + { id: 'boom', icon: 'bolt', label: 'boom' }, + ]); assert.equal(h.act('runDrawMarkAction', 'r1', 'boom'), false); assert.deepEqual(warned, ['[draw] boom failed']); } finally { @@ -652,7 +911,7 @@ test('an action that throws is reported and leaves the row alone', async () => { } }); -test('what a row action answers is its row\'s note; the row is busy until then, and a removed shape drops it', async () => { +test("what a row action answers is its row's note; the row is busy until then, and a removed shape drops it", async () => { const pending = []; const h = harness({ markActions: [ @@ -661,34 +920,73 @@ test('what a row action answers is its row\'s note; the row is busy until then, icon: 'straighten', label: (name) => `Measure ${name}`, shapes: ['area'], - run: () => new Promise((resolve, reject) => pending.push({ resolve, reject })), + run: () => + new Promise((resolve, reject) => pending.push({ resolve, reject })), + }, + { + id: 'now', + icon: 'bolt', + label: () => 'Now', + shapes: ['area'], + run: () => ' 12 km² ', + }, + { + id: 'long', + icon: 'notes', + label: () => 'Long', + shapes: ['area'], + run: () => `${'word '.repeat(60)}end`, }, - { id: 'now', icon: 'bolt', label: () => 'Now', shapes: ['area'], run: () => ' 12 km² ' }, - { id: 'long', icon: 'notes', label: () => 'Long', shapes: ['area'], run: () => `${'word '.repeat(60)}end` }, ], }); const warn = console.warn; console.warn = () => {}; try { const board = h.annotations; - const area = (id) => ({ id, type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] }); + const area = (id) => ({ + id, + type: 'area', + manual: true, + name: null, + color: 'primary', + hidden: false, + ring: [ + [0, 0], + [1, 0], + [1, 1], + ], + }); board.marks.push(area('r1'), area('r2')); board.changed(); const row = (id) => h.shown.view.marks.find((entry) => entry.id === id); assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), true); assert.deepEqual([row('r1').busy, row('r1').note], [false, '12 km²']); h.act('runDrawMarkAction', 'r1', 'long'); - assert.ok(row('r1').note.length <= 200 && row('r1').note.endsWith('word…'), 'a long note is cut at a word'); + assert.ok( + row('r1').note.length <= 200 && row('r1').note.endsWith('word…'), + 'a long note is cut at a word', + ); assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true); assert.deepEqual([row('r1').busy, row('r1').note], [true, '']); - assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), false, 'a busy row takes no second press'); + assert.equal( + h.act('runDrawMarkAction', 'r1', 'now'), + false, + 'a busy row takes no second press', + ); pending[0].resolve('412 km², 38 km of edge'); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.deepEqual([row('r1').busy, row('r1').note], [false, '412 km², 38 km of edge']); + assert.deepEqual( + [row('r1').busy, row('r1').note], + [false, '412 km², 38 km of edge'], + ); h.act('runDrawMarkAction', 'r1', 'measure'); pending[1].reject(new Error('refused')); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.deepEqual([row('r1').busy, row('r1').note], [false, ''], 'a failure clears the note'); + assert.deepEqual( + [row('r1').busy, row('r1').note], + [false, ''], + 'a failure clears the note', + ); h.act('runDrawMarkAction', 'r2', 'measure'); board.marks.splice(1, 1); board.changed(); @@ -697,7 +995,11 @@ test('what a row action answers is its row\'s note; the row is busy until then, assert.equal(row('r2'), undefined); board.marks.push(area('r2')); board.changed(); - assert.deepEqual([row('r2').busy, row('r2').note], [false, ''], 'a late answer never reaches a shape that went'); + assert.deepEqual( + [row('r2').busy, row('r2').note], + [false, ''], + 'a late answer never reaches a shape that went', + ); } finally { console.warn = warn; h.restore(); @@ -710,30 +1012,49 @@ test('Backspace on the page removes the last vertex', () => { h.act('toggleDraw'); h.tool.addVertex(-97.75, 30.26); h.tool.addVertex(-97.74, 30.26); - h.documentDouble.emit('keydown', { key: 'Backspace', target: h.documentDouble.body }); + h.documentDouble.emit('keydown', { + key: 'Backspace', + target: h.documentDouble.body, + }); assert.equal(h.tool.session.vertices.length, 1); } finally { h.restore(); } }); -test('keys on the shape list are the list\'s, not the drawing\'s', async () => { +test("keys on the shape list are the list's, not the drawing's", async () => { const h = harness(); try { const listButton = new FakeElement('BUTTON'); - listButton.closest = (selector) => (selector === '#draw-mark-list' ? {} : null); + listButton.closest = (selector) => + selector === '#draw-mark-list' ? {} : null; const elsewhere = new FakeElement('INPUT', 'location-search'); h.act('toggleDraw'); h.tool.addVertex(-97.75, 30.26); h.tool.addVertex(-97.74, 30.26); h.documentDouble.emit('keydown', { key: 'Escape', target: listButton }); - assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape'); + assert.equal( + h.tool.session.vertices.length, + 2, + 'Escape in the list keeps the shape', + ); assert.equal(h.tool.active, true, 'and keeps Draw on'); h.documentDouble.emit('keydown', { key: 'Enter', target: elsewhere }); await Promise.resolve(); - assert.equal(h.annotations.calls.annotate.length, 0, 'another field keeps its Enter'); - h.documentDouble.emit('keydown', { key: 'Escape', target: h.documentDouble.body }); - assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape'); + assert.equal( + h.annotations.calls.annotate.length, + 0, + 'another field keeps its Enter', + ); + h.documentDouble.emit('keydown', { + key: 'Escape', + target: h.documentDouble.body, + }); + assert.equal( + h.tool.session.vertices.length, + 0, + 'Escape on the page drops the open shape', + ); } finally { h.restore(); } diff --git a/src/annotations/hybridAnnotationRenderer.test.mjs b/src/annotations/hybridAnnotationRenderer.test.mjs index cf61502c47..ef56dea496 100644 --- a/src/annotations/hybridAnnotationRenderer.test.mjs +++ b/src/annotations/hybridAnnotationRenderer.test.mjs @@ -5,6 +5,9 @@ import { createPinia } from 'pinia'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; +import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; /** A hybrid renderer whose screen board is presented to its own store. */ function hybridWithBoard(viewer) { @@ -89,11 +92,41 @@ function installBrowserGlobals(t) { }); } +/** + * `viewer` with the fake scene's camera, query, frame and draw ports and the + * fake credits bound over it as one renderer. + */ +function withScenePorts(viewer) { + const { unbind, ...ports } = bindFakeCesiumScene(viewer); + unbind(); + bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) }); + return ports.draw; +} + +/** What the world renderer draws, each item of its live sets (of `kind`). */ +function worldItems(draw, kind) { + const items = []; + for (const record of draw.sets.values()) + if ( + !record.disposed && + record.spec.id.startsWith('annotations:') && + (!kind || record.kind === kind) + ) + items.push(...record.items.values()); + return items; +} + +/** Surface heights the scene samples: `height(lon, lat)` in degrees. */ +function sampleHeights(scene, height) { + scene.sampleHeightSupported = true; + scene.sampleHeight = (carto) => + height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude)); +} + /** A viewer whose scene/camera is just enough for both sub-renderers. */ function fakeViewer(lon, lat) { const credits = new Set(); const camera = cameraLookingAt(lon, lat); - const dataSources = []; const frames = controlledFrames(); const scene = { camera, @@ -107,31 +140,19 @@ function fakeViewer(lon, lat) { scene.renderRequests += 1; }, }; - return { - dataSources, - frames, - viewer: { - credits, - creditDisplay: { - addStaticCredit: (credit) => credits.add(credit), - removeStaticCredit: (credit) => credits.delete(credit), - }, - scene, - camera, - trackedEntity: null, - dataSources: { - add(dataSource) { - dataSources.push(dataSource); - return dataSource; - }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, + const viewer = { + credits, + creditDisplay: { + addStaticCredit: (credit) => credits.add(credit), + removeStaticCredit: (credit) => credits.delete(credit), }, + scene, + camera, + canvas: scene.canvas, + trackedEntity: null, }; + const draw = withScenePorts(viewer); + return { draw, frames, viewer }; } function controlledFrames() { @@ -192,7 +213,6 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' }); const camera = cameraLookingAt(-99, 31); - const dataSources = []; const frames = controlledFrames(); const scene = { camera, @@ -206,19 +226,12 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' const viewer = { scene, camera, + canvas: scene.canvas, trackedEntity: null, - dataSources: { - add(dataSource) { - dataSources.push(dataSource); - return dataSource; - }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, }; + // The screen board projects through the renderer's camera and query; the + // world renderer draws through its draw port. + const { draw } = bindFakeCesiumScene(viewer); const { store, renderer } = hybridWithBoard(viewer); const anno = { id: 'anno-hybrid-fb3', @@ -235,8 +248,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' renderer.add(anno); const [before] = annotationGroups(store); assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2); - assert.equal(dataSources.length, 1); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); const ring = [ [-106, 25], @@ -268,10 +280,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1)); assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1)); assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned'); - assert.equal(dataSources[0].entities.values.length, 2, 'world area adds one fill and one outline'); - assert.equal(dataSources[0].entities.values.filter((entity) => entity.polygon).length, 1); - assert.equal(dataSources[0].entities.values.filter((entity) => entity.polyline).length, 1); - assert.equal(Object.hasOwn(anno, '_entities'), false, 'world entity state stays on the inherited proxy'); + assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline'); + assert.equal(worldItems(draw, 'shapes').length, 1); + assert.equal(worldItems(draw, 'lines').length, 1); + assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy'); const outer = [ [-99, 31], [-98.999, 31], @@ -298,33 +310,26 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' buildingHeight: 20, }; const completion = renderer.add(building); - assert.equal(dataSources[0].entities.values.length, 2, 'building geometry waits for all probes'); + assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes'); for (let frame = 0; frame < 8; frame += 1) frames.emit(); assert.equal((await completion).status, 'installed'); - const added = dataSources[0].entities.values.slice(2); - const fills = added.filter( - (entity) => entity.polygon && entity.polygon.fill?.getValue() !== false, - ); + const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:')); assert.equal( fills.length, 2, - 'every building part gets a classification volume', + 'every building part gets a volume', ); - assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1); - assert.equal(fills[1].polygon.hierarchy.getValue().holes.length, 0); + assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole'); + assert.equal(fills[1].geometry.rings.length, 1); + assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour'); assert.equal( - fills[0].polygon.material, - fills[1].polygon.material, - 'parts share the fill material', - ); - assert.equal( - added.filter((entity) => entity.polyline).length, + worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length, 3, 'all outer and hole outlines are retained', ); renderer.remove(building); assert.equal( - dataSources[0].entities.values.length, + worldItems(draw).length, 2, 'multipart removal leaves only the earlier area', ); @@ -341,7 +346,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -369,26 +374,26 @@ test('a sub-renderer throw mid-add leaves state the rollback can still remove', }; assert.throws(() => renderer.add(anno), /screen insert failed/); - assert.equal(dataSources[0].entities.values.length, 2, 'the world drape is already live'); + assert.equal(worldItems(draw).length, 2, 'the world drape is already live'); assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself'); // The engine's rollback path — it must reach the partial state by id. renderer.remove(anno); - assert.equal(dataSources[0].entities.values.length, 0, 'partial world state must be released'); + assert.equal(worldItems(draw).length, 0, 'partial world state must be released'); // …and the id is free again: a retry draws ONE mark, not a second one over // an orphan nothing owns. renderer.add(anno); - assert.equal(dataSources[0].entities.values.length, 2, 'the retry draws exactly one world drape'); + assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape'); assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption'); renderer.remove(anno); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); renderer.destroy(); }); test('a release that throws keeps the mark addressable for a retry cleanup', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -404,7 +409,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) }; renderer.add(anno); - assert.equal(dataSources[0].entities.values.length, 2); + assert.equal(worldItems(draw).length, 2); assert.equal(annotationGroups(store).length, 1); // The world route releases fine, then the screen release fails part-way @@ -412,7 +417,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) const workingSetTimeout = globalThis.window.setTimeout; globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); }; assert.throws(() => renderer.remove(anno), /teardown scheduling failed/); - assert.equal(dataSources[0].entities.values.length, 0, 'the world route did release'); + assert.equal(worldItems(draw).length, 0, 'the world route did release'); assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan'); // Dropping the routing entry here would make that orphan permanently @@ -420,7 +425,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) globalThis.window.setTimeout = workingSetTimeout; renderer.remove(anno); assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan'); - assert.equal(dataSources[0].entities.values.length, 0, 'without double-releasing the world route'); + assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route'); // Fully released now — a third call is inert. renderer.remove(anno); @@ -430,7 +435,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) test('a world add that fails mid-way leaves its landed entities removable', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -446,25 +451,23 @@ test('a world add that fails mid-way leaves its landed entities removable', (t) }; // The draped fill lands; the outline throws (bad geometry / lost context). - const entities = dataSources[0].entities; - const realAdd = entities.add.bind(entities); - let addsLeft = 1; - entities.add = (options) => { - if (addsLeft <= 0) throw new Error('entity add failed'); - addsLeft -= 1; - return realAdd(options); + const realLines = draw.lines; + draw.lines = (spec) => { + const set = realLines(spec); + set.set = () => { throw new Error('draw failed'); }; + return set; }; - assert.throws(() => renderer.add(anno), /entity add failed/); - assert.equal(entities.values.length, 1, 'one entity landed before the failure'); + assert.throws(() => renderer.add(anno), /draw failed/); + assert.equal(worldItems(draw).length, 1, 'one item landed before the failure'); - entities.add = realAdd; + draw.lines = realLines; renderer.remove(anno); - assert.equal(entities.values.length, 0, - 'the rollback must see the entities that landed before the throw'); + assert.equal(worldItems(draw).length, 0, + 'the rollback must see the items that landed before the throw'); renderer.add(anno); - assert.equal(entities.values.length, 2, 'the retry draws a complete mark'); + assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark'); assert.equal(annotationGroups(store).length, 1); renderer.destroy(); }); @@ -475,7 +478,7 @@ function workTrace() { test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => { installBrowserGlobals(t); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); t.after(() => renderer.destroy()); const first = buildingAnnotation('sampled-building'); @@ -485,15 +488,12 @@ test('buildings share one probe per frame and preserve probe geometry, filtering showOsmCredit(viewer, otherOwner); const probes = []; const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90]; - viewer.scene.clampToHeight = (position) => { - const cartographic = Cesium.Cartographic.fromCartesian(position); - const lon = Cesium.Math.toDegrees(cartographic.longitude); - const lat = Cesium.Math.toDegrees(cartographic.latitude); + sampleHeights(viewer.scene, (lon, lat) => { probes.push([lon, lat]); const outcome = outcomes[probes.length - 1]; if (outcome instanceof Error) throw outcome; - return outcome == null ? undefined : Cesium.Cartesian3.fromDegrees(lon, lat, outcome); - }; + return outcome == null ? undefined : outcome; + }); // Suppress screen points: these counts concern the eight outside-building // probes, not the screen renderer's separate anchor-height sampling. const firstTrace = workTrace(); @@ -510,14 +510,14 @@ test('buildings share one probe per frame and preserve probe geometry, filtering const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace }); const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace }); assert.equal(probes.length, 0, 'enqueue must not probe synchronously'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1, 'pending outlines add no tile credit to the other owner'); for (let frame = 0; frame < 16; frame += 1) { const before = probes.length; frames.emit(); assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget'); - if (frame < 7) assert.equal(dataSources[0].entities.values.length, 0, 'no partial world parts'); + if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts'); } const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]); assert.equal(installed.status, 'installed'); @@ -540,8 +540,9 @@ test('buildings share one probe per frame and preserve probe geometry, filtering const detail = parent.detail; assert.equal(detail.index, index); assert.equal(detail.status, trace === firstTrace ? 'recorded' : 'missing'); + // The fourth probe finds nothing and the fifth throws: both are misses. assert.equal(detail.clampResult, - trace === firstTrace && index === 4 ? 'threw' : 'returned'); + trace === firstTrace && index !== 3 && index !== 4 ? 'hit' : 'missed'); assert.ok(Number.isFinite(detail.clampStart) && Number.isFinite(detail.clampEnd)); assert.ok(parent.start <= detail.clampStart && detail.clampStart <= detail.clampEnd && detail.clampEnd <= parent.end); if (index === 7) { @@ -571,10 +572,10 @@ test('buildings share one probe per frame and preserve probe geometry, filtering assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10); } assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8); - const fills = dataSources[0].entities.values.filter((entity) => entity.polygon?.fill?.getValue() !== false && entity.polygon); + const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:')); assert.equal(fills.length, 2); - assert.ok(Math.abs(fills[0].polygon.height.getValue() - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3'); - assert.ok(Math.abs(fills[1].polygon.height.getValue() - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback'); + assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3'); + assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback'); const afterCompletion = probes.length; frames.emit(); assert.equal(probes.length, afterCompletion, 'completion releases the sampler'); @@ -597,7 +598,7 @@ test('a building queued behind others gets its full budget on a slow device', as t.mock.method(globalThis.performance, 'now', () => now); const { viewer, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); - viewer.scene.clampToHeight = (position) => position; + sampleHeights(viewer.scene, () => 0); const traces = [workTrace(), workTrace(), workTrace()]; const completions = [0, 0.01, 0.02].map((offset, index) => renderer.add(buildingAnnotation(`queued-${index}`, offset), { @@ -626,10 +627,10 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks installBrowserGlobals(t); t.mock.timers.enable({ apis: ['setTimeout'] }); t.after(() => t.mock.timers.reset()); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); let probeCount = 0; - viewer.scene.clampToHeight = (position) => { probeCount += 1; return position; }; + sampleHeights(viewer.scene, () => { probeCount += 1; return 0; }); const cancelled = buildingAnnotation('cancelled-building'); const cancelledTrace = workTrace(); const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace }); @@ -671,7 +672,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks assert.equal(viewer.credits.size, 0); for (const listener of savedTimeout) listener(); assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); const pending = buildingAnnotation('destroyed-building'); const destruction = renderer.add(pending, { pendingVisible: false }); @@ -681,7 +682,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks for (const listener of savedDestroy) listener(); t.mock.timers.tick(2000); assert.equal(probeCount, 1); - assert.equal(dataSources.length, 0, 'destroy removes the owned data source'); + assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go'); assert.equal(frames.size, 0, 'destroy removes frame listeners'); assert.equal(viewer.credits.size, 0); }); @@ -690,7 +691,7 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy installBrowserGlobals(t); t.mock.timers.enable({ apis: ['setTimeout'] }); t.after(() => t.mock.timers.reset()); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' }; renderer.add(anno); @@ -703,15 +704,15 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy assert.equal(after.key, before.key); assert.equal(others.length, 0); assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); frames.emit(); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); renderer.destroy(); }); test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => { installBrowserGlobals(t); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' }; renderer.add(anno); @@ -724,7 +725,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet // Frame projection is still ordinary pending-point work. Arm the failure // only after sampling completes, before its promise converts the caption. for (let frame = 0; frame < 8; frame += 1) frames.emit(); - assert.ok(dataSources[0].entities.values.length > 0, 'multipart world geometry landed before caption conversion'); + assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion'); assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy'); // The caption conversion fails when it presents the converted mark. const publish = store.publish; @@ -747,7 +748,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8); assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1); assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1); - assert.equal(dataSources[0].entities.values.length, 0, 'all classification, cage and outline parts roll back'); + assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back'); assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy'); assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable'); globalThis.window.setTimeout = workingSetTimeout; @@ -781,6 +782,7 @@ test('a deadline passed during caption conversion leaves a drawn pending point', const live = annotationGroups(store).filter((mark) => !mark.className?.includes('gev-out')); assert.equal(live.length, 1); assert.ok(childrenWithClass(live[0], 'gev-anno-ring').length > 0, 'the pending point still draws'); + assert.notEqual(live[0].display, 'none', 'and is on screen'); renderer.remove(anno); renderer.destroy(); }); diff --git a/src/annotations/outlineRungs.test.mjs b/src/annotations/outlineRungs.test.mjs index 6554e6f61a..016012bbfb 100644 --- a/src/annotations/outlineRungs.test.mjs +++ b/src/annotations/outlineRungs.test.mjs @@ -18,6 +18,7 @@ import { outlineQueryText, } from './outlineRungs.js'; import { createAnnotationResolver } from './resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { decodeOpenFreeMapOutlineTile } from '../sources/openFreeMapOutlines.js'; import { createNominatimOutlineClient } from '../sources/nominatimOutlines.js'; import { createApplicationRequestServices } from '../services/requests.js'; @@ -924,15 +925,17 @@ const PLACES = { }, }; -const viewerAt = (lat, lon, height = 4000) => ({ - camera: { - positionCartographic: { - latitude: (lat * Math.PI) / 180, - longitude: (lon * Math.PI) / 180, - height, +// The resolver reads the camera through the renderer's camera port. +const viewerAt = (lat, lon, height = 4000) => + bindFakeCesiumCamera({ + camera: { + positionCartographic: { + latitude: (lat * Math.PI) / 180, + longitude: (lon * Math.PI) / 180, + height, + }, }, - }, -}); + }); test('default settings: outline, street and building asks send nothing to Overpass', async (t) => { const prior = process.env.OVERPASS_UPSTREAMS; diff --git a/src/annotations/placeOutline.test.mjs b/src/annotations/placeOutline.test.mjs index 7f2acdde36..07e65449a5 100644 --- a/src/annotations/placeOutline.test.mjs +++ b/src/annotations/placeOutline.test.mjs @@ -5,11 +5,14 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js'; import { createAnnotationResolver } from './resolver.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { polygonsContain } from '../data/adminBoundaries.js'; import { streetFootprint } from './outlineRungs.js'; +import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; function viewerAt(lat, lon, height = 20_000) { - return { + // The resolver reads the camera through the renderer's camera port. + return bindFakeCesiumCamera({ camera: { positionCartographic: { latitude: (lat * Math.PI) / 180, @@ -17,7 +20,7 @@ function viewerAt(lat, lon, height = 20_000) { height, }, }, - }; + }); } /** A resolver whose boundary lookups and geocoder record every call. */ @@ -180,10 +183,10 @@ test('a geocoded city or neighborhood upgrades to the bundled outline', async () const credits = []; const cancelled = await city.resolve( 'Austin', - { + bindFakeCesiumCredits({ ...viewerAt(39, -100, 5_000_000), creditDisplay: { addStaticCredit: (credit) => credits.push(credit) }, - }, + }), { signal: controller.signal }, ); const pending = cancelled.resolveOutline(); diff --git a/src/annotations/resolver.js b/src/annotations/resolver.js index 527f451131..5e5506ed44 100644 --- a/src/annotations/resolver.js +++ b/src/annotations/resolver.js @@ -14,7 +14,6 @@ import { nearestPointOnLines, } from '../sources/featureGeometry.js'; import { defaultGeospatial } from '../search/defaults.js'; -import * as Cesium from 'cesium'; import { lookupNeighborhoodRing } from '../data/neighborhoodPolygons.js'; import { lookupNaturalRegionOutline, @@ -45,6 +44,9 @@ import { import { createOutlineRungs } from './outlineRungs.js'; import { unavailablePlaceSearch } from '../search/placeSearch.js'; import { isPickedWorldPosition } from '../data/scenePick.js'; +import { heightsOf } from '../queries/heights.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js'; /** Prepare only local dateline outlines for planar admission and centering. */ function localOutlineFrame(fp) { @@ -178,7 +180,7 @@ export function createAnnotationResolver({ * Resolve a single annotation target to a normalized world anchor. * * @param {object} opts - * @param {Cesium.Viewer} opts.viewer + * @param {object} opts.viewer The viewer the renderer is bound to. * @param {string} [opts.target] Place name to geocode. * @param {number} [opts.latitude] Explicit latitude (wins over target). * @param {number} [opts.longitude] Explicit longitude. @@ -2216,11 +2218,10 @@ export function createAnnotationResolver({ */ function viewportProximity(viewer) { try { - const carto = viewer?.camera?.positionCartographic; - if (!carto) return null; - const lat = Cesium.Math.toDegrees(carto.latitude); - const lon = Cesium.Math.toDegrees(carto.longitude); - const radiusKm = Math.max((carto.height / 1000) * 3, 5); + const pose = viewer ? findCamera(viewer)?.pose() : null; + if (!pose) return null; + const { lat, lon } = pose; + const radiusKm = Math.max((pose.height / 1000) * 3, 5); if (![lat, lon, radiusKm].every(Number.isFinite)) return null; return { lat, lon, radiusKm }; } catch { @@ -2231,12 +2232,12 @@ export function createAnnotationResolver({ /** Exported for searchAndFlyTo (src/locations.js), which shares this bias. */ function viewportBias(viewer) { try { - const rect = viewer?.camera?.computeViewRectangle?.(); + const rect = viewer ? findCamera(viewer)?.viewRectangle() : null; if (!rect) return null; - const swLat = Cesium.Math.toDegrees(rect.south).toFixed(4); - const swLng = Cesium.Math.toDegrees(rect.west).toFixed(4); - const neLat = Cesium.Math.toDegrees(rect.north).toFixed(4); - const neLng = Cesium.Math.toDegrees(rect.east).toFixed(4); + const swLat = rect.south.toFixed(4); + const swLng = rect.west.toFixed(4); + const neLat = rect.north.toFixed(4); + const neLng = rect.east.toFixed(4); if ([swLat, swLng, neLat, neLng].some((v) => v === 'NaN')) return null; return `${swLat},${swLng}|${neLat},${neLng}`; } catch { @@ -2289,58 +2290,39 @@ export function createAnnotationResolver({ * name the place, and we anchor the mark to the actual world point under it. */ function pickWorldFromScreen(viewer, nx, ny) { - const scene = viewer?.scene; - if (!scene) return null; - const canvas = scene.canvas; + const query = viewer ? findQuery(viewer) : null; + // The renderer's canvas; a viewer with no renderer bound, its own. + const canvas = canvasOf(viewer); + if (!query || !canvas) return null; const w = canvas.clientWidth || canvas.width || 0; const h = canvas.clientHeight || canvas.height || 0; if (!w || !h) return null; const px = Math.max(0, Math.min(1, nx)) * w; const py = Math.max(0, Math.min(1, ny)) * h; - const pos = new Cesium.Cartesian2(px, py); // Each stage is validated before it is accepted: a depth pick over empty sky - // can return a NaN or centre-of-the-earth Cartesian, and converting one of - // those throws inside Cesium. A degenerate pick IS a missed pick, so it falls - // through to the next stage and ultimately to the caller's null. - let cart = null; - if ( - scene.pickPositionSupported && - typeof scene.pickPosition === 'function' - ) { + // can return a NaN or centre-of-the-earth position, and converting one of + // those throws inside the renderer. A degenerate pick IS a missed pick, so it + // falls through to the next stage and ultimately to the caller's null. + const attempt = (pick) => { try { - cart = scene.pickPosition(pos); + return pick(); } catch { - cart = null; + return null; } - } - if ( - !isPickedWorldPosition(cart) && - typeof viewer.camera.pickEllipsoid === 'function' - ) { - try { - cart = viewer.camera.pickEllipsoid(pos, Cesium.Ellipsoid.WGS84); - } catch { - cart = null; - } - } - if ( - !isPickedWorldPosition(cart) && - typeof viewer.camera.getPickRay === 'function' - ) { - try { - const ray = viewer.camera.getPickRay(pos); - cart = ray ? scene.globe?.pick(ray, scene) || null : null; - } catch { - cart = null; - } - } + }; + // The depth pick answers null where the renderer has no depth support. + let cart = attempt(() => query.pickPosition(px, py)); + if (!isPickedWorldPosition(cart)) + cart = attempt(() => query.pickEllipsoid(px, py)); + if (!isPickedWorldPosition(cart)) + cart = attempt(() => query.pickGlobe(query.pickRay(px, py))); if (!isPickedWorldPosition(cart)) return null; - const carto = Cesium.Cartographic.fromCartesian(cart); + const carto = toLonLatH(cart); if (!carto) return null; return { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), + lat: carto.lat, + lon: carto.lon, // The height the pick actually landed on — a roof, a hillside, or 0 on // the ellipsoid. Callers that only want a coordinate ignore it; the draw // tool's live preview needs it, or the rubber band sinks to sea level @@ -2355,28 +2337,18 @@ export function createAnnotationResolver({ * the tiles for that spot aren't loaded we fall back to the ellipsoid (0). */ function sampleGroundHeight(viewer, lon, lat) { - const scene = viewer?.scene; - if (!scene) return 0; - try { - if ( - scene.clampToHeightSupported && - typeof scene.clampToHeight === 'function' - ) { - const carto = Cesium.Cartographic.fromDegrees(lon, lat); - const surface = Cesium.Cartographic.toCartesian(carto); - const clamped = scene.clampToHeight(surface); - if (clamped) { - const h = Cesium.Cartographic.fromCartesian(clamped).height; - if (Number.isFinite(h)) return h; - } + if (!viewer) return 0; + const heights = heightsOf(viewer); + // A miss is tiles not ready: fall through to the terrain, then 0. + if (heights.supported().clamp) { + const clamped = heights.clampNow(fromDegrees(lon, lat, 0)); + if (clamped) { + const h = toLonLatH(clamped)?.height; + if (Number.isFinite(h)) return h; } - } catch { - /* tiles not ready — fall through */ } - const globeHeight = scene.globe?.getHeight?.( - Cesium.Cartographic.fromDegrees(lon, lat), - ); - return Number.isFinite(globeHeight) && globeHeight > 0 ? globeHeight : 0; + const globeHeight = heights.now({ lon, lat }, { against: 'terrain' }); + return globeHeight !== null && globeHeight > 0 ? globeHeight : 0; } function shortLabel(formattedAddress) { diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index 0509a47a56..660a4066a9 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { followedOf } from '../data/followed.js'; import { getOverlayPaintRect } from '../overlays/worldOverlay.js'; import { getActiveTrackedReadoutId, @@ -8,6 +8,15 @@ import { t } from '../i18n/index.js'; import { nextTick } from 'vue'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import { applicationPinia } from '../ui/vueRuntime.js'; +import { heightsOf } from '../queries/heights.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { distance } from '../geo/vector.js'; +import { + canvasOf as sceneCanvasOf, + findCamera, + findFrame, + findQuery, +} from '../render/rendererOf.js'; /** A label whose detailed outline could not be resolved. */ function outlineUnavailableLabel(label) { @@ -78,11 +87,13 @@ export function createScreenAnnotationRenderer( const arrowMarkers = new Map(); let viewBox = null; - const scene = viewer.scene; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - scene.camera.positionWC, - ); + // The eye this frame is projected from (the camera port's pose), and the + // query port and canvas it is projected through, read once per pass. + let pose = null; + let passQuery = null; + let passCanvas = null; + // The renderer's canvas; a viewer with no renderer bound, its own. + const canvasOf = () => sceneCanvasOf(viewer); const records = new Map(); // anno.id -> { key, anno, group, parts } const leaving = new Map(); // key -> a removed mark's record while it fades out const byKey = new Map(); // key -> record, live or fading @@ -91,8 +102,6 @@ export function createScreenAnnotationRenderer( let published = ''; // Only the renderer whose board the store shows may change or remove it. const shown = () => store.board?.owner === owner; - const scratch = new Cesium.Cartesian2(); - const scratchDir = new Cesium.Cartesian3(); // Per-point ground height cache. Marks must sit on the real surface, not at // sea level — otherwise in elevated cities (Austin ~150 m) they project // underground and parallax sinks them at oblique angles. Sampled once the @@ -121,7 +130,7 @@ export function createScreenAnnotationRenderer( // Re-project every annotation each rendered frame so marks stay glued to the // world. postRender runs after the camera/tiles update, so positions are exact. const onPostRender = () => projectAll(); - scene.postRender.addEventListener(onPostRender); + const removePostRender = findFrame(viewer)?.on('postRender', onPostRender); function color(anno) { return PALETTE[anno.color] || PALETTE.primary; @@ -141,15 +150,12 @@ export function createScreenAnnotationRenderer( return cached.h; } try { - if ( - scene.clampToHeightSupported && - typeof scene.clampToHeight === 'function' - ) { - const c = scene.clampToHeight( - Cesium.Cartesian3.fromDegrees(lon, lat, 0), - ); + const heights = heightsOf(viewer); + if (heights.supported().clamp) { + // A miss is tiles not ready. + const c = heights.clampNow(fromDegrees(lon, lat, 0)); if (c) { - const h = Cesium.Cartographic.fromCartesian(c).height; + const h = toLonLatH(c)?.height; if (Number.isFinite(h) && h > -430 && h < 9000) { heightCache.set(key, { h, settled: true, gen: projGen }); trimHeightCache(); @@ -278,7 +284,7 @@ export function createScreenAnnotationRenderer( } // Record the mark BEFORE it reaches the board, then unwind on any throw - // from here down (projectAll reaches into Cesium and can fail on a lost + // from here down (projectAll reaches into the renderer and can fail on a lost // context). Previously a throw past the insert left an ORPHANED mark: the // engine's rollback only deletes its own map entry, so the next annotate // of the same geometry stacked a fresh mark on top of the corpse. @@ -363,26 +369,27 @@ export function createScreenAnnotationRenderer( // Anchor at the real surface height (cached + validated), so marks sit on // the ground/building instead of at sea level. The settle-once cache keeps // it stable (no per-frame jitter that earlier broke nearby projections). - const world = Cesium.Cartesian3.fromDegrees( - lon, - lat, - groundHeight(lon, lat), - ); + const world = fromDegrees(lon, lat, groundHeight(lon, lat)); + if (!pose) return null; // Reject points behind the camera (they produce wrapped/extreme coords). - Cesium.Cartesian3.subtract(world, scene.camera.positionWC, scratchDir); - if (Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0) + const eye = pose.position; + const look = pose.direction; + if ( + (world.x - eye.x) * look.x + + (world.y - eye.y) * look.y + + (world.z - eye.z) * look.z <= + 0 + ) return null; // Reject points beyond the globe horizon. - if (!occluder.isPointVisible(world)) return null; - const win = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - world, - scratch, - ); + const query = passQuery; + if (!query || query.isOccluded(world)) return null; + const win = query.project(world); if (!win || !Number.isFinite(win.x) || !Number.isFinite(win.y)) return null; // Reject absurd off-screen projections (anchor not in view). - const w = scene.canvas.clientWidth || scene.canvas.width; - const h = scene.canvas.clientHeight || scene.canvas.height; + const canvas = passCanvas; + const w = canvas.clientWidth || canvas.width; + const h = canvas.clientHeight || canvas.height; if ( !allowOffscreen && (win.x < -w || win.x > 2 * w || win.y < -h || win.y > 2 * h) @@ -399,9 +406,13 @@ export function createScreenAnnotationRenderer( // from the host's ACTUAL painted rectangle after final layout; the billboard extent // is unioned for aircraft/satellites that also own a native tracked graphic. const TRACKED_BBOX_MARGIN = 8; // px buffer added around the footprint - const TRACKED_FADE_EASE = 0.22; // per-frame ease toward hidden(0) / visible(1) + // Ease toward hidden(0) / visible(1): this share of the gap closes in one + // 60 Hz frame (about 200 ms to settle), scaled by elapsed time so the fade + // takes as long at any refresh rate. + const TRACKED_FADE_EASE = 0.22; + const TRACKED_FADE_FRAME_MS = 1000 / 60; + let trackedFadeAtMs = -Infinity; const TRACKED_HYSTERESIS_PX = 18; // dead-band so the overlap test can't flip-flop - const _scratchTrackedWin = new Cesium.Cartesian2(); // Evaluate a NearFarScalar (billboard scaleByDistance) at a camera distance. function nearFarValue(nfs, dist) { @@ -422,32 +433,23 @@ export function createScreenAnnotationRenderer( let top = painted?.y; let bottom = painted ? painted.y + painted.h : undefined; - const ent = viewer.trackedEntity; - const now = Cesium.JulianDate.now(); + const followed = followedOf(viewer); + const displayPosition = followed?.displayPosition; const world = - typeof ent?.gevDisplayPosition === 'function' - ? ent.gevDisplayPosition() - : null; - const win = world - ? Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - world, - _scratchTrackedWin, - ) - : null; + typeof displayPosition === 'function' ? displayPosition() : null; + const win = world ? (passQuery?.project(world) ?? null) : null; - // Billboard box — centered on the anchor, magnified by scaleByDistance. - const bb = ent?.billboard; - if (bb && win && Number.isFinite(win.x) && Number.isFinite(win.y)) { - const baseW = bb.width?.getValue?.(now) ?? 28; - const baseH = bb.height?.getValue?.(now) ?? 28; + // Billboard box — centered on the anchor, magnified by scaleByDistance, from + // the size the tracking layer recorded for its sprite. + const sprite = followed?.sprite; + if (sprite && win && Number.isFinite(win.x) && Number.isFinite(win.y)) { + const baseW = sprite.width ?? 28; + const baseH = sprite.height ?? 28; let scale = 1; - const sbd = bb.scaleByDistance?.getValue?.(now); - if (sbd) - scale = nearFarValue( - sbd, - Cesium.Cartesian3.distance(scene.camera.positionWC, world), - ); + const sbd = sprite.scaleByDistance; + // No eye to measure from: the sprite's own size. + if (sbd && pose) + scale = nearFarValue(sbd, distance(pose.position, world)); const hw = (baseW * scale) / 2; const hh = (baseH * scale) / 2; const bbLeft = win.x - hw; @@ -476,14 +478,17 @@ export function createScreenAnnotationRenderer( return; } projGen += 1; // new frame: entries touched below are "hot" and survive trimming + pose = findCamera(viewer)?.pose() ?? null; + passQuery = findQuery(viewer); + passCanvas = canvasOf(); const trackedRect = trackedEntityRect(); - occluder.cameraPosition = scene.camera.positionWC; - const h = scene.canvas.clientHeight || scene.canvas.height; - const w = scene.canvas.clientWidth || scene.canvas.width; + const canvas = passCanvas; + const h = canvas.clientHeight || canvas.height; + const w = canvas.clientWidth || canvas.width; viewBox = `0 0 ${w} ${h}`; // Shrink point-marker geometry as the camera pulls back (declutter the blob). const mScale = markScale( - viewer.camera.positionCartographic?.height ?? 1000, + Number.isFinite(pose?.height) ? pose.height : 1000, ); for (const rec of records.values()) { @@ -677,6 +682,14 @@ export function createScreenAnnotationRenderer( // safe and not jarring. function fadeTracked(trackedRect) { if (!shown()) return; + const nowMs = performance.now(); + // A gap longer than a slow frame means the fade was not running (nothing + // followed): it starts again as from one 60 Hz frame. + const gapMs = nowMs - trackedFadeAtMs; + const stepMs = gapMs >= 0 && gapMs <= 100 ? gapMs : TRACKED_FADE_FRAME_MS; + trackedFadeAtMs = nowMs; + const ease = + 1 - Math.pow(1 - TRACKED_FADE_EASE, stepMs / TRACKED_FADE_FRAME_MS); let changed = false; for (const rec of records.values()) { const { anno, group } = rec; @@ -705,10 +718,10 @@ export function createScreenAnnotationRenderer( } } const target = overlapping ? 0 : 1; - const next = cur + (target - cur) * TRACKED_FADE_EASE; + const next = cur + (target - cur) * ease; rec._trackedFade = Math.abs(next - target) < 0.02 ? target : next; // The base alpha applies unless faded. (The CSS `transition: opacity` was - // removed from .gev-anno so this per-frame JS ease is the ONLY easing — + // removed from .gev-anno so this JS ease is the ONLY easing — // previously the two fought and produced an opacity oscillation.) const opacity = String( (anno.alpha ?? 1) * (rec._trackedFade !== 1 ? rec._trackedFade : 1), @@ -821,7 +834,7 @@ export function createScreenAnnotationRenderer( function destroy() { try { - scene.postRender.removeEventListener(onPostRender); + removePostRender?.(); } catch { /* torn down */ } diff --git a/src/annotations/screenAnnotationRenderer.test.mjs b/src/annotations/screenAnnotationRenderer.test.mjs index ce1fb40583..406938cf31 100644 --- a/src/annotations/screenAnnotationRenderer.test.mjs +++ b/src/annotations/screenAnnotationRenderer.test.mjs @@ -6,7 +6,19 @@ import { createApp, nextTick } from 'vue'; import { createPinia } from 'pinia'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import ScreenAnnotations from '../ui/views/panels/ScreenAnnotations.vue'; -import { createScreenAnnotationRenderer } from './screenAnnotationRenderer.js'; +import { createScreenAnnotationRenderer as createRenderer } from './screenAnnotationRenderer.js'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; +import { rendererOf } from '../render/rendererOf.js'; + +/** + * The renderer over a viewer double with the camera, query and frame ports + * bound over it (once per double), and the scene's canvas as the viewer's. + */ +function createScreenAnnotationRenderer(viewer, options) { + if (!rendererOf(viewer)) bindFakeCesiumScene(viewer); + viewer.canvas ??= viewer.scene?.canvas; + return createRenderer(viewer, options); +} // happy-dom does not lay out SVG; every element measures as a 40 x 16 box. for (const type of [globalThis.SVGElement, globalThis.SVGGraphicsElement]) { @@ -53,7 +65,7 @@ function sceneFor(camera, extra = {}) { return { camera, canvas: { clientWidth: 800, clientHeight: 600, width: 800, height: 600 }, - clampToHeightSupported: false, + sampleHeightSupported: false, postRender: { addEventListener() {}, removeEventListener() {} }, ...extra, }; @@ -173,14 +185,13 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => { const sampledAnchors = []; const scene = sceneFor(camera, { canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 }, - clampToHeightSupported: true, - clampToHeight(world) { - const cartographic = Cesium.Cartographic.fromCartesian(world); + sampleHeightSupported: true, + sampleHeight(cartographic) { sampledAnchors.push([ Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(4)), Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(4)), ]); - return world; + return 0; }, }); const renderer = createScreenAnnotationRenderer( @@ -216,7 +227,7 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => { assert.ok(after === before, 'the rendered group is mutated, not replaced'); assert.deepEqual(sampledAnchors.at(-1), [-97.5, 31.2], 'the existing group projects from the re-seated anchor'); assert.equal(groups().length, 1); - assert.equal(after.querySelector('.gev-anno-ring'), null, 'reticle rings are removed in place'); + assert.equal(after.querySelector('.gev-anno-ring') === null, true, 'reticle rings are removed in place'); assert.ok(after.querySelector('.gev-anno-callout') === callout, 'the original callout remains in the group'); assert.ok(after.querySelector('.gev-anno-dot') === dot, 'the anchor dot remains in the group'); assert.ok(svg()); @@ -330,7 +341,7 @@ test('a removed mark fades out, then leaves the board', async (t) => { assert.equal(group.isConnected, false); renderer.destroy(); await settle(); - assert.equal(document.querySelector('.gev-screen-whiteboard'), null); + assert.equal(document.querySelector('.gev-screen-whiteboard') === null, true); }); // ── Partial-add unwind (review round 2) ─────────────────────────────────────── diff --git a/src/annotations/worldAnnotationRenderer.js b/src/annotations/worldAnnotationRenderer.js index 189d46830c..dd4d802ae0 100644 --- a/src/annotations/worldAnnotationRenderer.js +++ b/src/annotations/worldAnnotationRenderer.js @@ -1,64 +1,156 @@ import { recordWorkSlice } from '../sources/phaseTiming.js'; import { ringCentroid } from '../sources/featureGeometry.js'; -import * as Cesium from 'cesium'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { + drawOf, + findCamera, + findFrame, + frameOf, +} from '../render/rendererOf.js'; +import { heightsOf } from '../queries/heights.js'; /** * World-space annotation renderer (Direction A). * - * Draws annotations as native Cesium entities anchored to lon/lat. Because they - * live in the 3D scene they track the camera, sit at the right depth, and are - * occluded by the photoreal buildings the way a real marker would be. + * Draws annotations through the renderer's draw port, anchored to lon/lat. + * Because they live in the 3D scene they track the camera, sit at the right + * depth, and are occluded by the photoreal buildings the way a real marker + * would be. * * IMPORTANT — drawing on Google Photorealistic 3D Tiles: - * The Cesium globe is hidden, so there is no terrain to clamp to. Ground - * geometry (areas, rings, connectors) is draped onto the photoreal tiles with - * `classificationType: CESIUM_3D_TILE`; points clamp to the tile - * surface with `heightReference: CLAMP_TO_GROUND` (which requires the tileset - * to have `enableCollision = true`, set in initAnnotations). This keeps marks - * sitting ON the world instead of buried at sea level. + * The globe is hidden, so there is no terrain to clamp to. Ground geometry + * (areas, rings, connectors) is draped onto the photoreal tiles and the + * terrain alike (`clampTo: 'both'`); points clamp to the surface. This + * keeps marks sitting ON the world instead of buried at sea level. * - * Live alpha (fade in/out) and pulsing are driven by CallbackProperty so they - * animate every render without the engine touching them per frame. + * Fades follow the mark's alpha: the engine calls `sync` as it changes, and + * each mark's items take their new colours where they are. Pulsing fills + * are a declarative pulse the renderer runs; target rings follow the + * camera's height, read before each frame, and are sent again at the radius + * it gives when that changes. + * + * Each mark draws into sets of its own, so adding or removing one leaves + * the others' geometry alone. * * Renderer contract (shared with the screen-space renderer): * add(anno) / remove(anno) / sync(map) / destroy() */ +/** Each palette colour as `r, g, b`, 0..1. */ const PALETTE = { - primary: '#8be9ff', - amber: '#ffb547', - cyan: '#39d0ff', - green: '#5dff9f', - red: '#ff6b6b', + primary: rgb('#8be9ff'), + amber: rgb('#ffb547'), + cyan: rgb('#39d0ff'), + green: rgb('#5dff9f'), + red: rgb('#ff6b6b'), }; +const WHITE = [1, 1, 1]; /** - * What a draped mark is allowed to paint onto. - * - * This was CESIUM_3D_TILE, which is right with Google's photoreal tiles under - * the camera and wrong everywhere else: on a keyless boot (Esri or OSM imagery - * on Cesium's own globe) there are no 3D tiles to classify against, so every - * area fill, area outline, route and arrow rendered to nothing. The labels - * showed and the geometry did not, which reads as a broken feature rather than - * an unsupported surface — and it hit spoken annotations exactly as hard as - * hand-drawn ones. - * - * BOTH paints onto terrain AND onto 3D tiles, so one value covers both worlds. + * What a draped mark is allowed to paint onto: terrain AND 3D tiles, so one + * value covers a keyless boot (imagery on the globe, no tiles) and the + * photoreal world alike. Tiles alone rendered every area, route and arrow to + * nothing on a keyless boot. */ -const CLASSIFY = Cesium.ClassificationType.BOTH; -const CLAMP = Cesium.HeightReference.CLAMP_TO_GROUND; +const CLAMP_TO = 'both'; + +/** + * The pulse of a pulsing fill: its alpha swings between 60% and all of its + * own, a sine of about 0.8 Hz on the wall clock. + */ +const PULSE_MS = (2 * Math.PI) / 0.005; +const PULSE_LOW = 0.6; + +/** Target rings: 3% of the camera's height, between 14 m and 170 m. */ +const RING_RADIUS = Object.freeze({ factor: 0.03, min: 14, max: 170 }); + +/** Relative change of the ring radius under which rings are not redrawn. */ +const RING_RESIZE = 1e-3; + +/** + * A target ring's radius, metres, for a camera `height` metres above the + * ellipsoid; 1000 m stands in for a height the camera cannot give. + * @param {number} height + */ +export function ringRadiusAt(height) { + const h = Number.isFinite(height) ? height : 1000; + return Math.max( + RING_RADIUS.min, + Math.min(RING_RADIUS.max, h * RING_RADIUS.factor), + ); +} + +/** + * Each renderer's sets have ids of their own, unique across copies of this + * module on one viewer too. + */ +let rendererSeq = 0; +const MODULE_TOKEN = Math.random().toString(36).slice(2, 8); export function createWorldAnnotationRenderer(viewer) { - const dataSource = new Cesium.CustomDataSource('gev-annotations'); - viewer.dataSources.add(dataSource); + const draw = drawOf(viewer); + const instance = `${MODULE_TOKEN}${(rendererSeq += 1)}`; + let markSeq = 0; const osmAnnotations = new Set(); - // Every mark with entities on the globe, so sync() can take a hidden one out. + // Every mark with sets on the globe, so sync() can take a hidden one out. const drawn = new Set(); const pendingGround = new Map(); const groundQueue = []; - let observingGround = false; + let offGroundFrame = null; let destroyed = false; + // Marks with a target ring, and the radius they are drawn at. + const ringed = new Set(); + let offRingFrame = null; + let ringRadius = ringRadiusAt(cameraHeight()); + + /** The camera's height above the ellipsoid, or NaN when it has none. */ + function cameraHeight() { + try { + return findCamera(viewer)?.pose().height ?? Number.NaN; + } catch { + return Number.NaN; + } + } + + /** The current ring radius, for the items that draw rings. */ + const ringRadiusNow = () => ringRadius; + + /** + * Before each frame: when the camera's height gives the rings another + * radius, every shown mark's ring is sent again at it. A hidden mark's + * ring catches up when it shows (`sync`). + */ + function followRings() { + const radius = ringRadiusAt(cameraHeight()); + if (Math.abs(radius - ringRadius) <= RING_RESIZE * ringRadius) return; + ringRadius = radius; + for (const anno of ringed) if (!anno.hidden) resizeRing(anno); + } + + /** Send a mark's ring again at the current radius, when it differs. */ + function resizeRing(anno) { + const was = anno._drawn; + const set = anno._draw?.shapes; + if (!was?.ring || !set || was.ringRadius === ringRadius) return; + was.ringRadius = ringRadius; + set.upsert([was.ring(was.alpha)]); + } + + /** + * Keep the ring frame listener while any mark has a ring. A host with no + * frame port draws its rings at the radius they were added with. + */ + function watchRings() { + if (ringed.size && !offRingFrame) + offRingFrame = findFrame(viewer)?.on('preRender', followRings) ?? null; + else if (!ringed.size && offRingFrame) { + offRingFrame(); + offRingFrame = null; + } + } + + const requestRender = () => frameOf(viewer).requestRender('annotations'); function sampleBuilding(anno, options) { pendingGround.get(anno)?.finish('cancelled'); @@ -107,7 +199,7 @@ export function createWorldAnnotationRenderer(viewer) { // A task promoted outside a frame (its predecessor timed out or was // cancelled) still needs frames in request-render mode. try { - viewer.scene.requestRender?.(); + requestRender(); } catch { /* the enqueue path reports render failures */ } @@ -120,9 +212,9 @@ export function createWorldAnnotationRenderer(viewer) { clearTimeout(task.timer); if (position === 0) groundQueue[0]?.begin(); options.signal?.removeEventListener('abort', task.abort); - if (!groundQueue.length && observingGround) { - viewer.scene.postRender.removeEventListener(onGroundFrame); - observingGround = false; + if (!groundQueue.length && offGroundFrame) { + offGroundFrame(); + offGroundFrame = null; } timing.elapsedMs = performance.now() - (started ?? queuedAt); if (workTrace) { @@ -174,28 +266,25 @@ export function createWorldAnnotationRenderer(viewer) { const sliceStart = performance.now(); let error; try { - if ( - viewer.scene.clampToHeightSupported && - typeof viewer.scene.clampToHeight === 'function' - ) { + // Without depth support the surface answers nothing: the + // probes are skipped, and the fallback height is taken. + if (heightsOf(viewer).supported().surface) { const [lon, lat] = task.points[task.index++]; timing.probes += 1; try { - const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0); - let c; + let h; note?.('clampStart'); - if (detail) detail.clampResult = 'threw'; try { - c = viewer.scene.clampToHeight(position); - if (detail) detail.clampResult = 'returned'; + // The surface under the probe: the drawn tiles or terrain, + // never a mark (no draw set is in height queries). + h = heightsOf(viewer).now({ lon, lat }); + if (detail) + detail.clampResult = Number.isFinite(h) ? 'hit' : 'missed'; } finally { note?.('clampEnd'); } - if (c) { - const h = Cesium.Cartographic.fromCartesian(c).height; - if (Number.isFinite(h) && h > -430 && h < 9000) - task.samples.push(h); - } + if (Number.isFinite(h) && h > -430 && h < 9000) + task.samples.push(h); } catch { /* surface not ready: preserve the existing sample filter */ } @@ -240,7 +329,7 @@ export function createWorldAnnotationRenderer(viewer) { task.finish('installed'); } finally { // Commit includes sort/selection/add/deadline/finish or rollback, - // including intervening bookkeeping; it is not exclusive entity cost. + // including intervening bookkeeping; it is not exclusive draw cost. if (detail?.commitStatus === 'attempted') note('commitEnd'); if (workTrace) recordWorkSlice( @@ -257,12 +346,10 @@ export function createWorldAnnotationRenderer(viewer) { if (groundQueue[0] === task) task.begin(); options.signal?.addEventListener('abort', task.abort, { once: true }); if (!task.current()) return task.finish('cancelled'); - if (!observingGround) { - viewer.scene.postRender.addEventListener(onGroundFrame); - observingGround = true; - } try { - viewer.scene.requestRender?.(); + if (!offGroundFrame) + offGroundFrame = frameOf(viewer).on('postRender', onGroundFrame); + requestRender(); } catch (error) { task.finish('failed', error); } @@ -274,49 +361,43 @@ export function createWorldAnnotationRenderer(viewer) { const task = groundQueue[0]; try { task?.step(); - if (groundQueue.length) viewer.scene.requestRender?.(); + if (groundQueue.length) requestRender(); } catch (error) { for (const pending of [...groundQueue]) pending.finish('failed', error); } } - - // Register the GevRouteFlow fabric once so Cesium's Material.fromType() can build the - // material the route pipeline renders. The animated `time` uniform is read straight - // from performance.now() inside FlowMaterialProperty.getValue (which Cesium calls each - // rendered frame with the live uniforms object), so the dashes flow with no extra - // per-frame bookkeeping. - ensureFlowFabricRegistered(); - - function colorFor(anno) { - return Cesium.Color.fromCssColorString( - PALETTE[anno.color] || PALETTE.primary, - ); + /** + * The mark's draw sets, made on first use: shapes (fills, volumes, rings), + * lines (outlines, routes, arrows) and points (markers). + */ + function setsOf(anno) { + if (!anno._draw) { + markSeq += 1; + const prefix = `annotations:${instance}:${markSeq}`; + anno._draw = { prefix, shapes: null, lines: null, points: null }; + } + return anno._draw; } - // Target-ring radius (meters) scaled to camera height so it reads at any - // altitude. Read once per frame for BOTH ellipse axes — camera height is - // constant within a frame, so semiMajor === semiMinor always holds. - function ringRadius() { - const h = viewer.camera.positionCartographic?.height ?? 1000; - return Math.max(14, Math.min(170, h * 0.03)); - } - - // A live color that follows the annotation's fade alpha and an optional pulse. - function liveColor(anno, base, { alpha = 0.9, pulse = false } = {}) { - return new Cesium.CallbackProperty(() => { - const a = (anno.alpha ?? 1) * alpha * (pulse ? pulseFactor() : 1); - return base.withAlpha(Math.max(0, Math.min(1, a))); - }, false); + function setOf(anno, kind) { + const sets = setsOf(anno); + if (!sets[kind]) { + sets[kind] = draw[kind]({ + id: `${sets.prefix}:${kind}`, + clampTo: CLAMP_TO, + show: !anno.hidden, + }); + } + return sets[kind]; } function add(anno, options = {}) { - const base = colorFor(anno); - // Published to the mark BEFORE anything is added, and mutated in place as - // each entity lands: a mid-add failure (bad geometry, lost context) must - // leave the entities that DID land visible to remove(), or the rollback - // path cannot reach them and they stay on the globe forever. - const entities = []; - anno._entities = entities; + // A destroyed renderer draws nothing more. + if (destroyed) return; + // Published to the mark BEFORE anything is drawn: a mid-add failure (bad + // geometry, lost context) must leave the sets that DID land visible to + // remove(), or the rollback path cannot reach them and they stay on the + // globe forever. drawn.add(anno); if ( @@ -327,253 +408,43 @@ export function createWorldAnnotationRenderer(viewer) { return sampleBuilding(anno, options); } - if ( - anno.ring && - anno.ring.length >= 3 && - anno.footprintKind === 'building' - ) { - const addBuildingEntity = (definition) => { - if (!(options.isCurrent?.() ?? true)) - throw new Error('Building install cancelled'); - const entity = dataSource.entities.add(definition); - if (!(options.isCurrent?.() ?? true)) { - dataSource.entities.remove(entity); - throw new Error('Building install cancelled'); - } - return entity; - }; - // Single building → the PRIMARY highlight is an extruded CLASSIFICATION - // volume that tints the real photogrammetry mesh (dome, walls, roof — - // everything inside the column) amber and pulses. A flat footprint - // extrusion is only 2.5D and misses domes; classification colors the - // actual tiles. A faint wireframe cage rides on top as a secondary cue. - const parts = - Array.isArray(anno.polygons) && anno.polygons.length - ? anno.polygons - : [[anno.ring]]; - const groundH = - options.sampledGroundHeight ?? - (Number.isFinite(anno.anchor.height) - ? anno.anchor.height - (anno.buildingHeight || 25) - : 0); - const baseH = groundH - 3; - // Tall headroom is free: classification only colors where tiles exist, so - // empty air above the roof isn't tinted — this just guarantees we cover - // under-tagged building heights. - const topH = groundH + Math.max(18, anno.buildingHeight || 25) + 24; - const fillMaterial = new Cesium.ColorMaterialProperty( - liveColor(anno, base, { alpha: 0.45, pulse: true }), - ); - const lineMaterial = new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.25, - color: liveColor(anno, base, { alpha: 0.7 }), - }); - for (const [outer, ...holes] of parts) { - const buffered = bufferRing(outer, 3); - const positions = Cesium.Cartesian3.fromDegreesArray(buffered.flat()); - // 1) Classification volume — tints the mesh amber, pulsing. - entities.push( - addBuildingEntity({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - positions, - holes.map( - (hole) => - new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(hole.flat()), - ), - ), - ), - height: baseH, - extrudedHeight: topH, - perPositionHeight: false, - classificationType: CLASSIFY, - material: fillMaterial, - }, - }), - ); - // 2) Faint, SIMPLIFIED wireframe cage — secondary, lower opacity. Decimate - // the footprint so the extruded outline draws ~14 clean verticals, not one - // per (often 100+) ring vertex. - const cagePositions = Cesium.Cartesian3.fromDegreesArray( - decimateRing(buffered, 14).flat(), - ); - entities.push( - addBuildingEntity({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy(cagePositions), - height: baseH, - extrudedHeight: topH, - perPositionHeight: false, - fill: false, - outline: true, - outlineColor: liveColor(anno, base, { alpha: 0.32, pulse: true }), - }, - }), - ); - // 3) Crisp draped base outline so the footprint reads on the ground. - for (const ring of [outer, ...holes]) { - entities.push( - addBuildingEntity({ - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - closedRing(ring).flat(), - ), - width: 3, - material: lineMaterial, - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } + // Rings not yet followed take the camera's height now. + if (!offRingFrame) ringRadius = ringRadiusAt(cameraHeight()); + const items = itemsOf(anno, options, ringRadiusNow); + anno._drawn = { + alpha: alphaOf(anno), + items, + ring: items.ring, + ringRadius, + }; + if (items.ring) ringed.add(anno); + else ringed.delete(anno); + watchRings(); + const current = () => options.isCurrent?.() ?? true; + const building = anno.footprintKind === 'building'; + for (const kind of ['shapes', 'lines', 'points']) { + if (!items[kind].length) { + // Added again as another kind: what it drew before goes. + disposeSet(anno, kind); + continue; } - } else if (anno.ring && anno.ring.length >= 3) { - // Larger area (district / compound / park / state) → flat fill draped on - // the tiles + a glowing outline. Draping is right here: you can't extrude - // a whole neighbourhood, and the GIS overlay shows the boundary clearly. - // A multi-part outline (`anno.polygons`: Hawaii's islands, Berlin as a - // hole in Brandenburg) draws every part with its holes. All parts share - // ONE fill and ONE line material, so Cesium batches the whole mark into a - // ground primitive per kind instead of one per island. - const parts = - Array.isArray(anno.polygons) && anno.polygons.length - ? anno.polygons - : [[anno.ring]]; - const fillMaterial = new Cesium.ColorMaterialProperty( - // Synthesized (approximate) areas get a fainter fill so they don't read as solid. - liveColor(anno, base, { - alpha: anno.synthesized ? 0.1 : 0.2, - pulse: true, - }), - ); - // Synthesized → DASHED outline (signals "approximate, not an authoritative - // boundary", research §8.4/§8.6); real footprints → solid glow. - const lineMaterial = anno.synthesized - ? new Cesium.PolylineDashMaterialProperty({ - color: liveColor(anno, base, { alpha: 0.95 }), - dashLength: 24, - }) - : new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.35, - color: liveColor(anno, base, { alpha: 1 }), - }); - for (const [outer, ...holes] of parts) { - if (!Array.isArray(outer) || outer.length < 3) continue; - const rings = [outer, ...holes.filter((h) => h?.length >= 3)]; - entities.push( - dataSource.entities.add({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(outer.flat()), - rings - .slice(1) - .map( - (hole) => - new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(hole.flat()), - ), - ), - ), - material: fillMaterial, - classificationType: CLASSIFY, - }, - }), - ); - for (const ring of rings) { - entities.push( - dataSource.entities.add({ - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - closedRing(ring).flat(), - ), - width: 6, - material: lineMaterial, - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } + if (building && !current()) throw new Error('Building install cancelled'); + setOf(anno, kind).set(items[kind].map((item) => item(anno._drawn.alpha))); + if (building && !current()) { + clearSets(anno); + throw new Error('Building install cancelled'); } - } else if ( - anno.type === 'route' && - Array.isArray(anno.path) && - anno.path.length >= 2 - ) { - // A real path (street-following) draped on the 3D tiles, with dashes that - // FLOW toward the destination (custom st.s + time material; works on the - // clamped/classified ground polyline). - const positions = Cesium.Cartesian3.fromDegreesArray( - anno.path.flatMap((p) => [p.lon, p.lat]), - ); - entities.push( - dataSource.entities.add({ - polyline: { - positions, - width: 9, - material: new FlowMaterialProperty( - PALETTE[anno.color] || PALETTE.primary, - () => anno.alpha ?? 1, - ), - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); + } + if (anno.type === 'route' && items.lines.length) { osmAnnotations.add(anno); showOsmCredit(viewer, anno); - } else if (anno.type === 'arrow' && anno.to) { - // Connector draped across the ground from origin to destination. - const positions = [ - Cesium.Cartesian3.fromDegrees(anno.anchor.lon, anno.anchor.lat), - Cesium.Cartesian3.fromDegrees(anno.to.lon, anno.to.lat), - ]; - entities.push( - dataSource.entities.add({ - polyline: { - positions, - width: 16, - material: new Cesium.PolylineArrowMaterialProperty( - liveColor(anno, base, { alpha: 0.95 }), - ), - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } else { - // pin / highlight / label — a camera-proportional target ring + a marker. - if (anno.type !== 'label') { - // Radius scales with camera height so the ring reads at any altitude. - // semiMajor === semiMinor is required AND must hold every frame, so both - // axes read the SAME ringRadius() (camera height is constant per frame). - entities.push( - dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees( - anno.anchor.lon, - anno.anchor.lat, - ), - ellipse: { - semiMajorAxis: new Cesium.CallbackProperty(ringRadius, false), - semiMinorAxis: new Cesium.CallbackProperty(ringRadius, false), - material: new Cesium.ColorMaterialProperty( - liveColor(anno, base, { alpha: 0.38, pulse: true }), - ), - outline: false, - classificationType: CLASSIFY, - }, - }), - ); - } - entities.push(pointMarker(anno, base)); } if ( - entities.length && + (items.shapes.length || items.lines.length || items.points.length) && anno.ring?.length >= 3 && !anno.synthesized && (anno.outlineCredit === 'tiles' || anno.outlineCredit === 'osm') && - (options.isCurrent?.() ?? true) + current() ) { // The actual world proxy owns both geometry and credit, including rollback. osmAnnotations.add(anno); @@ -583,19 +454,19 @@ export function createWorldAnnotationRenderer(viewer) { } } - // Captions belong to the hybrid renderer's screen-space callouts. - function pointMarker(anno, base) { - return dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees(anno.anchor.lon, anno.anchor.lat), - point: { - pixelSize: anno.type === 'label' ? 8 : 14, - color: liveColor(anno, base, { alpha: 1 }), - outlineColor: liveColor(anno, Cesium.Color.WHITE, { alpha: 0.95 }), - outlineWidth: 3, - heightReference: CLAMP, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + function disposeSet(anno, kind) { + const sets = anno?._draw; + if (!sets?.[kind]) return; + try { + sets[kind].dispose(); + } catch { + /* already gone */ + } + sets[kind] = null; + } + + function clearSets(anno) { + for (const kind of ['shapes', 'lines', 'points']) disposeSet(anno, kind); } function remove(anno) { @@ -603,27 +474,39 @@ export function createWorldAnnotationRenderer(viewer) { hideOsmCredit(viewer, anno); osmAnnotations.delete(anno); drawn.delete(anno); - if (!anno?._entities) return; - for (const entity of anno._entities) { - try { - dataSource.entities.remove(entity); - } catch { - /* already gone */ - } + ringed.delete(anno); + watchRings(); + clearSets(anno); + if (anno) { + anno._draw = null; + anno._drawn = null; } - anno._entities = null; } /** - * CallbackProperty drives per-frame alpha and pulse. A hidden mark is taken - * out whole, so no material that keeps its own colour (the route's flow), - * ground classification or pick can still show it. + * A hidden mark is taken out whole (its sets hidden), so no fill, line or + * pick can still show it; a mark whose alpha moved (fading in or out) + * takes its new colours in place. */ function sync() { for (const anno of drawn) { + const sets = anno._draw; + if (!sets) continue; const show = !anno.hidden; - for (const entity of anno._entities || []) - if (entity.show !== show) entity.show = show; + for (const kind of ['shapes', 'lines', 'points']) + if (sets[kind] && sets[kind].show !== show) sets[kind].show = show; + const was = anno._drawn; + const alpha = alphaOf(anno); + if (!was || was.alpha === alpha) { + // Shown again: its ring catches up with the camera. + if (show) resizeRing(anno); + continue; + } + was.alpha = alpha; + was.ringRadius = ringRadius; + for (const kind of ['shapes', 'lines', 'points']) + if (sets[kind] && was.items[kind].length) + sets[kind].upsert(was.items[kind].map((item) => item(alpha))); } } @@ -632,114 +515,234 @@ export function createWorldAnnotationRenderer(viewer) { for (const task of [...pendingGround.values()]) task.finish('cancelled'); for (const anno of osmAnnotations) hideOsmCredit(viewer, anno); osmAnnotations.clear(); - drawn.clear(); - try { - viewer.dataSources.remove(dataSource, true); - } catch { - /* scene torn down */ + ringed.clear(); + watchRings(); + for (const anno of drawn) { + clearSets(anno); + anno._draw = null; + anno._drawn = null; } + drawn.clear(); } return { add, remove, sync, destroy }; } -function pulseFactor() { - // 0.6 .. 1.0 sinusoid at ~0.8 Hz - return 0.8 + 0.2 * Math.sin(performance.now() * 0.005); -} +/** A mark's alpha as drawn, 0..1. */ +const alphaOf = (anno) => Math.max(0, Math.min(1, anno.alpha ?? 1)); -/** - * A custom Fabric polyline material whose dashes flow toward the destination. - * `materialInput.st.s` is the along-line coordinate (0 = origin, 1 = destination), - * so `fract(s*repeat - time*speed)` scrolls the pattern toward the end. Works on - * a clamped/classified ground polyline (PolylineMaterialAppearance supports it). - */ -function makeRouteFlowMaterial(colorCss) { - return new Cesium.Material({ - fabric: { - type: 'GevRouteFlow', - uniforms: { - color: Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95), - time: 0.0, - repeat: 64.0, // dash cells along the whole route - duty: 0.46, // fraction of each cell that is "on" - speed: 0.55, // cells per second toward the destination - }, - source: ` - czm_material czm_getMaterial(czm_materialInput materialInput) { - czm_material m = czm_getDefaultMaterial(materialInput); - float s = materialInput.st.s; // 0 origin -> 1 dest - float flow = fract(s * repeat - time * speed); // scroll toward dest - float on = smoothstep(duty + 0.08, duty - 0.08, flow); - // keep a faint baseline so the whole route stays readable between dashes - float a = max(on, 0.18); - m.diffuse = color.rgb; - m.emission = color.rgb * on * 0.9; // glow on the lit cells - m.alpha = color.a * a; - return m; - }`, - }, - }); -} +/** `[r, g, b, a]` for a palette colour at `alpha`. */ +const colour = (base, alpha) => [base[0], base[1], base[2], alpha]; -let _flowFabricRegistered = false; -/** Register the GevRouteFlow fabric ONCE so Cesium's `Material.fromType('GevRouteFlow')` - * can build the material the render pipeline uses. Constructing one Material with the - * fabric caches it under its type name. */ -export function ensureFlowFabricRegistered() { - if (_flowFabricRegistered) return; - makeRouteFlowMaterial('#ffffff'); // side effect: registers the 'GevRouteFlow' type - _flowFabricRegistered = true; -} - -/** - * MaterialProperty for the animated route. Cesium builds the rendered Material once - * from getType() (our registered GevRouteFlow fabric), then EACH FRAME calls - * getValue(time, material.uniforms) and uses whatever we write INTO that uniforms - * object — it ignores the return value. So getValue writes color/time/repeat/duty/ - * speed straight onto `result` (the live uniforms). Writing the animated `time` here - * is what actually makes the dashes flow on the GPU. (The prior versions either - * returned a standalone Material Cesium never rendered, or treated `result` as a - * Material — both left the real uniforms untouched, so nothing animated.) - */ -export function FlowMaterialProperty(colorCss, alphaOf = () => 1) { - this._color = Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95); - // The mark's live alpha (fade in and out, hidden), applied every frame. - this._alphaOf = alphaOf; - this._live = this._color.clone(); - this._definitionChanged = new Cesium.Event(); -} -Object.defineProperties(FlowMaterialProperty.prototype, { - isConstant: { - get() { - return false; - }, - }, // re-evaluated each frame → it animates - definitionChanged: { - get() { - return this._definitionChanged; - }, - }, +/** A fill or outline that pulses about `alpha`. */ +const pulse = (alpha) => ({ + property: 'alpha', + from: alpha * PULSE_LOW, + to: alpha, + periodMs: PULSE_MS, }); -FlowMaterialProperty.prototype.getType = function getType() { - return 'GevRouteFlow'; -}; -FlowMaterialProperty.prototype.getValue = function getValue(time, result) { - // `result` IS the live uniforms object Cesium renders — write into it directly. - // `time` is read straight from the wall clock so the dashes flow every rendered - // frame (the scene renders continuously; no requestRenderMode here). - if (!Cesium.defined(result)) result = {}; - this._live.alpha = this._color.alpha * this._alphaOf(); - result.color = this._live; - result.time = performance.now() / 1000; // the per-frame animated value - result.repeat = 64.0; - result.duty = 0.46; - result.speed = 0.55; - return result; -}; -FlowMaterialProperty.prototype.equals = function equals(other) { - return this === other; -}; + +/** + * What a mark draws, as item makers by kind, each taking the mark's alpha: + * built once per add, called again on each fade step. `ring` is the target + * ring's maker among the shapes, drawn at `ringRadiusNow()`. + */ +function itemsOf(anno, options, ringRadiusNow) { + const base = PALETTE[anno.color] || PALETTE.primary; + const shapes = []; + const lines = []; + const points = []; + const meta = { annotation: anno.id }; + let ring = null; + const draped = (id, positions, widthPx, style) => (alpha) => ({ + id, + positions, + widthPx, + mode: 'draped', + clampTo: CLAMP_TO, + style: style(alpha), + meta, + }); + if (anno.ring?.length >= 3 && anno.footprintKind === 'building') { + // Single building → the PRIMARY highlight is a translucent extruded + // column round the building that pulses, from just under its ground to + // well over its roof, with a faint wireframe cage on it as a secondary + // cue and a crisp draped base outline. + const parts = + Array.isArray(anno.polygons) && anno.polygons.length + ? anno.polygons + : [[anno.ring]]; + const groundH = + options.sampledGroundHeight ?? + (Number.isFinite(anno.anchor.height) + ? anno.anchor.height - (anno.buildingHeight || 25) + : 0); + const baseH = groundH - 3; + // Tall headroom so under-tagged building heights are covered too. + const topH = groundH + Math.max(18, anno.buildingHeight || 25) + 24; + const at = (ring) => + ring.map(([lon, lat]) => ({ lon, lat, height: baseH })); + parts.forEach(([outer, ...holes], p) => { + const buffered = bufferRing(outer, 3); + // Built once: a fade step only changes colours. + const volume = { kind: 'polygon', rings: [buffered, ...holes].map(at) }; + shapes.push((alpha) => ({ + id: `volume:${p}`, + geometry: volume, + fill: colour(base, 0.45 * alpha), + animate: pulse(0.45 * alpha), + extrudeHeight: topH, + height: 'absolute', + meta, + })); + // Faint, SIMPLIFIED wireframe cage: the footprint decimated so the + // extruded outline draws ~14 clean verticals, not one per (often + // 100+) ring vertex. + const cage = { + kind: 'polygon', + rings: [at(decimateRing(buffered, 14))], + }; + shapes.push((alpha) => ({ + id: `cage:${p}`, + geometry: cage, + outline: colour(base, 0.32 * alpha), + outlineOnly: true, + animate: pulse(0.32 * alpha), + extrudeHeight: topH, + height: 'absolute', + meta, + })); + [outer, ...holes].forEach((ring, r) => + lines.push( + draped(`base:${p}:${r}`, ecefOf(closedRing(ring)), 3, (alpha) => ({ + kind: 'glow', + color: colour(base, 0.7 * alpha), + power: 0.25, + })), + ), + ); + }); + } else if (anno.ring?.length >= 3) { + // Larger area (district / compound / park / state) → flat fill draped on + // the tiles + a glowing outline. Draping is right here: you can't extrude + // a whole neighbourhood, and the GIS overlay shows the boundary clearly. + // A multi-part outline (`anno.polygons`: Hawaii's islands, Berlin as a + // hole in Brandenburg) draws every part with its holes. + const parts = + Array.isArray(anno.polygons) && anno.polygons.length + ? anno.polygons + : [[anno.ring]]; + // Synthesized (approximate) areas get a fainter fill so they don't read + // as solid, and a DASHED outline (signals "approximate, not an + // authoritative boundary", research §8.4/§8.6); real footprints a solid + // glow. + const fillAlpha = anno.synthesized ? 0.1 : 0.2; + const style = anno.synthesized + ? (alpha) => ({ + kind: 'dash', + color: colour(base, 0.95 * alpha), + length: 24, + }) + : (alpha) => ({ kind: 'glow', color: colour(base, alpha), power: 0.35 }); + parts.forEach(([outer, ...holes], p) => { + if (!Array.isArray(outer) || outer.length < 3) return; + const rings = [outer, ...holes.filter((h) => h?.length >= 3)]; + const area = { + kind: 'polygon', + rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))), + }; + shapes.push((alpha) => ({ + id: `fill:${p}`, + geometry: area, + fill: colour(base, fillAlpha * alpha), + animate: pulse(fillAlpha * alpha), + height: 'clampGround', + clampTo: CLAMP_TO, + meta, + })); + rings.forEach((ring, r) => + lines.push( + draped(`outline:${p}:${r}`, ecefOf(closedRing(ring)), 6, style), + ), + ); + }); + } else if ( + anno.type === 'route' && + Array.isArray(anno.path) && + anno.path.length >= 2 + ) { + // A real path (street-following) draped on the surface, with dashes that + // FLOW toward the destination. + lines.push( + draped( + 'route', + anno.path.map((p) => fromDegrees(p.lon, p.lat, 0)), + 9, + (alpha) => ({ + kind: 'flow', + color: colour(base, 0.95 * alpha), + repeat: 64, + duty: 0.46, + speed: 0.55, + }), + ), + ); + } else if (anno.type === 'arrow' && anno.to) { + // Connector draped across the ground from origin to destination. + lines.push( + draped( + 'arrow', + [ + fromDegrees(anno.anchor.lon, anno.anchor.lat, 0), + fromDegrees(anno.to.lon, anno.to.lat, 0), + ], + 16, + (alpha) => ({ kind: 'arrow', color: colour(base, 0.95 * alpha) }), + ), + ); + } else { + // pin / highlight / label — a camera-proportional target ring + a marker. + const pos = { lon: anno.anchor.lon, lat: anno.anchor.lat }; + if (anno.type !== 'label') { + ring = (alpha) => ({ + id: 'ring', + geometry: { + kind: 'ellipse', + center: pos, + semiMajor: ringRadiusNow(), + semiMinor: ringRadiusNow(), + }, + fill: colour(base, 0.38 * alpha), + animate: pulse(0.38 * alpha), + height: 'clampGround', + clampTo: CLAMP_TO, + meta, + }); + shapes.push(ring); + } + // Captions belong to the hybrid renderer's screen-space callouts. + points.push((alpha) => ({ + id: 'marker', + pos, + height: 'clampGround', + pixelSize: anno.type === 'label' ? 8 : 14, + color: colour(base, alpha), + outlineColor: colour(WHITE, 0.95 * alpha), + outlineWidth: 3, + disableDepthTest: Number.POSITIVE_INFINITY, + meta, + })); + } + return { shapes, lines, points, ring }; +} + +/** `[lon, lat]` pairs as ECEF positions on the ellipsoid. */ +const ecefOf = (ring) => ring.map(([lon, lat]) => fromDegrees(lon, lat, 0)); + +function rgb(css) { + const n = parseInt(css.slice(1), 16); + return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; +} /** The ring with its first vertex repeated at the end, so an outline closes. */ function closedRing(ring) { @@ -763,7 +766,7 @@ function decimateRing(ring, n) { function groundProbePositions(ring) { const { lon: clon, lat: clat } = ringCentroid(ring); const latS = 111320; - const lonS = latS * Math.cos(Cesium.Math.toRadians(clat)); + const lonS = latS * Math.cos((clat * Math.PI) / 180); let maxR = 0; for (const [lon, lat] of ring) { maxR = Math.max(maxR, Math.hypot((lon - clon) * lonS, (lat - clat) * latS)); @@ -801,7 +804,7 @@ function bufferRing(ring, meters) { clon /= ring.length; clat /= ring.length; const latScale = 111320; - const lonScale = latScale * Math.cos(Cesium.Math.toRadians(clat)); + const lonScale = latScale * Math.cos((clat * Math.PI) / 180); return ring.map(([lon, lat]) => { const dx = (lon - clon) * lonScale; const dy = (lat - clat) * latScale; diff --git a/src/annotations/worldAnnotationRenderer.test.mjs b/src/annotations/worldAnnotationRenderer.test.mjs index a05c52373f..62e0b65749 100644 --- a/src/annotations/worldAnnotationRenderer.test.mjs +++ b/src/annotations/worldAnnotationRenderer.test.mjs @@ -1,70 +1,448 @@ -// A mark hidden from Draw's list leaves the globe whole: every entity it put -// there is taken out on sync and comes back when shown, and the line's -// flowing stroke, which keeps its own colour, follows the mark's alpha. +// The world renderer draws each mark through the draw port, in sets of its +// own: a hidden mark has its sets hidden on sync and shown again; a fading +// mark takes its new colours in place; every kind draws what it drew as +// entities, draped and clamped to terrain and tiles alike. import test from 'node:test'; import assert from 'node:assert/strict'; -import * as C from 'cesium'; -import { - FlowMaterialProperty, - createWorldAnnotationRenderer, -} from './worldAnnotationRenderer.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js'; -const noop = () => {}; -function viewer(t) { - for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) { - const original = globalThis[name]; - globalThis[name] = class {}; - t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; }); - } - const before = globalThis.document; - globalThis.document = { addEventListener: noop, removeEventListener: noop }; - t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; }); +/** + * A viewer with a fake draw port, frame, camera and query bound. The camera + * stands at `camera.height`; `preRender()` runs the frame's preRender + * listeners, `emit()` its postRender ones. + */ +function viewer(t, { heights = () => null } = {}) { + const draw = fakeDrawPort(); + const frames = new Set(); + const before = new Set(); + const v = { requests: 0 }; + const frame = { + on(phase, cb) { + const listeners = + phase === 'postRender' ? frames : phase === 'preRender' ? before : null; + if (!listeners) return () => {}; + listeners.add(cb); + return () => listeners.delete(cb); + }, + requestRender() { + v.requests += 1; + }, + }; + const camera = { height: 2000, pose: () => ({ height: camera.height }) }; + const query = { sampleHeightNow: (point) => heights(point) }; + const unbind = bindRenderer(v, { draw, frame, query, camera }); + t.after(unbind); return { - creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop }, - entities: new C.EntityCollection(), - dataSources: new C.DataSourceCollection(), - camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } }, - scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(), - primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } }, + v, + draw, + frames, + before, + camera, + emit: () => [...frames].forEach((cb) => cb()), + preRender: () => [...before].forEach((cb) => cb()), }; } const marks = () => [ - { id: 'route', type: 'route', color: 'amber', alpha: 1, anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] }, - { id: 'area', type: 'area', color: 'green', alpha: 1, anchor: { lat: 0.005, lon: 0.005 }, ring: [[0, 0], [0.01, 0], [0.01, 0.01], [0, 0]] }, - { id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } }, + { + id: 'route', + type: 'route', + color: 'amber', + alpha: 1, + anchor: { lat: 0, lon: 0 }, + path: [ + { lat: 0, lon: 0 }, + { lat: 0.01, lon: 0.01 }, + ], + }, + { + id: 'area', + type: 'area', + color: 'green', + alpha: 1, + anchor: { lat: 0.005, lon: 0.005 }, + ring: [ + [0, 0], + [0.01, 0], + [0.01, 0.01], + [0, 0], + ], + }, + { + id: 'pin', + type: 'pin', + color: 'primary', + alpha: 1, + anchor: { lat: 0.02, lon: 0.02 }, + }, ]; -test('a hidden mark has every entity taken off on sync, and back when shown', (t) => { - const renderer = createWorldAnnotationRenderer(viewer(t)); +/** The live sets a mark draws into. */ +const setsOf = (draw, anno) => + [...draw.sets.values()].filter( + (record) => + !record.disposed && record.spec.id.startsWith(`${anno._draw.prefix}:`), + ); + +test('each mark draws in sets of its own; a hidden one has them hidden on sync, and back when shown', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); const [route, area, pin] = marks(); for (const anno of [route, area, pin]) renderer.add(anno); - const shown = (anno) => anno._entities.map((entity) => entity.show); - for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id); + for (const anno of [route, area, pin]) + assert.ok(setsOf(draw, anno).length > 0, anno.id); + const shown = (anno) => setsOf(draw, anno).map((record) => record.show); route.hidden = true; area.hidden = true; renderer.sync(); - assert.ok(shown(route).every((show) => show === false), 'the line is off'); - assert.ok(shown(area).every((show) => show === false), 'the area is off'); - assert.ok(shown(pin).every((show) => show === true), 'a visible mark stays'); + assert.ok( + shown(route).every((show) => show === false), + 'the line is off', + ); + assert.ok( + shown(area).every((show) => show === false), + 'the area is off', + ); + assert.ok( + shown(pin).every((show) => show === true), + 'a visible mark stays', + ); route.hidden = false; renderer.sync(); - assert.ok(shown(route).every((show) => show === true), 'the line is back'); + assert.ok( + shown(route).every((show) => show === true), + 'the line is back', + ); + const areaSets = setsOf(draw, area); renderer.remove(area); + assert.ok( + areaSets.every((record) => record.disposed), + 'a removed mark lets its sets go', + ); renderer.sync(); - assert.equal(area._entities, null, 'a removed mark is no longer synced'); + renderer.destroy(); + assert.equal( + [...draw.sets.values()].filter((record) => !record.disposed).length, + 0, + ); +}); + +test('a fading mark takes its new colours in place, its pulses with them', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [route, area] = marks(); + renderer.add(route); + renderer.add(area); + const line = () => [...setsOf(draw, route)[0].items.values()][0]; + const fill = () => + setsOf(draw, area) + .find((r) => r.kind === 'shapes') + .items.get('fill:0'); + assert.ok(Math.abs(line().style.color[3] - 0.95) < 1e-9); + assert.ok(Math.abs(fill().fill[3] - 0.2) < 1e-9); + route.alpha = 0.5; + area.alpha = 0.5; + renderer.sync(); + assert.ok(Math.abs(line().style.color[3] - 0.475) < 1e-9, 'fading'); + assert.ok(Math.abs(fill().fill[3] - 0.1) < 1e-9); + assert.deepEqual( + [fill().animate.from, fill().animate.to].map((a) => Math.round(a * 1000)), + [60, 100], + 'its pulse swings between 60% and all of its alpha', + ); + route.alpha = 0; + renderer.sync(); + assert.equal(line().style.color[3], 0, 'faded out: nothing painted'); renderer.destroy(); }); -test('the line\'s flowing stroke follows its mark\'s alpha', () => { - let alpha = 1; - const material = new FlowMaterialProperty('#ffb547', () => alpha); - assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9); - alpha = 0; - assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted'); - alpha = 0.5; - assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading'); - assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before'); +test('every kind draws as it did: draped on terrain and tiles alike, rings by camera height, pulses', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [route, area, pin] = marks(); + const synth = { ...area, id: 'synth', synthesized: true }; + const arrow = { + id: 'arrow', + type: 'arrow', + color: 'red', + alpha: 1, + anchor: { lon: 0, lat: 0 }, + to: { lon: 0.01, lat: 0 }, + }; + const label = { + id: 'label', + type: 'label', + color: 'amber', + alpha: 1, + anchor: { lon: 0.03, lat: 0 }, + }; + for (const anno of [route, area, pin, synth, arrow, label]) + renderer.add(anno); + const items = (anno, kind) => [ + ...(setsOf(draw, anno) + .find((r) => r.kind === kind) + ?.items.values() ?? []), + ]; + for (const record of [...draw.sets.values()]) + assert.equal(record.spec.clampTo, 'both'); + + const [flow] = items(route, 'lines'); + assert.equal(flow.mode, 'draped'); + assert.equal(flow.widthPx, 9); + assert.deepEqual( + { ...flow.style, color: undefined }, + { kind: 'flow', color: undefined, repeat: 64, duty: 0.46, speed: 0.55 }, + ); + + const [areaFill] = items(area, 'shapes'); + assert.equal(areaFill.height, 'clampGround'); + assert.equal(areaFill.animate.property, 'alpha'); + assert.ok(Math.abs(areaFill.animate.periodMs - (2 * Math.PI) / 0.005) < 1e-9); + const [areaLine] = items(area, 'lines'); + assert.deepEqual( + [areaLine.widthPx, areaLine.style.kind, areaLine.style.power], + [6, 'glow', 0.35], + ); + const [synthLine] = items(synth, 'lines'); + assert.deepEqual( + [synthLine.style.kind, synthLine.style.length], + ['dash', 24], + ); + assert.ok( + Math.abs(items(synth, 'shapes')[0].fill[3] - 0.1) < 1e-9, + 'an approximate area is fainter', + ); + + const [arrowLine] = items(arrow, 'lines'); + assert.deepEqual( + [arrowLine.mode, arrowLine.widthPx, arrowLine.style.kind], + ['draped', 16, 'arrow'], + ); + + const [ring] = items(pin, 'shapes'); + assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height'); + assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor); + const [marker] = items(pin, 'points'); + assert.deepEqual( + [ + marker.pixelSize, + marker.height, + marker.outlineWidth, + marker.disableDepthTest, + ], + [14, 'clampGround', 3, Infinity], + ); + assert.equal(items(label, 'shapes').length, 0, 'a label has no ring'); + assert.equal(items(label, 'points')[0].pixelSize, 8); + renderer.destroy(); +}); + +test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => { + const { v, draw, camera, preRender, before } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [, , pin] = marks(); + const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } }; + renderer.add(pin); + renderer.add(other); + const ringOf = (anno) => + setsOf(draw, anno) + .find((r) => r.kind === 'shapes') + .items.get('ring'); + // Writes to the rings' sets since they were drawn. + const shapeSets = [pin, other].map((anno) => + setsOf(draw, anno).find((r) => r.kind === 'shapes'), + ); + const upserts = { + get length() { + return shapeSets.reduce((n, record) => n + record.writes - 1, 0); + }, + }; + assert.equal(ringOf(pin).geometry.semiMajor, 60); + assert.equal(before.size, 1, 'one listener for every ring'); + // The camera has not moved: nothing is sent. + preRender(); + assert.equal(upserts.length, 0); + // It climbs: both rings are sent at the new radius, once. + camera.height = 4000; + preRender(); + preRender(); + assert.equal(upserts.length, 2); + assert.equal(ringOf(pin).geometry.semiMajor, 120); + assert.equal(ringOf(pin).geometry.semiMinor, 120); + assert.equal(ringOf(other).geometry.semiMajor, 120); + // A change under 0.1% sends nothing. + camera.height = 4002; + preRender(); + assert.equal(upserts.length, 2); + // Held within 14 m and 170 m. + camera.height = 1e6; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 170); + camera.height = 10; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 14); + // A hidden mark waits, and catches up when shown. + other.hidden = true; + renderer.sync(); + camera.height = 3000; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 90); + assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent'); + other.hidden = false; + renderer.sync(); + assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up'); + // The last ring gone, the listener goes with it. + renderer.remove(pin); + renderer.remove(other); + assert.equal(before.size, 0); + renderer.destroy(); +}); + +test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => { + const { v, draw, emit, frames } = viewer(t, { heights: () => 150 }); + const renderer = createWorldAnnotationRenderer(v); + const ring = [ + [0, 0], + [0.001, 0], + [0.001, 0.001], + [0, 0.001], + [0, 0], + ]; + const anno = { + id: 'b', + type: 'area', + color: 'amber', + alpha: 1, + footprintKind: 'building', + buildingHeight: 40, + anchor: { lon: 0.0005, lat: 0.0005, height: 200 }, + ring, + }; + const done = renderer.add(anno); + assert.equal(frames.size, 1, 'probing on the frames'); + assert.equal( + setsOf(draw, anno).length, + 0, + 'nothing until its ground is known', + ); + for (let i = 0; i < 8; i++) emit(); + assert.equal((await done).status, 'installed'); + assert.equal(frames.size, 0, 'done probing'); + const shapes = [ + ...setsOf(draw, anno) + .find((r) => r.kind === 'shapes') + .items.values(), + ]; + const volume = shapes.find((s) => s.id === 'volume:0'); + assert.equal(volume.extrudeHeight, 150 + 40 + 24); + assert.equal(volume.geometry.rings[0][0].height, 147); + assert.equal(volume.height, 'absolute'); + const cage = shapes.find((s) => s.id === 'cage:0'); + assert.equal(cage.outlineOnly, true); + assert.ok(cage.geometry.rings[0].length <= 14); + const [base] = setsOf(draw, anno) + .find((r) => r.kind === 'lines') + .items.values(); + assert.deepEqual( + [base.mode, base.widthPx, base.style.kind, base.style.power], + ['draped', 3, 'glow', 0.25], + ); + renderer.destroy(); +}); + +test('each kind paints the alphas it painted as entities, at full alpha', (t) => { + const { v, draw } = viewer(t, { heights: () => 150 }); + const renderer = createWorldAnnotationRenderer(v); + const [route, area, pin] = marks(); + const synth = { ...area, id: 'synth', synthesized: true }; + const arrow = { + id: 'arrow', + type: 'arrow', + color: 'red', + alpha: 1, + anchor: { lon: 0, lat: 0 }, + to: { lon: 0.01, lat: 0 }, + }; + const ring = Array.from({ length: 40 }, (_, i) => [ + 0.0005 + 0.0004 * Math.cos((i / 40) * 2 * Math.PI), + 0.0005 + 0.0004 * Math.sin((i / 40) * 2 * Math.PI), + ]); + const building = { + id: 'b', + type: 'area', + color: 'amber', + alpha: 1, + footprintKind: 'building', + buildingHeight: 40, + anchor: { lon: 0.0005, lat: 0.0005, height: 200 }, + ring, + }; + for (const anno of [route, area, pin, synth, arrow]) renderer.add(anno); + renderer.add(building, { sampledGroundHeight: 150 }); + const items = (anno, kind) => [ + ...(setsOf(draw, anno) + .find((r) => r.kind === kind) + ?.items.values() ?? []), + ]; + const alpha = (c) => Math.round(c[3] * 1000) / 1000; + assert.equal(alpha(items(route, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(area, 'lines')[0].style.color), 1); + assert.equal(alpha(items(synth, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(arrow, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(pin, 'shapes')[0].fill), 0.38); + const marker = items(pin, 'points')[0]; + assert.deepEqual( + [alpha(marker.color), alpha(marker.outlineColor)], + [1, 0.95], + ); + assert.deepEqual(marker.outlineColor.slice(0, 3), [1, 1, 1]); + const [volume, cage] = items(building, 'shapes'); + assert.equal(alpha(volume.fill), 0.45); + assert.equal(alpha(cage.outline), 0.32); + assert.equal( + Math.round(cage.animate.from * 1000) / 1000, + 0.192, + 'the cage pulses too', + ); + assert.equal(cage.geometry.rings[0].length, 14, 'decimated to 14'); + assert.equal(alpha(items(building, 'lines')[0].style.color), 0.7); + renderer.destroy(); +}); + +test('a mark removed and added again draws afresh; two renderers on one viewer keep apart', (t) => { + const { v, draw } = viewer(t); + const first = createWorldAnnotationRenderer(v); + const second = createWorldAnnotationRenderer(v); + const [route, area] = marks(); + first.add(route); + const prefix = route._draw.prefix; + first.remove(route); + assert.doesNotThrow(() => first.add(route)); + assert.notEqual(route._draw.prefix, prefix, 'fresh sets'); + assert.doesNotThrow(() => second.add(area)); + assert.ok( + !area._draw.prefix.startsWith( + route._draw.prefix.split(':').slice(0, 2).join(':') + ':', + ), + ); + // Added again as another kind, its old sets go. + const kinds = () => + setsOf(draw, route) + .map((r) => r.kind) + .sort(); + assert.deepEqual(kinds(), ['lines']); + Object.assign(route, { type: 'pin', path: undefined }); + first.add(route); + assert.deepEqual(kinds(), ['points', 'shapes']); + assert.doesNotThrow(() => first.remove(null)); + first.destroy(); + second.destroy(); + assert.equal(route._draw, null); + first.add(route); + assert.equal(route._draw, null, 'a destroyed renderer draws nothing more'); + assert.equal([...draw.sets.values()].filter((r) => !r.disposed).length, 0); }); diff --git a/src/app/application.test.mjs b/src/app/application.test.mjs index c01878d891..00807c0972 100644 --- a/src/app/application.test.mjs +++ b/src/app/application.test.mjs @@ -2,20 +2,74 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { createApplication } from './application.js'; +import { installTrackpadPinchRelay } from '../render/cesium/ctrlWheelZoom.js'; import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js'; import * as Cesium from 'cesium'; -import { - installFreeLookHeightLimit, - installGlobeInViewRecovery, - installTrackpadPinchZoom, -} from './viewer.js'; -import { - FREE_LOOK_MAX_HEIGHT_METERS, - globeFrameShare, - globeOutOfFrame, - lookAngleWithinFrame, - lookStepLosesGlobe, -} from '../globeInView.js'; +import { installFreeLookHeightLimit } from '../render/cesium/freeLookLimit.js'; +import { installGlobeInViewRecovery } from './globeInViewRecovery.js'; +import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js'; +import * as globeInView from '../globeInView.js'; +import { createCesiumCamera } from '../render/cesium/camera.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { entityFollowTarget } from '../data/followed.js'; + +/** The camera port bound over each real Cesium camera a test makes. */ +const cameraPorts = new WeakMap(); + +/** + * Bind `viewer` the Cesium renderer's own camera port over its real camera, + * with the camera's own `moveStart` and `moveEnd` so a test raises them, and + * a frame port that counts render requests on the scene. + */ +function bindCameraPorts(viewer) { + const { camera, scene } = viewer; + const noEvent = { addEventListener: () => () => {} }; + const real = createCesiumCamera({ + scene: { + postUpdate: noEvent, + preUpdate: noEvent, + get screenSpaceCameraController() { + return scene.screenSpaceCameraController; + }, + requestRender: () => scene.requestRender?.(), + }, + camera, + report: (error) => { + throw error; + }, + }).port; + const port = Object.create(real, { + on: { value: (event, cb) => camera[event].addEventListener(cb) }, + }); + cameraPorts.set(camera, port); + bindRenderer(viewer, { + camera: port, + get canvas() { + return scene.canvas; + }, + frame: { + on: () => () => {}, + requestRender: () => scene.requestRender?.(), + }, + }); +} + +// The frame measures take a camera pose; these take the test's camera. +const poseOf = (camera) => cameraPorts.get(camera).pose(); +const LOOKS = { + lookUp: 'up', + lookDown: 'down', + lookLeft: 'left', + lookRight: 'right', +}; +const globeFrameShare = (camera, options) => + globeInView.globeFrameShare(poseOf(camera), options); +const globeOutOfFrame = (camera, options) => + globeInView.globeOutOfFrame(poseOf(camera), options); +const lookAngleWithinFrame = (camera, look, angle, options) => + globeInView.lookAngleWithinFrame(poseOf(camera), LOOKS[look], angle, options); +const lookStepLosesGlobe = (camera, look, angle, options) => + globeInView.lookStepLosesGlobe(poseOf(camera), LOOKS[look], angle, options); const phases = ['Scene', 'Controls', 'Data', 'Tools']; function fixture(overrides = {}) { @@ -235,8 +289,9 @@ test('the separate viewer export imports without constructing a browser viewer', }); test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => { - const { applicationViewerOptions } = await import('./viewer.js'); - const { StarrySky } = await import('../sky/starrySky.js'); + const { applicationViewerOptions } = + await import('../render/cesium/applicationViewer.js'); + const { StarrySky } = await import('../render/cesium/starrySky.js'); const creditContainer = {}; const options = applicationViewerOptions(creditContainer); // CesiumWidget skips scene.sun and scene.moon when skyBox is false. @@ -300,14 +355,13 @@ function pinchFixture({ zoomEventTypes } = {}) { return { viewer, controller, container, handlers, relayed, createEvent }; } -test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs', () => { +test('the trackpad pinch relay leaves the zoom bindings and plain or line-mode wheels alone', () => { const original = [1, 2, 3]; const f = pinchFixture({ zoomEventTypes: original }); - const dispose = installTrackpadPinchZoom(f.viewer, { + const dispose = installTrackpadPinchRelay(f.viewer, { createWheelEvent: (_type, init) => f.createEvent(init), }); - assert.deepEqual(f.controller.zoomEventTypes.slice(0, 3), original); - assert.equal(f.controller.zoomEventTypes.length, 4); + assert.equal(f.controller.zoomEventTypes, original); const plain = f.createEvent({ deltaY: 2 }); f.container.emit(plain); @@ -325,7 +379,7 @@ test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs test('trackpad pinch relays pixel deltas once with bounded amplification', () => { const f = pinchFixture({ zoomEventTypes: [1, 2, 3] }); - installTrackpadPinchZoom(f.viewer, { + installTrackpadPinchRelay(f.viewer, { createWheelEvent: (_type, init) => f.createEvent(init), }); @@ -345,7 +399,7 @@ test('trackpad pinch relays pixel deltas once with bounded amplification', () => test('trackpad pinch falls back to the original event when relay construction fails', () => { const f = pinchFixture({ zoomEventTypes: [1, 2, 3] }); - installTrackpadPinchZoom(f.viewer, { + installTrackpadPinchRelay(f.viewer, { createWheelEvent() { throw new Error('unsupported'); }, @@ -382,7 +436,10 @@ function freeLookFixture({ enableLook = true, height = 0 } = {}) { test('free look follows camera height and is restored on dispose', () => { const f = freeLookFixture({ height: 500 }); - const dispose = installFreeLookHeightLimit(f.viewer); + const dispose = installFreeLookHeightLimit( + f.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); assert.equal(f.controller.enableLook, true); f.frame(FREE_LOOK_MAX_HEIGHT_METERS + 1); @@ -402,7 +459,10 @@ test('free look follows camera height and is restored on dispose', () => { test('drags that start on the stars orbit above the free-look height', () => { // Below Cesium's trackball height such a drag turns the camera in place. const f = freeLookFixture({ height: 500 }); - const dispose = installFreeLookHeightLimit(f.viewer); + const dispose = installFreeLookHeightLimit( + f.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); assert.equal( f.controller.minimumTrackBallHeight, FREE_LOOK_MAX_HEIGHT_METERS, @@ -412,7 +472,10 @@ test('drags that start on the stars orbit above the free-look height', () => { const lower = freeLookFixture({ height: 500 }); lower.controller.minimumTrackBallHeight = 500_000; - const disposeLower = installFreeLookHeightLimit(lower.viewer); + const disposeLower = installFreeLookHeightLimit( + lower.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); assert.equal( lower.controller.minimumTrackBallHeight, 500_000, @@ -422,7 +485,10 @@ test('drags that start on the stars orbit above the free-look height', () => { assert.equal(lower.controller.minimumTrackBallHeight, 500_000); const later = freeLookFixture({ height: 500 }); - const disposeLater = installFreeLookHeightLimit(later.viewer); + const disposeLater = installFreeLookHeightLimit( + later.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); later.controller.minimumTrackBallHeight = 2_000_000; disposeLater(); assert.equal( @@ -434,7 +500,10 @@ test('drags that start on the stars orbit above the free-look height', () => { test('free look keeps a setting other code makes after it is installed', () => { const f = freeLookFixture({ height: 500 }); - const dispose = installFreeLookHeightLimit(f.viewer); + const dispose = installFreeLookHeightLimit( + f.viewer, + FREE_LOOK_MAX_HEIGHT_METERS, + ); f.controller.enableLook = false; f.frame(10); assert.equal(f.controller.enableLook, false, 'turned off stays off'); @@ -454,7 +523,7 @@ test('free look keeps a setting other code makes after it is installed', () => { test('free look stays off when the viewer had it disabled', () => { const f = freeLookFixture({ enableLook: false, height: 500 }); - installFreeLookHeightLimit(f.viewer); + installFreeLookHeightLimit(f.viewer, FREE_LOOK_MAX_HEIGHT_METERS); f.frame(10); assert.equal(f.controller.enableLook, false); }); @@ -479,7 +548,9 @@ function realCamera({ width = 1600, height = 900, mode } = {}) { }; const camera = new Cesium.Camera(scene); camera.frustum.aspectRatio = width / height; - return { camera, scene, viewer: { camera, scene } }; + const viewer = { camera, scene }; + bindCameraPorts(viewer); + return { camera, scene, viewer }; } function aim( @@ -573,7 +644,8 @@ test('a move that ends with the globe out of frame turns back to nadir', () => { Cesium.Cartesian3.equalsEpsilon(camera.positionWC, position, 0, 1e-3), ); assert.equal(globeOutOfFrame(camera), false); - assert.equal(scene.renders, 1); + // One render for the new view, one the recovery asks for itself. + assert.equal(scene.renders, 2, 'the turned view is drawn'); // Looking up near the ground, then zoomed out past the limit. aim(camera, { alt: 3_834_000, pitch: 10 }); @@ -602,7 +674,7 @@ function moveEndKeepsView(camera) { return Cesium.Cartesian3.equalsEpsilon(camera.directionWC, direction, 1e-9); } -test('globe recovery leaves partial, low, locked and 2D views alone', () => { +test('globe recovery leaves partial, low, locked and following views alone', () => { for (const view of partialGlobeViews) { const { camera, viewer } = realCamera(); installGlobeInViewRecovery(viewer); @@ -626,19 +698,18 @@ test('globe recovery leaves partial, low, locked and 2D views alone', () => { assert.equal(globeOutOfFrame(locked.camera), true); assert.ok(moveEndKeepsView(locked.camera), 'locked camera'); - // Tracking an entity that has no position yet keeps an identity transform. + // Following an entity that has no position yet keeps an identity transform. const tracked = realCamera(); - tracked.viewer.trackedEntity = { id: 'pending-fix' }; + const pending = entityFollowTarget( + { id: 'pending-fix' }, + { position: () => null }, + ); + Object.defineProperty(cameraPorts.get(tracked.camera), 'followed', { + get: () => pending, + }); installGlobeInViewRecovery(tracked.viewer); aim(tracked.camera, reportedStuckView); assert.ok(moveEndKeepsView(tracked.camera), 'tracked camera'); - - const flat = realCamera({ mode: Cesium.SceneMode.COLUMBUS_VIEW }); - installGlobeInViewRecovery(flat.viewer); - flat.scene.mode = Cesium.SceneMode.SCENE3D; - aim(flat.camera, reportedStuckView); - flat.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; - assert.ok(moveEndKeepsView(flat.camera), 'Columbus view'); }); test('the look limit from orbit tolerates grid noise and never reaches zero', () => { diff --git a/src/app/constructCatalog.js b/src/app/constructCatalog.js index c3d6c6f405..ed6821edda 100644 --- a/src/app/constructCatalog.js +++ b/src/app/constructCatalog.js @@ -6,6 +6,7 @@ import { createWeatherLayer } from '../layers/weather/index.js'; import { createApplicationCyclones } from './layers/cyclones.js'; import { createWindLayer } from '../layers/wind/index.js'; import { createLayerCatalog } from './catalog.js'; +import { layerPlacement } from '../data/placementProvider.js'; import { LAYER_STATE_REGISTRY } from '../data/layerState.js'; import { createMilitaryRegistry } from '../layers/aircraft/classification.js'; import { createApplicationFlights } from './layers/flights.js'; @@ -63,6 +64,9 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([ /** Construct the current catalog without choosing any source provider. * Scene engines remain page-owned; layers and classification have this app's lifetime. * The manager owns layer destruction, while abort releases classification even if startup fails. + * `placement`, a host-supplied placement provider (../data/placementProvider.js), + * places live aircraft, vessels, transit and trains; without one each layer + * uses its own motion. */ export function createApplicationCatalog({ surface, @@ -74,6 +78,7 @@ export function createApplicationCatalog({ resolveAsset, nepalBoundaryResolver, streetLevelProviders, + placement = null, }) { if (!signal?.addEventListener) throw new TypeError('An application lifetime signal is required'); @@ -97,18 +102,23 @@ export function createApplicationCatalog({ const flights = createApplicationFlights({ surface, source: sources.flights, + placement: layerPlacement(placement, 'aircraft'), militaryRegistry, resolveAsset, }); const military = createApplicationMilitary({ surface, source: sources.military, + placement: layerPlacement(placement, 'military'), militaryRegistry, resolveAsset, }); const vessels = createApplicationVessels({ source: sources.vessels, + placement: layerPlacement(placement, 'vessels'), options: vesselOptions, + displayParams: () => flights.getParams(), + ...(resolveAsset ? { resolveAsset } : {}), }); const installations = createApplicationInstallations({ surface, @@ -167,7 +177,13 @@ export function createApplicationCatalog({ createApplicationTraffic({ source: sources.traffic, surface }), createApplicationCctv({ surface, source: sources.cctv }), createApplicationRadio({ surface, source: sources.radio }), - createApplicationTransit({ surface, source: sources.transit }), + createApplicationTransit({ + surface, + source: sources.transit, + placement: layerPlacement(placement, 'transit'), + displayParams: () => flights.getParams(), + ...(resolveAsset ? { resolveAsset } : {}), + }), createApplicationBikeshare({ source: sources.bikeshare }), createApplicationDirections({ source: sources.directions }), createApplicationRecentImagery({ source: sources['recent-imagery'] }), @@ -200,7 +216,13 @@ export function createApplicationCatalog({ ...createOsmOverlayLayers(), ...createInfrastructureLayers(localGeoJsonServices), createApplicationCables({ source: sources.cables }), - createApplicationRail({ surface, source: sources.rail }), + createApplicationRail({ + surface, + source: sources.rail, + placement: layerPlacement(placement, 'rail'), + displayParams: () => flights.getParams(), + ...(resolveAsset ? { resolveAsset } : {}), + }), createApplicationFirms({ surface, id: 'local-firms', diff --git a/src/app/constructCatalog.test.mjs b/src/app/constructCatalog.test.mjs index dadf2c5411..ea6b46cd66 100644 --- a/src/app/constructCatalog.test.mjs +++ b/src/app/constructCatalog.test.mjs @@ -6,6 +6,11 @@ import { createStandaloneLayerSources } from '../standalone/layerSources.js'; import { catalogControlServices } from './catalog.js'; import { LayerLifecycle } from '../data/lifecycle.js'; import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs'; +import { worldClock } from '../time/worldClock.js'; + +const flush = async () => { + for (let i = 0; i < 20; i++) await Promise.resolve(); +}; function fixtureSources(ids, calls) { const sources = createStandaloneLayerSources(); @@ -27,6 +32,7 @@ test('catalogs construct distinct layers and classification from their supplied t.after(() => { a.abort(); b.abort(); + worldClock.goLive(); }); const callsA = []; const callsB = []; @@ -53,7 +59,10 @@ test('catalogs construct distinct layers and classification from their supplied 'the hardware-local layer is never serialized into links', ); assert.notEqual(first.weatherClock, second.weatherClock); - await first.weatherClock.setTarget('2026-09-21T12:00:00.000Z'); + // Time moves on the world clock, which the catalog's weather clock follows. + assert.equal(first.weatherClock.world, worldClock); + worldClock.seek(Date.parse('2026-09-21T12:00:00.000Z')); + await flush(); assert.match( first.get('wind').getRowControls().info, /Forecast · does not follow history/, @@ -111,9 +120,16 @@ test('catalogs construct distinct layers and classification from their supplied assert.equal(first.militaryRegistry.isMilitaryIcao('def456'), false); assert.equal(second.militaryRegistry.isMilitaryIcao('def456'), true); a.abort(); + worldClock.seek(Date.parse('2026-09-21T13:00:00.000Z')); + await flush(); assert.equal( - await first.weatherClock.setTarget('2026-09-21T13:00:00.000Z'), - false, + first.weatherClock.getState().target, + '2026-09-21T12:00:00.000Z', + 'an aborted catalog no longer follows the world clock', + ); + assert.equal( + second.weatherClock.getState().target, + '2026-09-21T13:00:00.000Z', ); assert.equal(callsA[0].aborted, true); assert.equal(first.militaryRegistry.isMilitaryIcao('abc123'), false); @@ -218,9 +234,8 @@ test('a GNSS integrity source can set the layer evidence window', (t) => { }; const shows = (layer, minutes) => { assert.equal(layer.provenance.window.minutes, minutes); - const { info, legend } = layer.getRowControls(); + const { info } = layer.getRowControls(); assert.match(info, new RegExp(`visited views over ${minutes} min`)); - assert.match(legend[0].blurb, new RegExp(`over ${minutes} minutes`)); }; shows(gnssLayer({ windowMs: 65 * 60_000 }), 65); shows(gnssLayer({}), 30); diff --git a/src/app/controls.js b/src/app/controls.js index def69325db..bec189ed31 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -1,8 +1,11 @@ import { catalogControlServices } from './catalog.js'; import { StyleManager } from '../ui/composition.js'; -import { flyToAustin } from '../camera.js'; -import { installZoomOutGuard } from './zoomOutGuard.js'; +import { applyStartView, START_VIEW } from '../camera.js'; import { initCockpitCloudEffects } from '../cockpitCloudEffects.js'; +import { createViewSky } from '../viewSky.js'; +import { findGlobe } from '../render/rendererOf.js'; +import { useDisplayStore } from '../ui/stores/display.js'; +import { applicationPinia } from '../ui/vueRuntime.js'; import { t } from '../i18n/index.js'; /** @@ -10,10 +13,13 @@ import { t } from '../i18n/index.js'; * opens a share code (the `` of `/share/`) at start-up, for a host * whose address does not carry one. `localePicker: false` removes the language * picker, for a host that offers its own language choice (`switchLocale` from - * the `./i18n` entry). + * the `./i18n` entry). `startView` is where the camera starts (the whole + * planet by default; a host may pass a city); a shared view flies from there. + * `services.cockpitSubjects` adds the application's own first-person subjects + * to the Cockpit (src/cockpitSubjectProviders.js). */ export function createApplicationControls({ - scene: { viewer, mapStackController, operations }, + scene: { viewer, mapStackController, operations, viewerDrawsEntity }, loaderStatus, Controls = StyleManager, services, @@ -22,7 +28,10 @@ export function createApplicationControls({ defer, initialShareCode = null, localePicker = true, + startView = START_VIEW, }) { + // Every boot starts from the same view, before share restoration flies on. + applyStartView(viewer, startView); // Initialize the style manager (post-processing, HUD, locations, share links) const styleManager = new Controls(viewer, { services: { @@ -32,6 +41,8 @@ export function createApplicationControls({ fetchRegionalBrief: (...args) => operations.requests.regional.getBrief(...args), ...catalogControlServices(catalog), + // Whether an entity is one of the viewer's own; the scene answers it. + viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity, }, requestServices: operations.requests, mapStackController, @@ -43,28 +54,27 @@ export function createApplicationControls({ defer(() => styleManager.orbitController.stop()); defer(() => styleManager.hud.destroy()); defer(() => styleManager.dispose()); - defer( - installZoomOutGuard(viewer, { - subscribeCameraHandoff: (listener) => - styleManager.subscribeCameraHandoff?.(listener), - }), - ); // The previous multi-canvas weather compositor remains disabled. Cockpit // clouds use a separate, capped low-resolution GPU pass that never attaches // Cesium fog or post-process stages and is fully stopped in map mode. const weatherEffects = null; - const cockpitCloudEffects = initCockpitCloudEffects(viewer, { - weatherService: operations.requests.weather, - }); + // Where the renderer draws weather, it draws the cockpit's clouds too. + const cockpitCloudEffects = findGlobe(viewer)?.weather + ? null + : initCockpitCloudEffects(viewer, { + weatherService: operations.requests.weather, + }); defer(() => cockpitCloudEffects?.destroy()); + // The atmosphere, sun lighting, sun, moon, stars and Milky Way the user + // chooses in the Display panel. + const viewSky = createViewSky(viewer, { + store: useDisplayStore(applicationPinia()), + }); + defer(() => viewSky.destroy()); - // If no share link state, do default fly-to Austin - if (!styleManager.hasShareState) { - loaderStatus.textContent = t('Flying to Austin, TX...'); - defer(flyToAustin(viewer)); - } else { - loaderStatus.textContent = t('Restoring shared view...'); - } + loaderStatus.textContent = styleManager.hasShareState + ? t('Restoring shared view...') + : t('Loading'); return { styleManager, weatherEffects, cockpitCloudEffects }; } diff --git a/src/app/controls.test.mjs b/src/app/controls.test.mjs index 3db3b7d8b8..ebf847b077 100644 --- a/src/app/controls.test.mjs +++ b/src/app/controls.test.mjs @@ -1,9 +1,8 @@ import test, { after, before } from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import '../testSupport/stubMgrs.mjs'; import { installVueDom } from '../testSupport/vueDom.mjs'; -import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; const { createApplicationControls } = await import('./controls.js'); @@ -13,35 +12,20 @@ before(() => { }); after(() => uninstallDom()); -test('application controls install the zoom-out guard and remove it on teardown', () => { - const canvas = document.createElement('canvas'); - const controller = { maximumZoomDistance: Infinity }; - const scene = { - mode: Cesium.SceneMode.SCENE3D, - screenSpaceCameraController: controller, - preRender: new Cesium.Event(), - postUpdate: new Cesium.Event(), - }; - const camera = { - position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000), - positionCartographic: { height: 1_000_000 }, - }; - const viewer = { scene, camera, canvas }; - const handoffs = new Set(); +test('the application controls start and stop', () => { class Controls { hasShareState = true; orbitController = { stop() {} }; hud = { destroy() {} }; dispose() {} - subscribeCameraHandoff(listener) { - handoffs.add(listener); - return () => handoffs.delete(listener); - } } const cleanups = []; createApplicationControls({ scene: { - viewer, + viewer: bindFakeCesiumCamera({ + isDestroyed: () => false, + camera: { setView() {} }, + }), mapStackController: {}, operations: { surface: { controlServices: {} }, @@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown' catalog: { get: (id) => ({ id }) }, defer: (cleanup) => cleanups.push(cleanup), }); - - assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M); - assert.equal(scene.preRender.numberOfListeners, 1); - assert.equal(scene.postUpdate.numberOfListeners, 1); - assert.equal(handoffs.size, 1); - for (const cleanup of cleanups.reverse()) cleanup(); - assert.equal(controller.maximumZoomDistance, Infinity); - assert.equal(scene.preRender.numberOfListeners, 0); - assert.equal(scene.postUpdate.numberOfListeners, 0); - assert.equal(handoffs.size, 0); }); diff --git a/src/app/data.js b/src/app/data.js index 022839cd21..7e20f13150 100644 --- a/src/app/data.js +++ b/src/app/data.js @@ -15,7 +15,7 @@ export function createApplicationData({ const dataManager = new LayerLifecycle(viewer, { allowQaRegistration, // A panel's host may report it hidden while it is on screen; its layers - // keep polling (see keepPanelRendering in embed.js). + // keep polling (see keepPanelRendering in app/panelRendering.js). visibilityTarget: panelAwareVisibility(document), getSourceAvailability: catalog?.getSourceAvailability, }); diff --git a/src/app/embed.js b/src/app/embed.js index 85c4f0752f..c30731d895 100644 --- a/src/app/embed.js +++ b/src/app/embed.js @@ -11,13 +11,14 @@ * embedded or not. */ -import * as Cesium from 'cesium'; import { announceNavigationAuthority, watchCameraOwner, } from '../navigationPolicy.js'; +import { toRadians } from '../geo/index.js'; import { t, translateKnown } from '../i18n/index.js'; import { GOOGLE_LABEL } from '../layers/streetLevel/providers/google/policy.js'; +import { cameraOf } from '../render/rendererOf.js'; import { annotationsFromParams, createView, @@ -69,7 +70,8 @@ function isFreshPanelResult() { /** * `doc`'s visibility for work that pauses in a hidden page. A panel's host - * may report it hidden while it is on screen (see keepPanelRendering), so an + * may report it hidden while it is on screen (see keepPanelRendering in + * render/cesium/panelRendering.js), so an * inline panel always reads as visible. */ export function panelAwareVisibility(doc = globalThis.document) { @@ -89,69 +91,6 @@ export function panelAwareVisibility(doc = globalThis.document) { }; } -// A panel keeps drawing at about this rate when its host stops animation -// frames; see keepPanelRendering. -const PANEL_FRAME_MS = 33; -const MISSED_FRAMES_MS = 250; - -/** A render error's details, including the plain objects workers report. */ -function describeError(error) { - if (error instanceof Error) - return `${error.name}: ${error.message}\n${error.stack}`; - try { - return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {})); - } catch { - return String(error); - } -} - -/** - * Keep the globe drawing in an inline panel. Some hosts report a panel on - * screen as hidden, which stops the browser's animation frames and with them - * Cesium's render loop; while frames stop arriving, draw from a timer. - * Returns a function that stops it. - */ -export function keepPanelRendering( - viewer, - { windowRef = globalThis.window, now = () => performance.now() } = {}, -) { - let lastFrame = now(); - let frameRequest = null; - const onFrame = () => { - lastFrame = now(); - frameRequest = windowRef.requestAnimationFrame(onFrame); - }; - frameRequest = windowRef.requestAnimationFrame(onFrame); - // Cesium stops drawing after a render error, and so does the timer. - // Report the error in full: workers report plain objects, which Cesium - // prints as [object Object]. - let failed = false; - const removeErrorListener = viewer.scene?.renderError?.addEventListener( - (_scene, error) => { - failed = true; - console.error( - "[God's Eye View panel] render error:", - describeError(error), - ); - }, - ); - const timer = windowRef.setInterval(() => { - if ( - failed || - now() - lastFrame < MISSED_FRAMES_MS || - viewer.isDestroyed?.() - ) - return; - viewer.resize(); - viewer.render(); - }, PANEL_FRAME_MS); - return () => { - windowRef.clearInterval(timer); - windowRef.cancelAnimationFrame(frameRequest); - removeErrorListener?.(); - }; -} - const delay = (ms, signal) => new Promise((resolve) => { const timer = setTimeout(resolve, ms); @@ -169,21 +108,19 @@ const delay = (ms, signal) => function flyTo(viewer, camera) { announceNavigationAuthority('embed-view'); return new Promise((resolve) => { - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees( - camera.lon, - camera.lat, - camera.altitude_m, - ), - orientation: { - heading: Cesium.Math.toRadians(camera.heading_deg), - pitch: Cesium.Math.toRadians(camera.pitch_deg), - roll: 0, + cameraOf(viewer).flyTo( + { lon: camera.lon, lat: camera.lat, height: camera.altitude_m }, + { + orientation: { + heading: toRadians(camera.heading_deg), + pitch: toRadians(camera.pitch_deg), + roll: 0, + }, + durationS: FLIGHT_SECONDS, + onComplete: () => resolve(true), + onCancel: () => resolve(false), }, - duration: FLIGHT_SECONDS, - complete: () => resolve(true), - cancel: () => resolve(false), - }); + ); }); } @@ -331,6 +268,9 @@ export async function applyView( /** * Install embed mode when the page asks for it, and draw any annotations the * opening link carries. Returns a function that removes the message handler. + * `keepRendering({windowRef})` keeps the globe drawing in an inline panel + * whose host stops animation frames, and returns a function that stops it; + * the application scene gives it (`keepPanelRendering`). */ export function installViews({ shell, @@ -338,6 +278,7 @@ export function installViews({ dataManager, run, signal, + keepRendering = null, terrain = null, location = globalThis.location, windowRef = globalThis.window, @@ -450,9 +391,10 @@ export function installViews({ windowRef.document.body.classList.add('ui-embed'); shell.setCleanView?.(true); - const stopRendering = isEmbeddedInline() - ? keepPanelRendering(viewer, { windowRef }) - : () => {}; + const stopRendering = + isEmbeddedInline() && keepRendering + ? keepRendering({ windowRef }) + : () => {}; // A framing page talks to the app across frames; an inline panel shares // the page with it and talks through the page's own window. const peer = isEmbeddedInline() ? windowRef : windowRef.parent; diff --git a/src/app/embed.test.mjs b/src/app/embed.test.mjs index bcc5ada9b9..1889c906ab 100644 --- a/src/app/embed.test.mjs +++ b/src/app/embed.test.mjs @@ -1,10 +1,10 @@ +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import assert from 'node:assert/strict'; import test from 'node:test'; import { applyView, installViews, isEmbedded, - keepPanelRendering, panelAwareVisibility, } from './embed.js'; import { LayerLifecycle } from '../data/lifecycle.js'; @@ -12,7 +12,7 @@ import { createView, viewToParams } from '../view/index.js'; const fakeViewer = () => { const flights = []; - return { + return bindFakeCesiumCamera({ flights, camera: { flyTo(options) { @@ -20,7 +20,7 @@ const fakeViewer = () => { options.complete(); }, }, - }; + }); }; const fakeLayers = (enabled) => ({ getAll: () => @@ -329,6 +329,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn globalThis.GEV_EMBED_INLINE = true; try { assert.equal(isEmbedded({ search: '' }), true); + const kept = []; const remove = installViews({ shell: { initialRestorePromise: Promise.resolve() }, viewer: fakeViewer(), @@ -336,7 +337,13 @@ test('an app loaded inline into a panel page talks through its own window', asyn run: recorder().run, location: { search: '', hash: '' }, windowRef, + // The scene's panel rendering, kept on while the views are installed. + keepRendering: (options) => { + kept.push(options.windowRef === windowRef); + return () => kept.push('stopped'); + }, }); + assert.deepEqual(kept, [true]); await new Promise((resolve) => setTimeout(resolve, 0)); assert.deepEqual(posted, [{ type: 'gev:ready' }]); const event = new Event('message'); @@ -349,6 +356,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn assert.equal(posted[1].id, 7); assert.equal(posted[1].ok, true); remove(); + assert.deepEqual(kept, [true, 'stopped']); } finally { delete globalThis.GEV_EMBED_INLINE; } @@ -427,73 +435,6 @@ test('annotations in a link are drawn after it restores, embedded or not', async ]); }); -test('a panel keeps drawing from a timer while animation frames stop', () => { - let clock = 0; - let tick = null; - let frame = null; - const windowRef = { - requestAnimationFrame: (fn) => ((frame = fn), 1), - cancelAnimationFrame: () => (frame = null), - setInterval: (fn) => ((tick = fn), 1), - clearInterval: () => (tick = null), - }; - const drawn = []; - const viewer = { - resize: () => drawn.push('resize'), - render: () => drawn.push('render'), - }; - const stop = keepPanelRendering(viewer, { windowRef, now: () => clock }); - // Frames arrive: the render loop draws, so the timer does nothing. - clock = 100; - frame(); - tick(); - assert.deepEqual(drawn, []); - // Frames stop, as in a panel its host reports hidden: the timer draws. - clock = 400; - tick(); - assert.deepEqual(drawn, ['resize', 'render']); - stop(); - assert.equal(tick, null); - assert.equal(frame, null); -}); - -test('a panel reports a render error in full and stops drawing', () => { - let listener = null; - let tick = null; - const windowRef = { - requestAnimationFrame: () => 1, - cancelAnimationFrame() {}, - setInterval: (fn) => ((tick = fn), 1), - clearInterval() {}, - }; - const drawn = []; - const viewer = { - resize() {}, - render: () => drawn.push('render'), - scene: { - renderError: { - addEventListener: (fn) => ((listener = fn), () => (listener = null)), - }, - }, - }; - const logged = []; - const original = console.error; - console.error = (...args) => logged.push(args.join(' ')); - try { - let clock = 0; - const stop = keepPanelRendering(viewer, { windowRef, now: () => clock }); - listener(viewer.scene, { name: 'RuntimeError', message: 'worker failed' }); - assert.match(logged[0], /render error: .*"message":"worker failed"/); - clock = 1000; - tick(); - assert.deepEqual(drawn, []); - stop(); - assert.equal(listener, null); - } finally { - console.error = original; - } -}); - test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => { const viewer = fakeViewer(); const { calls, run } = recorder(); diff --git a/src/app/globeInViewRecovery.js b/src/app/globeInViewRecovery.js new file mode 100644 index 0000000000..91c1c3062a --- /dev/null +++ b/src/app/globeInViewRecovery.js @@ -0,0 +1,181 @@ +/** + * @module app/globeInViewRecovery + * @description Turns the camera back to the planet when a move ends looking + * away from it, through the renderer's camera and frame ports. + */ +import { PI_OVER_TWO } from '../geo/vector.js'; +import { + FREE_LOOK_MAX_HEIGHT_METERS, + globeOutOfFrame, + isFreeGlobeCamera, +} from '../globeInView.js'; +import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js'; + +/** Whether two vectors agree to `tolerance` in every component. */ +const within = (a, b, tolerance) => + Math.abs(a.x - b.x) <= tolerance && + Math.abs(a.y - b.y) <= tolerance && + Math.abs(a.z - b.z) <= tolerance; + +// How often a moving camera is sampled to see whether it has come to rest, how +// far a pose may drift between samples and still count as at rest, and how +// long after the camera last moved the check gives up if the camera never +// raises moveEnd. +const SETTLE_SAMPLE_MS = 250; +const SETTLE_POSITION_TOLERANCE_M = 1e-3; +const SETTLE_DIRECTION_TOLERANCE = 1e-9; +const SETTLE_GIVE_UP_MS = 5 * 60_000; + +/** + * Turn the camera back to the planet when a move ends above `minHeight` with + * no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about + * one sample cell thick can count as none), and return the disposer. Views with + * more surface, such as an oblique orbital shot, are left as they are. This + * catches a saved or shared view that looked away, or any other move that ends + * looking away from the planet. + * Heading and position are kept. Following cameras, locked ones (a target's + * frame), a camera flight in progress, a pointer held down on the canvas + * (a drag held still), and any time `paused` + * returns true (an authored scene playing) are left alone; a check they defer + * runs once they end, however long they last. + * `keyholeRadius` + * returns the radius of the visible circle when a scope mask hides the rest of + * the frame (see `globeFrameShare`), or 0; it is read at every check. + * + * The camera's `moveEnd` alone is not enough: the default renderer compares + * the camera with the last frame's to the last rounding error, and at some of + * these poses the camera drifts by a rounding error every frame, so it never + * sees it stop. + * So each `moveStart` also starts a check of its own that samples the pose + * every 250 ms, with a tolerance for that drift, and once the pose has held + * for half a second after moving runs the same recovery. It keeps watching + * until the camera raises `moveEnd`, since under that drift it raises no new + * `moveStart` for a later move, and gives up five minutes after the camera + * last moved. + * `setTimeout` and `clearTimeout` can be injected for tests. + */ +export function installGlobeInViewRecovery( + viewer, + { + minHeight = FREE_LOOK_MAX_HEIGHT_METERS, + keyholeRadius = () => 0, + paused = () => false, + setTimeout: schedule = globalThis.setTimeout, + clearTimeout: unschedule = globalThis.clearTimeout, + } = {}, +) { + const camera = findCamera(viewer); + if (!camera) throw new TypeError('A viewer with a camera is required'); + + // A pointer held on the globe is a gesture in progress, even when it holds + // still for half a second: the check waits until every pointer pressed on + // it (each finger of a pinch) is released. A release the page never sees, + // outside the window, is taken as given when the window loses focus, the + // page is hidden, the canvas loses the pointer's capture, or the pointer + // moves with no button down. + const canvas = canvasOf(viewer); + const releaseTarget = canvas?.ownerDocument ?? canvas; + const releaseWindow = canvas?.ownerDocument?.defaultView; + const heldPointers = new Set(); + const onPointerDown = (event) => heldPointers.add(event?.pointerId); + const onPointerUp = (event) => heldPointers.delete(event?.pointerId); + const onPointerMove = (event) => { + if (event?.buttons === 0) heldPointers.delete(event.pointerId); + }; + const releaseAll = () => heldPointers.clear(); + const onVisibilityChange = () => { + if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll(); + }; + const listeners = [ + [canvas, 'pointerdown', onPointerDown], + [canvas, 'lostpointercapture', onPointerUp], + [releaseTarget, 'pointerup', onPointerUp], + [releaseTarget, 'pointercancel', onPointerUp], + [releaseTarget, 'pointermove', onPointerMove], + [canvas?.ownerDocument, 'visibilitychange', onVisibilityChange], + [releaseWindow, 'blur', releaseAll], + ]; + for (const [target, type, listener] of listeners) + target?.addEventListener?.(type, listener); + + // Returns false while a flight, a paused scene or a held pointer defers the + // check, so the caller can try again once it ends. + const recover = () => { + if (!isFreeGlobeCamera(viewer)) return true; + if (camera.flying || paused() || heldPointers.size > 0) return false; + const pose = camera.pose(); + if ( + !(pose.height > minHeight) || + !globeOutOfFrame(pose, { keyholeRadius: keyholeRadius() }) + ) + return true; + camera.setView({ + orientation: { heading: pose.heading, pitch: -PI_OVER_TWO, roll: 0 }, + }); + findFrame(viewer)?.requestRender?.('globe-in-view'); + return true; + }; + + let lastPosition = null; + let lastDirection = null; + const remember = () => { + ({ position: lastPosition, direction: lastDirection } = camera.pose()); + }; + let settleTimer = null; + let settleElapsed = 0; + let restingSamples = 0; + let movedSinceCheck = false; + const stopSettling = () => { + if (settleTimer !== null) unschedule(settleTimer); + settleTimer = null; + }; + const sample = () => { + settleTimer = null; + settleElapsed += SETTLE_SAMPLE_MS; + const now = camera.pose(); + const atRest = + within(now.position, lastPosition, SETTLE_POSITION_TOLERANCE_M) && + within(now.direction, lastDirection, SETTLE_DIRECTION_TOLERANCE); + restingSamples = atRest ? restingSamples + 1 : 0; + if (!atRest) { + movedSinceCheck = true; + settleElapsed = 0; + } + // Two quiet samples in a row after a move: at rest for half a second, as + // for moveEnd. + if (restingSamples >= 2 && movedSinceCheck) { + if (recover()) movedSinceCheck = false; + // A flight or a playing scene bounds its own deferral. + else settleElapsed = 0; + } + if (settleElapsed >= SETTLE_GIVE_UP_MS) return; + remember(); + settleTimer = schedule(sample, SETTLE_SAMPLE_MS); + }; + const startSettling = () => { + stopSettling(); + settleElapsed = 0; + restingSamples = 0; + movedSinceCheck = true; + remember(); + settleTimer = schedule(sample, SETTLE_SAMPLE_MS); + }; + const removeMoveEnd = camera.on('moveEnd', () => { + if (recover()) stopSettling(); + // Deferred: keep sampling so the check runs once the flight or scene ends. + else if (settleTimer === null) startSettling(); + }); + const removeMoveStart = camera.on('moveStart', startSettling); + + let active = true; + return () => { + if (!active) return; + active = false; + stopSettling(); + removeMoveEnd(); + removeMoveStart(); + for (const [target, type, listener] of listeners) + target?.removeEventListener?.(type, listener); + heldPointers.clear(); + }; +} diff --git a/src/app/layers/aisLiveVessels.js b/src/app/layers/aisLiveVessels.js index cae0bf44c9..1f2a0ed850 100644 --- a/src/app/layers/aisLiveVessels.js +++ b/src/app/layers/aisLiveVessels.js @@ -10,9 +10,21 @@ import * as focus from '../../data/focusDeemphasis.js'; import * as worldFocus from '../../worldFocus.js'; import * as render from '../../renderGovernor.js'; import * as readouts from '../../hudReadouts.js'; +import { fleetModelServices } from './fleetModels.js'; -/** Construct one layer using the application scene owners and a supplied source. */ -export function createApplicationVessels({ source, options = {} }) { +/** + * Construct one layer using the application scene owners and a supplied + * source. `displayParams` reads the Flights layer's DISPLAY-rail 3D + * preference, under which nearby vessels are drawn as fleet models. + * `placement`: a host-supplied placement for its live vessels, or null. + */ +export function createApplicationVessels({ + source, + placement = null, + options = {}, + displayParams = null, + resolveAsset, +}) { return createVesselLayer({ source, options, @@ -28,6 +40,11 @@ export function createApplicationVessels({ source, options = {} }) { worldFocus, render, readouts, + placement, + fleet: fleetModelServices({ + display: displayParams, + ...(resolveAsset ? { resolveAsset } : {}), + }), }, }); } diff --git a/src/app/layers/droneAirspace.js b/src/app/layers/droneAirspace.js index f3472fec49..c9db27a57f 100644 --- a/src/app/layers/droneAirspace.js +++ b/src/app/layers/droneAirspace.js @@ -1,8 +1,6 @@ -import * as Cesium from 'cesium'; import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { isPointerFree } from '../../data/inputOwnership.js'; /** Wire FAA special-use airspace into the application catalog. */ export function createApplicationDroneAirspace(options) { @@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) { clearSource: overlays.clearOverlaySource, hitTest: overlays.hitTestWorldOverlay, }, - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, - pointer: { isPointerFree }, ...options, }); } diff --git a/src/app/layers/firms.js b/src/app/layers/firms.js index 6e64148784..4bb6518967 100644 --- a/src/app/layers/firms.js +++ b/src/app/layers/firms.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js'; import * as render from '../../renderGovernor.js'; import * as sprites from '../../data/spriteOrder.js'; @@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) { clearSource: overlays.clearOverlaySource, hitTest: overlays.hitTestWorldOverlay, }, - screenSpaceEventHandlerFactory: - options.screenSpaceEventHandlerFactory ?? - ((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)), }); } diff --git a/src/app/layers/fleetModels.js b/src/app/layers/fleetModels.js new file mode 100644 index 0000000000..f6c5bcb7dc --- /dev/null +++ b/src/app/layers/fleetModels.js @@ -0,0 +1,19 @@ +import { FLEET_MODEL_POLICY } from '../../layers/flights/policy.js'; + +/** + * The fleet-model service the Vessels, Transit and Rail layers draw their 3D + * models with: the Flights layer's DISPLAY-rail 3D preference + * (`{ models3d, models3dMode }`), the aircraft layers' icon-to-model rules, + * and the resolver the fleet set's files are fetched through. + * @param {{display?: (() => object|null)|null, + * resolveAsset?: (url: string) => string}} [options] + * @returns {object|null} Null without a display preference (no models). + */ +export function fleetModelServices({ + display = null, + resolveAsset = (url) => + `${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`, +} = {}) { + if (!display) return null; + return Object.freeze({ display, policy: FLEET_MODEL_POLICY, resolveAsset }); +} diff --git a/src/app/layers/flights.js b/src/app/layers/flights.js index 38f880a055..94fae26ee4 100644 --- a/src/app/layers/flights.js +++ b/src/app/layers/flights.js @@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js'; import * as render from '../../renderGovernor.js'; import * as recession from '../../data/aircraftRecession.js'; -/** Construct one layer using the application scene owners and a supplied source. */ +/** Construct one layer using the application scene owners and a supplied source. + * `placement`: a host-supplied placement for its live aircraft, or null. */ export function createApplicationFlights({ surface, source, militaryRegistry, + placement = null, resolveAsset = (url) => `${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`, }) { @@ -41,6 +43,7 @@ export function createApplicationFlights({ render, groundSnap, recession, + placement, }, }); } diff --git a/src/app/layers/ghostMaps.js b/src/app/layers/ghostMaps.js index ccca188507..56387a80fb 100644 --- a/src/app/layers/ghostMaps.js +++ b/src/app/layers/ghostMaps.js @@ -1,8 +1,6 @@ -import * as Cesium from 'cesium'; import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { isPointerFree } from '../../data/inputOwnership.js'; /** Wire the S2 Underground GhostMaps layer into the application catalog. */ export function createApplicationGhostMaps(options) { @@ -14,10 +12,7 @@ export function createApplicationGhostMaps(options) { hitTest: overlays.hitTestWorldOverlay, }, openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, - pointer: { isPointerFree }, ...options, }); } diff --git a/src/app/layers/militaryFlights.js b/src/app/layers/militaryFlights.js index 839220c545..fbedd20aa9 100644 --- a/src/app/layers/militaryFlights.js +++ b/src/app/layers/militaryFlights.js @@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js'; import * as render from '../../renderGovernor.js'; import * as recession from '../../data/aircraftRecession.js'; -/** Construct one layer using the application scene owners and a supplied source. */ +/** Construct one layer using the application scene owners and a supplied source. + * `placement`: a host-supplied placement for its live aircraft, or null. */ export function createApplicationMilitary({ surface, source, militaryRegistry, + placement = null, resolveAsset = (url) => `${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`, }) { @@ -41,6 +43,7 @@ export function createApplicationMilitary({ render, groundSnap, recession, + placement, }, }); } diff --git a/src/app/layers/perimeters.js b/src/app/layers/perimeters.js index f5110f630d..dd1230ce46 100644 --- a/src/app/layers/perimeters.js +++ b/src/app/layers/perimeters.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createFirePerimetersLayer, createInciwebIndexSource, @@ -6,7 +5,6 @@ import { } from '../../layers/perimeters/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { isPointerFree } from '../../data/inputOwnership.js'; /** Wire WFIGS fire perimeters into the application catalog. */ export function createApplicationFirePerimeters(options) { @@ -20,10 +18,7 @@ export function createApplicationFirePerimeters(options) { inciwebSource: createInciwebIndexSource(), inciwebPublications: createInciwebPublicationSource(), openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, - pointer: { isPointerFree }, ...options, }); } diff --git a/src/app/layers/rail.js b/src/app/layers/rail.js index 9b5a3bb0e2..883b5f8771 100644 --- a/src/app/layers/rail.js +++ b/src/app/layers/rail.js @@ -1,9 +1,9 @@ import { createRailLayer } from '../../layers/rail/index.js'; import * as render from '../../renderGovernor.js'; +import { fleetModelServices } from './fleetModels.js'; import * as sprites from '../../data/spriteOrder.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; -import { applyTrackedCameraFrame } from '../../data/trackedCamera.js'; import { WORLD_FOCUS_FRAMING, requestWorldFocus } from '../../worldFocus.js'; import { railFeedCredit, @@ -13,10 +13,20 @@ import { /** * Construct the Rail layer on the application's scene owners and its shared * ground floor, the same floor Transit and the aircraft stand on. - * @param {{surface: object, source?: object}} options + * `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under + * which nearby trains are drawn as fleet models. + * `placement` is a host-supplied placement for its live trains, or null. + * @param {{surface: object, source?: object, placement?: object|null, + * displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options * @returns {object} */ -export function createApplicationRail({ surface, source }) { +export function createApplicationRail({ + surface, + source, + placement = null, + displayParams = null, + resolveAsset, +}) { if (!surface?.groundFloor) throw new TypeError('Rail needs the application surface services'); const { groundFloor } = surface; @@ -27,6 +37,7 @@ export function createApplicationRail({ surface, source }) { sprites, picking, overlays, + placement, credits: { registerDynamicCredit, railFeedCredit }, ground: { GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M, @@ -40,11 +51,14 @@ export function createApplicationRail({ surface, source }) { camera: { framing: WORLD_FOCUS_FRAMING.train, requestWorldFocus, - applyTrackedCameraFrame, isCockpitActive: () => globalThis.document?.body?.classList?.contains('cockpit-mode') === true, }, + fleet: fleetModelServices({ + display: displayParams, + ...(resolveAsset ? { resolveAsset } : {}), + }), }, }); } diff --git a/src/app/layers/shipwrecks.js b/src/app/layers/shipwrecks.js index ece2d2dce4..8f91289f18 100644 --- a/src/app/layers/shipwrecks.js +++ b/src/app/layers/shipwrecks.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; @@ -14,8 +13,6 @@ export function createApplicationShipwrecks(options) { hitTest: overlays.hitTestWorldOverlay, }, openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, pointer: { isPointerFree }, ...options, diff --git a/src/app/layers/streetLevel.js b/src/app/layers/streetLevel.js index 268216eaaf..3b7c7cc0b9 100644 --- a/src/app/layers/streetLevel.js +++ b/src/app/layers/streetLevel.js @@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js'; import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js'; import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js'; -import * as sprites from '../../data/spriteOrder.js'; import * as picking from '../../data/pickRegistry.js'; -import * as input from '../../data/inputOwnership.js'; import * as scenePick from '../../data/scenePick.js'; import * as render from '../../renderGovernor.js'; @@ -37,6 +35,6 @@ export function createApplicationStreetLevel({ }) { return createStreetLevelLayer({ providers, - services: { sprites, picking, input, scenePick, render }, + services: { picking, scenePick, render }, }); } diff --git a/src/app/layers/submarineCables.js b/src/app/layers/submarineCables.js index b84c072dbb..1f6dd7d817 100644 --- a/src/app/layers/submarineCables.js +++ b/src/app/layers/submarineCables.js @@ -1,12 +1,9 @@ -import * as Cesium from 'cesium'; import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js'; import { overlayHost } from './overlayHost.js'; /** Wire cable source geometry to the application overlay host. */ export function createApplicationCables(options) { return createSubmarineCableLayer({ overlayHost, - screenSpaceEventHandlerFactory: (canvas) => - new Cesium.ScreenSpaceEventHandler(canvas), mapStackEventTarget: typeof window !== 'undefined' ? window : null, ...options, }); diff --git a/src/app/layers/transit.js b/src/app/layers/transit.js index 367fc425e0..5e89a1f47a 100644 --- a/src/app/layers/transit.js +++ b/src/app/layers/transit.js @@ -1,5 +1,6 @@ import { createTransitLayer } from '../../layers/transit/index.js'; import * as render from '../../renderGovernor.js'; +import { fleetModelServices } from './fleetModels.js'; import * as sprites from '../../data/spriteOrder.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; @@ -19,10 +20,21 @@ import { * own mesh floors. An earlier cut imported the legacy module-level singleton * instead and could not see either. * - * @param {{surface: object}} options + * `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under + * which nearby vehicles are drawn as fleet models. + * + * `placement` is a host-supplied placement for its live vehicles, or null. + * @param {{surface: object, source?: object, placement?: object|null, + * displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options * @returns {object} */ -export function createApplicationTransit({ surface, source }) { +export function createApplicationTransit({ + surface, + source, + placement = null, + displayParams = null, + resolveAsset, +}) { if (!surface?.groundFloor || !surface?.meshFloor) throw new TypeError('Transit needs the application surface services'); const { groundFloor, meshFloor } = surface; @@ -33,6 +45,7 @@ export function createApplicationTransit({ surface, source }) { sprites, picking, overlays, + placement, credits: { registerDynamicCredit, transitFeedCredit }, ground: { GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M, @@ -44,6 +57,10 @@ export function createApplicationTransit({ surface, source }) { allocateCorridorCells: groundFloor.allocateCorridorCells, }, mesh: { sampleMeshFloorCells: meshFloor.sampleMeshFloorCells }, + fleet: fleetModelServices({ + display: displayParams, + ...(resolveAsset ? { resolveAsset } : {}), + }), }, }); } diff --git a/src/app/layers/wildlifeSightings.js b/src/app/layers/wildlifeSightings.js index 6d181f2c72..6ce091c553 100644 --- a/src/app/layers/wildlifeSightings.js +++ b/src/app/layers/wildlifeSightings.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createWildlifeSightingsLayer } from '../../layers/wildlifeSightings/index.js'; import * as picking from '../../data/pickRegistry.js'; import * as overlays from '../../overlays/worldOverlay.js'; @@ -17,8 +16,6 @@ export function createApplicationWildlifeSightings(options) { clearSource: overlays.clearOverlaySource, hitTest: overlays.hitTestWorldOverlay, }, - screenSpaceEventHandlerFactory: (viewer) => - new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas), picking, pointer: { isPointerFree }, sprites, diff --git a/src/app/localGeojsonServices.js b/src/app/localGeojsonServices.js index 8103f3b353..a9607e192b 100644 --- a/src/app/localGeojsonServices.js +++ b/src/app/localGeojsonServices.js @@ -2,6 +2,7 @@ import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; import { governorRequestRender } from '../renderGovernor.js'; import { clearSelectedEntityContextForLayer, + getSelectedEntityContext, registerEntityContext, removeEntityContextsForLayer, selectEntityContext, @@ -19,6 +20,7 @@ export const localGeoJsonServices = Object.freeze({ setVisible: setOverlaySourceVisible, }), clearSelectedEntityContextForLayer, + getSelectedEntityContext, registerEntityContext, removeEntityContextsForLayer, selectEntityContext, diff --git a/src/app/mapLifecycle.test.mjs b/src/app/mapLifecycle.test.mjs index ef015bf52a..6286ca71d9 100644 --- a/src/app/mapLifecycle.test.mjs +++ b/src/app/mapLifecycle.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { MapStackController } from '../mapStackController.js'; +import '../render/cesium/mapEngine.js'; import { installRenderGovernor, uninstallRenderGovernor, @@ -8,6 +9,7 @@ import { governorRequestRender, getRenderGovernorDiagnostics, } from '../renderGovernor.js'; +import { framePortFor } from '../testSupport/fakeFramePort.mjs'; test('destroy invalidates a pending imagery provider before it can touch the viewer', async () => { let resolveProvider; @@ -44,11 +46,11 @@ test('uninstall only releases the current viewer and makes later render requests }, }, }; - installRenderGovernor(viewer); + installRenderGovernor(framePortFor(viewer.scene)); holdContinuousRender('fixture'); - uninstallRenderGovernor({}); + uninstallRenderGovernor(framePortFor({})); assert.equal(getRenderGovernorDiagnostics().installed, true); - uninstallRenderGovernor(viewer); + uninstallRenderGovernor(framePortFor(viewer.scene)); const before = renders; governorRequestRender('late'); assert.equal(renders, before); diff --git a/src/app/panelRendering.js b/src/app/panelRendering.js new file mode 100644 index 0000000000..1b3688eb12 --- /dev/null +++ b/src/app/panelRendering.js @@ -0,0 +1,74 @@ +/** + * @module app/panelRendering + * @description Keeping the globe drawing in an inline panel whose host stops + * animation frames (`src/app/embed.js`, embed mode), through the ports alone: the + * application scene hands it to the embed views (`src/app/scene.js`). + */ + +// A panel keeps drawing at about this rate when its host stops animation +// frames; see keepPanelRendering. +const PANEL_FRAME_MS = 33; +const MISSED_FRAMES_MS = 250; + +/** A render error's details, including the plain objects workers report. */ +function describeError(error) { + if (error instanceof Error) + return `${error.name}: ${error.message}\n${error.stack}`; + try { + return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {})); + } catch { + return String(error); + } +} + +/** + * Keep `renderer` drawing in an inline panel. Some hosts report a panel on + * screen as hidden, which stops the browser's animation frames and with them + * the renderer's own loop; while frames stop arriving, draw from a timer + * (`resize`, then a frame of the loop, `frame.renderNow({ifDue: true})`: the + * camera moves, input and the clock run, and it draws when due). While the + * renderer's loop is stopped after a failed frame (`stopped` in its frame + * diagnostics) the timer waits, and goes on once a retry starts the loop + * again; the render failure notice reports the error + * (src/render/cesium/renderFailure.js). Where the renderer never says so, a frame + * that fails stops the timer, its error reported in full. Returns a + * function that stops it. + * @param {import('../render/contract/renderer').Renderer} renderer + * @param {{windowRef?: Window, now?: () => number}} [options] + * @returns {() => void} + */ +export function keepPanelRendering( + renderer, + { windowRef = globalThis.window, now = () => performance.now() } = {}, +) { + let lastFrame = now(); + let frameRequest = null; + const onFrame = () => { + lastFrame = now(); + frameRequest = windowRef.requestAnimationFrame(onFrame); + }; + frameRequest = windowRef.requestAnimationFrame(onFrame); + let failed = false; + const stopped = () => renderer.frame.diagnostics?.().stopped; + const timer = windowRef.setInterval(() => { + if (failed || now() - lastFrame < MISSED_FRAMES_MS || stopped()) return; + try { + renderer.resize(); + renderer.frame.renderNow({ ifDue: true }); + } catch (error) { + // Stopped by now: the render failure notice has the error. + if (stopped() !== undefined) return; + // Report the error in full: workers report plain objects, which + // would print as [object Object]. + failed = true; + console.error( + "[God's Eye View panel] render error:", + describeError(error), + ); + } + }, PANEL_FRAME_MS); + return () => { + windowRef.clearInterval(timer); + windowRef.cancelAnimationFrame(frameRequest); + }; +} diff --git a/src/app/panelRendering.test.mjs b/src/app/panelRendering.test.mjs new file mode 100644 index 0000000000..49af8b2aa0 --- /dev/null +++ b/src/app/panelRendering.test.mjs @@ -0,0 +1,125 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { keepPanelRendering } from './panelRendering.js'; + +const windowWith = () => { + const handles = { tick: null, frame: null }; + handles.windowRef = { + requestAnimationFrame: (fn) => ((handles.frame = fn), 1), + cancelAnimationFrame: () => (handles.frame = null), + setInterval: (fn) => ((handles.tick = fn), 1), + clearInterval: () => (handles.tick = null), + }; + return handles; +}; + +test('a panel keeps drawing from a timer while animation frames stop', () => { + let clock = 0; + const handles = windowWith(); + const drawn = []; + const renderer = { + resize: () => drawn.push('resize'), + frame: { + renderNow: (options) => + drawn.push(options?.ifDue ? 'loop frame' : 'forced frame'), + }, + }; + const stop = keepPanelRendering(renderer, { + windowRef: handles.windowRef, + now: () => clock, + }); + // Frames arrive: the render loop draws, so the timer does nothing. + clock = 100; + handles.frame(); + handles.tick(); + assert.deepEqual(drawn, []); + // Frames stop, as in a panel its host reports hidden: the timer draws. + clock = 400; + handles.tick(); + // A frame of the loop, as the loop's own: the camera moves, input and + // the clock run, and it draws when due. + assert.deepEqual(drawn, ['resize', 'loop frame']); + stop(); + assert.equal(handles.tick, null); + assert.equal(handles.frame, null); +}); + +test('a panel reports a failed frame in full and stops drawing', () => { + const handles = windowWith(); + let renders = 0; + const renderer = { + resize() {}, + frame: { + renderNow() { + renders += 1; + // Workers report plain objects. + throw { name: 'RuntimeError', message: 'worker failed' }; + }, + }, + }; + const logged = []; + const original = console.error; + console.error = (...args) => logged.push(args.join(' ')); + try { + let clock = 0; + const stop = keepPanelRendering(renderer, { + windowRef: handles.windowRef, + now: () => clock, + }); + clock = 1000; + handles.tick(); + assert.match(logged[0], /render error: .*"message":"worker failed"/); + handles.tick(); + assert.equal(renders, 1, 'no frame after the one that failed'); + stop(); + } finally { + console.error = original; + } +}); + +test('a panel waits while its renderer’s loop is stopped after a failed frame, and draws again once it restarts', () => { + let clock = 0; + const handles = windowWith(); + let stopped = false; + let fail = false; + let renders = 0; + const renderer = { + resize() {}, + frame: { + diagnostics: () => ({ stopped }), + renderNow() { + renders += 1; + if (fail) { + // The renderer stops its loop as the frame fails. + stopped = true; + throw new Error('frame failed'); + } + }, + }, + }; + const errors = []; + const error = console.error; + console.error = (...args) => errors.push(args); + try { + const stop = keepPanelRendering(renderer, { + windowRef: handles.windowRef, + now: () => clock, + }); + clock = 1000; + fail = true; + handles.tick(); + assert.equal(renders, 1); + // Stopped: the timer waits, and leaves the error to the notice. + handles.tick(); + assert.equal(renders, 1); + assert.deepEqual(errors, []); + // A retry starts the loop again: the timer draws again. + stopped = false; + fail = false; + handles.tick(); + assert.equal(renders, 2); + stop(); + } finally { + console.error = error; + } +}); diff --git a/src/app/renderFailureInlineRetry.test.mjs b/src/app/renderFailureInlineRetry.test.mjs new file mode 100644 index 0000000000..31dff45918 --- /dev/null +++ b/src/app/renderFailureInlineRetry.test.mjs @@ -0,0 +1,132 @@ +// Retry in an inline panel whose host stops animation frames, so the panel +// draws from keepPanelRendering's timer. Drives Cesium's real startRenderLoop +// and useDefaultRenderLoop setter (CesiumWidget.prototype), through the +// Cesium frame port. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { keepPanelRendering } from './panelRendering.js'; +import { renderLoopFixture } from '../render/cesium/renderLoopFixture.mjs'; +import { createSceneFrame } from '../render/cesium/frame.js'; + +function setup() { + let tick = null; + let clock = 0; + // The host reports the panel hidden: its own animation frames never arrive. + const windowRef = { + requestAnimationFrame: () => 1, + cancelAnimationFrame() {}, + setInterval: (fn) => ((tick = fn), 1), + clearInterval() {}, + }; + const previousError = console.error; + console.error = () => {}; + const state = { failure: null, drawn: 0 }; + const scene = { + renderError: new Cesium.Event(), + preUpdate: new Cesium.Event(), + preRender: new Cesium.Event(), + postRender: new Cesium.Event(), + requestRender() {}, + initializeFrame() {}, + // Scene.render: a failing primitive update raises renderError + // (tryAndCatchError) and returns; a failing listener throws. + render() { + state.drawn += 1; + this.preUpdate.raiseEvent(this); + if (state.failure === 'caught') + this.renderError.raiseEvent(this, new Error('boom')); + if (state.failure === 'thrown') throw new Error('boom'); + this.postRender.raiseEvent(this); + }, + }; + const { frames, widget, viewer, store, runFrames, restore } = + renderLoopFixture(scene, { + viewer: { + isDestroyed: () => false, + render: () => widget.render(), + resize: () => widget.resize(), + }, + notice: { allowReload: false }, + }); + const frame = createSceneFrame(viewer); + const renderer = { resize: () => viewer.resize(), frame: frame.port }; + const stopPanel = keepPanelRendering(renderer, { + windowRef, + now: () => clock, + }); + const stop = () => { + stopPanel(); + frame.dispose(); + }; + viewer.useDefaultRenderLoop = true; + const timerFrame = () => { + clock += 400; + tick(); + }; + return { + frames, + state, + store, + timerFrame, + animationFrames: runFrames, + restore: () => { + stop(); + restore(); + console.error = previousError; + }, + }; +} + +for (const failure of ['caught', 'thrown']) { + test(`an error ${failure} in a frame the timer draws: Retry draws again with one render loop`, () => { + const { frames, state, store, timerFrame, animationFrames, restore } = + setup(); + try { + // The host stops animation frames with the loop's next one queued. + assert.equal(frames.length, 1); + state.failure = failure; + timerFrame(); // an error thrown here does not reach the host page + assert.equal(store.renderFailure?.reason, 'render-error'); + assert.equal(typeof store.renderFailure.retry, 'function'); + state.failure = null; + store.renderFailure.retry(); + const before = state.drawn; + timerFrame(); + assert.ok(state.drawn > before, 'the panel draws again after Retry'); + assert.equal( + store.renderFailure, + null, + 'a clean frame clears the notice', + ); + assert.equal(frames.length, 1, 'Retry starts no second loop'); + // The host resumes frames: the globe draws once a frame. + state.drawn = 0; + animationFrames(3); + assert.equal(state.drawn, 3); + } finally { + restore(); + } + }); +} + +test('an error Scene caught in an animation frame right before the host stopped frames: Retry keeps one render loop', () => { + const { frames, state, store, timerFrame, animationFrames, restore } = + setup(); + try { + state.failure = 'caught'; + animationFrames(1); + assert.equal(store.renderFailure?.reason, 'render-error'); + assert.equal(frames.length, 1); + state.failure = null; + store.renderFailure.retry(); + timerFrame(); + assert.equal(store.renderFailure, null); + assert.equal(frames.length, 1, 'Retry starts no second loop'); + state.drawn = 0; + animationFrames(3); + assert.equal(state.drawn, 3); + } finally { + restore(); + } +}); diff --git a/src/app/scene.js b/src/app/scene.js index b9799b8acf..63012fb663 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -1,26 +1,66 @@ import { createApplicationOperations } from './operations.js'; -import * as Cesium from 'cesium'; -import { - createApplicationViewer, - installFreeLookHeightLimit, - installTrackpadPinchZoom, -} from '../app/viewer.js'; import { registerDataCredits } from '../data/dataCredits.js'; -import { configureCreditKeyboardAccess } from '../creditKeyboard.js'; +import { mountCreditsView } from '../ui/creditsView.js'; import { MapStackController } from '../mapStackController.js'; -import { loadPhotorealisticTileset } from '../mapStartup.js'; +import { mapEngineFor } from '../maps/engine.js'; import { initLogoGaze } from '../logoGaze.js'; +import { inputFor } from '../input/dispatcher.js'; import { + holdContinuousRender, + installRenderGovernor, uninstallRenderGovernor, governorRequestRender, + releaseContinuousRender, } from '../renderGovernor.js'; import { describeError } from './errors.js'; +import { isEmbeddedInline } from './embed.js'; import { worldClock, worldTimeFor } from '../time/worldClock.js'; import { followWorldTime } from '../time/viewerClock.js'; -import { onLocaleChange, t } from '../i18n/index.js'; +import { t } from '../i18n/index.js'; +import { + applicationHooksOf, + provideApplicationHooks, +} from '../render/applicationHooks.js'; +import { keepPanelRendering } from './panelRendering.js'; +import { useStatusStore } from '../ui/stores/status.js'; +import { applicationPinia } from '../ui/vueRuntime.js'; +import { createSceneHost } from '../render/rendererOf.js'; -/** Construct the application globe using the caller's local configuration. */ +let defaultLoad = null; + +/** + * The application's composition root picks the renderer: the one given, else + * the default (Cesium), loaded only then, so a page on the stub never + * loads it. This is the only part of an adapter the application imports. A + * page that starts on the default calls this as it starts, so the renderer + * loads beside the rest of the page rather than after it. + * @returns {Promise} The default `RendererPlugin`. + */ +export function loadDefaultRenderer() { + if (defaultLoad) return defaultLoad; + const load = (async () => { + const { cesiumRenderer } = await import('../render/cesium/application.js'); + return cesiumRenderer; + })(); + defaultLoad = load; + // A load that failed is tried again by the next call. + load.catch(() => { + if (defaultLoad === load) defaultLoad = null; + }); + return load; +} + +/** + * Construct the application globe using the caller's local configuration. + * `renderer` is the `RendererPlugin` that draws it, or a promise of one + * (default: Cesium, `loadDefaultRenderer`). The + * application runs on a renderer with only the contract's required members: + * what a renderer's plugin hands it beside the contract + * (`src/render/applicationHooks.js`) it uses where given, and does without + * where not. + */ export async function createApplicationScene({ + renderer: givenPlugin, requestServices, googleApiKey, googleTokens = null, @@ -47,52 +87,117 @@ export async function createApplicationScene({ }); } loaderStatus.textContent = t('Configuring viewer...'); - // Provider attribution stays visible, including clean-view and recording. - const creditContainer = document.createElement('div'); - creditContainer.id = 'cesium-credits'; - document.body.appendChild(creditContainer); - defer(() => creditContainer.remove()); - const viewer = createApplicationViewer({ - container: 'cesiumContainer', - creditContainer, + const rendererPlugin = (await givenPlugin) ?? (await loadDefaultRenderer()); + signal.throwIfAborted(); + const container = document.getElementById('cesiumContainer'); + const renderer = await rendererPlugin.create({ + container, + googleApiKey: googleApiKey || undefined, + googleTokens: googleTokens + ? (options) => googleTokens.token(options) + : undefined, + worldDataToken: cesiumToken || undefined, + signal, }); + // The scene object every layer and tool is handed: the application's own, + // bound to the renderer. + const scene = createSceneHost(renderer, { container }); + const viewer = scene.host; + // The governor keeps its holds on the renderer's frame port. The loop + // draws every frame until the application's tools are up (they release + // 'boot'), as it did before anything could hold it. A camera move holds + // it drawing every frame too. + installRenderGovernor(renderer.frame, { camera: renderer.camera }); + holdContinuousRender('boot'); defer(() => { - uninstallRenderGovernor(viewer); - if (!viewer.isDestroyed()) viewer.destroy(); + try { + uninstallRenderGovernor(renderer.frame); + } finally { + try { + renderer.destroy(); + } finally { + scene.release(); + } + } }); - defer(installTrackpadPinchZoom(viewer)); + // What the plugin hands the application beside the contract, each hook + // optional (render/applicationHooks.js). + if (typeof rendererPlugin.applicationHooks === 'function') + provideApplicationHooks( + renderer, + rendererPlugin.applicationHooks(renderer), + ); + const hooks = applicationHooksOf(renderer); + // The renderer follows its container's size (`Renderer.resize`). + if (typeof ResizeObserver === 'function' && container) { + const resizes = new ResizeObserver(() => renderer.resize()); + resizes.observe(container); + defer(() => resizes.disconnect()); + } + // Before any layer binds a click: every layer and tool shares this one. + // Deferred after the renderer, so it is released before the renderer goes. + const input = inputFor(viewer); + defer(() => input.destroy()); + // Ctrl+wheel and trackpad pinches zoom the globe, not the page. + const { controls } = renderer.camera; + if (!controls.zoomInputs.includes('ctrlWheel')) + controls.zoomInputs = [...controls.zoomInputs, 'ctrlWheel']; + // The user's outward zooms stop at a whole-Earth view, which stays framed. + if (renderer.capabilities.has('keepEarthFramed')) { + controls.keepEarthFramed = true; + defer(() => { + controls.keepEarthFramed = false; + }); + } + // The renderer's own notice when the globe stops drawing, in place of a + // dead-end panel; an inline panel must not reload or navigate its host's + // page. + const offRenderFailure = hooks.renderFailureNotice?.({ + allowReload: !isEmbeddedInline(), + store: useStatusStore(applicationPinia()), + }); + if (offRenderFailure) defer(offRenderFailure); defer( followWorldTime(viewer, worldTimeFor('sky'), { subscribe: worldClock.subscribe, requestRender: () => governorRequestRender('world-time'), + // A playing world time moves something every frame: draw at the + // display's rate meanwhile, not the parked scene's cap. + onPlaying: (playing) => + playing + ? holdContinuousRender('world-time') + : releaseContinuousRender('world-time'), }), ); - defer(installFreeLookHeightLimit(viewer)); registerDataCredits(viewer, credits); - configureCreditKeyboardAccess(document); - defer(onLocaleChange(() => configureCreditKeyboardAccess(document))); + // The credits, in the application's own line, unless the renderer shows + // them in a display of its own. + if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer)); loaderStatus.textContent = googleApiKey || googleTokens || cesiumToken ? t('Loading Google 3D Tiles...') : t('Loading the keyless globe...'); - const photoreal = await loadPhotorealisticTileset(Cesium, { + // The map stacks, and the photoreal base among them, switch through the + // scene's map engine: the renderer's own, or its globe port. + const engine = mapOptions.engine ?? mapEngineFor(viewer); + const photoreal = (await engine.loadPhotoreal?.(viewer, { googleApiKey, googleTokens, cesiumToken, - }); + })) ?? { tileset: null, route: 'none', errors: [] }; const tileset = photoreal.tileset; // A provider can finish after cancellation; retain ownership of its result. defer(() => { - if (tileset && !tileset.isDestroyed()) { - if (!viewer.scene.primitives.remove(tileset)) tileset.destroy(); - } + if (!tileset || engine.isDestroyed(tileset)) return; + engine.removeTileset(viewer, tileset); + engine.release(tileset); }); signal.throwIfAborted(); if (tileset) { - viewer.scene.primitives.add(tileset); + engine.addTileset(viewer, tileset); // NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom. // Google Photorealistic 3D Tiles provide their own terrain/elevation. - viewer.scene.globe.show = false; + renderer.globe.setGlobeVisible(false); console.info(`[Init] Google 3D Tiles loaded via ${photoreal.route}.`); } else { if (photoreal.errors.length) { @@ -109,7 +214,7 @@ export async function createApplicationScene({ }, ); } - viewer.scene.globe.show = true; + renderer.globe.setGlobeVisible(true); } loaderStatus.textContent = t('Initializing systems...'); @@ -117,6 +222,7 @@ export async function createApplicationScene({ const mapStackController = new MapController(viewer, { requestRender: governorRequestRender, ...mapOptions, + engine, googleTileset: tileset, cesiumToken, initialStack: tileset ? 'photoreal' : 'esri-imagery', @@ -138,5 +244,22 @@ export async function createApplicationScene({ }); signal.throwIfAborted(); - return { viewer, tileset, mapStackController, operations }; + return { + renderer, + viewer, + tileset, + mapStackController, + operations, + input, + // Keeps the globe drawing in an inline panel whose host stops animation + // frames (embed mode, src/app/embed.js); returns its disposer. + keepPanelRendering: (options) => keepPanelRendering(renderer, options), + // What the renderer's plugin hands the application beside the contract, + // each optional: trims stale draw commands, says whether an entity is + // the renderer's own, and what QA scripts read + // (render/applicationHooks.js). + trimStaleCommands: hooks.trimStaleCommands, + viewerDrawsEntity: hooks.viewerDrawsEntity, + qaHandles: hooks.qaHandles, + }; } diff --git a/src/app/scene.test.mjs b/src/app/scene.test.mjs new file mode 100644 index 0000000000..b19dac0f81 --- /dev/null +++ b/src/app/scene.test.mjs @@ -0,0 +1,152 @@ +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createApplicationScene } from './scene.js'; +import { createApplicationRequestServices } from '../services/requests.js'; +import { createStubRendererPlugin } from '../render/stub/index.js'; +import { rendererOf } from '../render/rendererOf.js'; + +/** Start the scene on a stub renderer with `capabilities`. */ +async function startOnStub(t, { capabilities = [], ...rest } = {}) { + document.body.innerHTML = '
'; + const made = []; + const deferred = []; + t.after(async () => { + for (const fn of deferred.reverse()) await fn(); + }); + const scene = await createApplicationScene({ + renderer: createStubRendererPlugin({ capabilities }, (renderer) => + made.push(renderer), + ), + requestServices: createApplicationRequestServices(), + loaderStatus: { textContent: '' }, + signal: new AbortController().signal, + defer: (fn) => deferred.push(fn), + ...rest, + }); + return { scene, renderer: made[0], deferred }; +} + +test('the scene runs on a renderer with only the required members', async (t) => { + const { scene, renderer, deferred } = await startOnStub(t); + assert.equal(scene.renderer, renderer); + assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound'); + assert.equal( + scene.viewer.container, + document.getElementById('cesiumContainer'), + ); + assert.equal(scene.viewer.isDestroyed(), false); + assert.ok( + scene.viewer.container.contains(renderer.canvas), + 'the renderer fills the container', + ); + // Nothing of the engine on the scene object. + assert.deepEqual(Object.keys(scene.viewer).sort(), [ + 'container', + 'isDestroyed', + ]); + // No hooks: each is left out, not faked. + for (const name of ['trimStaleCommands', 'viewerDrawsEntity', 'qaHandles']) + assert.equal(scene[name], undefined, name); + // What the renderer does through its ports. + assert.equal(typeof scene.keepPanelRendering, 'function'); + assert.equal( + renderer.camera.controls.keepEarthFramed, + undefined, + 'no framing on a renderer without it', + ); + // Keyless, the map stack shows Esri on the globe through the globe port. + assert.equal(scene.tileset, null); + assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery'); + const layers = renderer.globe.imagery.list(); + assert.equal(layers.length, 1, 'one base imagery layer'); + assert.ok( + renderer.testing.calls.some( + (call) => + call.port === 'globe' && + call.member === 'imagery.add' && + call.args[0]?.url?.includes('World_Imagery'), + ), + 'Esri imagery through the port', + ); + assert.equal(scene.mapStackController.getDrapeSurface(), 'globe'); + // The credits show in the application's own line: the Esri base's on it, + // the data credits in the list it opens. + const line = document.getElementById('gev-credits'); + assert.ok(line, 'a credits line'); + assert.match(line.textContent, /Esri/); + assert.ok( + document.querySelectorAll('#gev-credits-panel li').length > 10, + 'the data credits', + ); + + // Switching stacks goes through the port too. + await scene.mapStackController.setStack('osm'); + assert.equal(scene.mapStackController.getActiveId(), 'osm'); + assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way'); + + for (const fn of deferred.splice(0).reverse()) await fn(); + assert.equal(scene.viewer.isDestroyed(), true); + assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer'); + assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released'); + assert.equal(document.getElementById('gev-credits'), null, 'credits gone'); +}); + +test('the scene keeps the Earth framed where the renderer can', async (t) => { + const { renderer, deferred } = await startOnStub(t, { + capabilities: ['keepEarthFramed'], + }); + assert.equal(renderer.camera.controls.keepEarthFramed, true); + const controls = renderer.camera.controls; + for (const fn of deferred.splice(0).reverse()) await fn(); + assert.equal(controls.keepEarthFramed, false, 'and lets go on teardown'); +}); + +test("the scene takes a plugin's application hooks", async (t) => { + const stub = createStubRendererPlugin({ capabilities: [] }); + const given = []; + const handles = Object.freeze({ probe: 'qa' }); + const { scene } = await startOnStub(t, { + renderer: { + id: 'stub-with-hooks', + create: (options) => stub.create(options), + applicationHooks(made) { + given.push(made); + return { qaHandles: handles, ownCreditDisplay: true }; + }, + }, + }); + assert.deepEqual(given, [scene.renderer], 'asked once, for the renderer'); + assert.equal(scene.qaHandles, handles, 'QA scripts read its handles'); + assert.equal( + document.getElementById('gev-credits'), + null, + 'its own display shows the credits', + ); +}); + +test('with credentials, the photoreal base loads through the globe port', async (t) => { + const { scene, renderer } = await startOnStub(t, { + capabilities: ['photoreal', 'globeVisibility'], + googleApiKey: 'stub-key', + }); + assert.ok(scene.tileset, 'a photoreal base'); + assert.equal(scene.mapStackController.getActiveId(), 'photoreal'); + assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden'); + const photoreal = renderer.testing.calls.filter( + (call) => call.port === 'globe' && call.member === 'setPhotoreal', + ); + assert.equal(photoreal[0]?.args[0]?.key, 'stub-key'); + + // A globe stack hides photoreal through the port, and shows the globe. + await scene.mapStackController.setStack('esri-imagery'); + assert.equal(renderer.globe.isGlobeVisible(), true); + assert.equal( + renderer.testing.calls + .filter((call) => call.port === 'globe' && call.member === 'setPhotoreal') + .at(-1).args[0], + null, + ); + await scene.mapStackController.setStack('photoreal'); + assert.equal(renderer.globe.isGlobeVisible(), false); +}); diff --git a/src/app/sourceComposition.test.mjs b/src/app/sourceComposition.test.mjs index 466572d843..e5a3bcb6ee 100644 --- a/src/app/sourceComposition.test.mjs +++ b/src/app/sourceComposition.test.mjs @@ -1,3 +1,5 @@ +// The click dispatcher's input port over a viewer double: the Cesium adapter's. +import '../render/cesium/input.js'; import assert from 'node:assert/strict'; import test from 'node:test'; import { diff --git a/src/app/startupCamera.test.mjs b/src/app/startupCamera.test.mjs index 721f9964b1..0c1767cef2 100644 --- a/src/app/startupCamera.test.mjs +++ b/src/app/startupCamera.test.mjs @@ -1,25 +1,41 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { flyToAustin } from '../camera.js'; +import { applyStartView, START_VIEW } from '../camera.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; -test('teardown before the initial camera delay prevents a late flight', (t) => { - t.mock.timers.enable({ apis: ['setTimeout'] }); - let flights = 0; - let cancelled = 0; - const stop = flyToAustin({ +function viewerRecording(views) { + return bindFakeCesiumCamera({ isDestroyed: () => false, camera: { - setView() {}, - flyTo() { - flights++; + setView(view) { + views.push(view); }, - cancelFlight() { - cancelled++; + flyTo() { + assert.fail('a start view is set, not flown to'); }, }, }); - stop(); - t.mock.timers.tick(1000); - assert.equal(flights, 0); - assert.equal(cancelled, 1); +} + +test('the camera starts over the whole planet, looking straight down', () => { + const views = []; + applyStartView(viewerRecording(views)); + assert.equal(views.length, 1); + assert.ok(START_VIEW.height >= 20000000, 'the whole planet is in view'); + assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 2) < 1e-9); + assert.equal(views[0].orientation.heading, 0); +}); + +test('a host can start the camera at a city instead', () => { + const views = []; + applyStartView(viewerRecording(views), { + lon: 2.35, + lat: 48.86, + height: 5000, + heading: 90, + pitch: -30, + }); + assert.equal(views.length, 1); + assert.ok(Math.abs(views[0].orientation.heading - Math.PI / 2) < 1e-9); + assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 6) < 1e-9); }); diff --git a/src/app/tools.js b/src/app/tools.js index 476e252a54..1aae7ab8d5 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -1,3 +1,4 @@ +import { onFollowChanged } from '../data/followed.js'; import { SceneDirector } from '../scenes/director.js'; import { initAnnotations } from '../annotations/index.js'; import { initDrawTool } from '../annotations/drawTool.js'; @@ -24,17 +25,22 @@ import { isScopeMaskEnabled, } from '../scopeMask.js'; import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js'; -import { installGlobeInViewRecovery } from './viewer.js'; +import { installGlobeInViewRecovery } from './globeInViewRecovery.js'; import { installLayerReleaseTrim } from '../sceneCommandRelease.js'; import { - installRenderGovernor, getRenderGovernorDiagnostics, governorRequestRender, holdContinuousRender, releaseContinuousRender, } from '../renderGovernor.js'; +import { entityRecord, readEntityRecord } from '../data/entityRecords.js'; +import { overlayHost } from './layers/overlayHost.js'; -/** Attach scene tools, rendering listeners and the application debug handle. */ +/** + * Attach scene tools, rendering listeners and the application debug handle. + * `scene` is what `createApplicationScene` returns; its `trimStaleCommands` + * runs after each layer disable (a scene without one keeps that memory). + */ export function createApplicationTools({ scene, controls, @@ -49,11 +55,11 @@ export function createApplicationTools({ signal, defer, }) { - const { viewer, tileset, mapStackController, operations } = scene; + const { viewer, renderer, tileset, mapStackController, operations } = scene; const { styleManager, weatherEffects, cockpitCloudEffects } = controls; const { dataManager } = data; const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, { - dataPacks: sceneDataPacks, + dataPacks: { overlayHost, ...sceneDataPacks }, isMapStackAvailable: (id) => mapStackController?.isStackAvailable(id) === true, }); @@ -198,19 +204,21 @@ export function createApplicationTools({ } if (startChrome) defer(startChrome({ loadingScreen, styleManager, dataManager, signal })); - // Idle render governor: flips the scene into requestRenderMode whenever - // nothing animates per frame. Installed AFTER every module above has had - // its chance to register pre-install holds. (perf wave 2) - installRenderGovernor(viewer); - // Cesium keeps a turned-off layer's draw commands (and so all its entities) - // alive in reused per-pass arrays; trim them after each disable. - defer( - installLayerReleaseTrim({ - scene: viewer.scene, - dataManager, - requestRender: governorRequestRender, - }), - ); + // Idle render governor: the loop draws on demand whenever nothing animates + // per frame. It goes idle only now, after every module above has had its + // chance to hold. (perf wave 2) + releaseContinuousRender('boot'); + // The renderer may keep a turned-off layer's draw commands (and so all its + // entities) alive; trim them after each disable. + if (scene.trimStaleCommands) + defer( + installLayerReleaseTrim({ + frame: renderer.frame, + dataManager, + requestRender: governorRequestRender, + trim: scene.trimStaleCommands, + }), + ); // Install the explicit scope mask used by the DISPLAY controls. installScopeMask(viewer); @@ -218,12 +226,10 @@ 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 = viewer.trackedEntityChanged.addEventListener( - () => { - if (viewer.trackedEntity) holdContinuousRender('tracked-entity'); - else releaseContinuousRender('tracked-entity'); - }, - ); + const removeTrackingListener = onFollowChanged(viewer, (followed) => { + if (followed) holdContinuousRender('tracked-entity'); + else releaseContinuousRender('tracked-entity'); + }); // Hidden-state suspension (perf wave 2): when the window/tab is hidden, // stop the default render loop outright — a hidden canvas repaints for @@ -232,9 +238,9 @@ export function createApplicationTools({ // the loop, refresh the one DOM surface we gated, render a frame. const syncVisibilitySuspension = () => { // A panel's host may report it hidden while it is on screen; the panel - // keeps drawing itself (see keepPanelRendering in embed.js). + // keeps drawing itself (see keepPanelRendering in app/panelRendering.js). const hidden = document.hidden && !isEmbeddedInline(); - viewer.useDefaultRenderLoop = !hidden; + renderer.frame.suspend(hidden); cockpitCloudEffects?.setSuspended?.(hidden); if (!hidden) { data.presentation.flushVisible(); @@ -267,6 +273,10 @@ export function createApplicationTools({ getRenderGovernorDiagnostics, surfaceServices: operations.surface, requestRender: governorRequestRender, + entityRecords: { read: readEntityRecord, write: entityRecord }, + // What the renderer's plugin lets QA scripts read (the Cesium viewer, + // for the default renderer), in place of the scene object above. + ...scene.qaHandles, }; const debug = window.__godsEyeView; defer(() => { @@ -299,11 +309,13 @@ export function createApplicationTools({ run: (name, args, options = {}) => voiceCommands.runner(name, args, { ...options, signal }), signal, + keepRendering: scene.keepPanelRendering, terrain: operations.requests.terrain, }), ); - // An application's own tool takes the pointer as Draw does, and its own - // click handlers yield while a tool holds it, as the layers' do + // Any other tool takes the pointer as Draw does (the newest + // claim takes over; `claim(owner, {onLost})` tells the tool it replaces), + // and its own click handlers yield while a tool holds it, as the layers' do // (data/inputOwnership.js). return { sceneDirector, diff --git a/src/app/viewer.js b/src/app/viewer.js deleted file mode 100644 index e4288e8a3e..0000000000 --- a/src/app/viewer.js +++ /dev/null @@ -1,432 +0,0 @@ -import * as Cesium from 'cesium'; -import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js'; -import { StarrySky } from '../sky/starrySky.js'; -import { - FREE_LOOK_MAX_HEIGHT_METERS, - globeOutOfFrame, - isFreeGlobeCamera, -} from '../globeInView.js'; - -/** - * At the farthest a hand can zoom out, the globe is this share of the - * screen's height across. Cesium sets no limit, so zooming on left the globe - * a speck among the stars. - */ -const MIN_GLOBE_SHARE = 0.3; - -/** - * The farthest a hand can zoom out, in metres above the ellipsoid, for a - * vertical field of view. It follows the screen's shape, as the app's own - * whole-globe view does, so that view always lies within it. - * @param {number} fovy Vertical field of view, radians. - */ -export function zoomOutLimit(fovy) { - const radius = Cesium.Ellipsoid.WGS84.maximumRadius; - const angular = Math.atan(MIN_GLOBE_SHARE * Math.tan(fovy / 2)); - return radius / Math.sin(angular) - radius; -} - -/** - * Hold a hand's zoom out to `zoomOutLimit` on the globe, each frame, since the - * field of view follows the screen's shape. The limit never sits below the - * camera: one already past it (a flight, a screen turned) stops there rather - * than jumping in at the next zoom. Flat maps keep Cesium's own, unlimited. - * @returns {() => void} Stop limiting. - */ -export function limitZoomOut(viewer) { - const { scene, camera } = viewer; - return scene.preRender.addEventListener(() => { - const controller = scene.screenSpaceCameraController; - const fovy = camera.frustum.fovy; - if (scene.mode !== Cesium.SceneMode.SCENE3D || !Number.isFinite(fovy)) { - controller.maximumZoomDistance = Number.POSITIVE_INFINITY; - return; - } - controller.maximumZoomDistance = Math.max( - zoomOutLimit(fovy), - camera.positionCartographic?.height ?? 0, - ); - }); -} - -const PINCH_ZOOM_MULTIPLIER = 8; -const MAX_PINCH_PIXEL_DELTA = 120; - -function boundedPinchDelta(delta) { - if (!Number.isFinite(delta) || delta === 0) return delta; - return ( - Math.sign(delta) * - Math.min(Math.abs(delta) * PINCH_ZOOM_MULTIPLIER, MAX_PINCH_PIXEL_DELTA) - ); -} - -/** - * Add browser trackpad pinch to Cesium's zoom inputs and return its disposer. - * Browsers expose this gesture as a small pixel-mode Ctrl+wheel event. - */ -export function installTrackpadPinchZoom( - viewer, - { createWheelEvent = (type, init) => new WheelEvent(type, init) } = {}, -) { - const controller = viewer?.scene?.screenSpaceCameraController; - const container = viewer?.container; - const canvas = viewer?.canvas; - if (!controller || !container || !canvas) - throw new TypeError('A complete Cesium viewer is required'); - - const originalZoomEventTypes = controller.zoomEventTypes; - const zoomEventTypes = Array.isArray(originalZoomEventTypes) - ? originalZoomEventTypes - : originalZoomEventTypes === undefined - ? [] - : [originalZoomEventTypes]; - const alreadyHandlesControlWheel = zoomEventTypes.some( - (binding) => - binding?.eventType === Cesium.CameraEventType.WHEEL && - binding?.modifier === Cesium.KeyboardEventModifier.CTRL, - ); - const configuredZoomEventTypes = alreadyHandlesControlWheel - ? originalZoomEventTypes - : [ - ...zoomEventTypes, - { - eventType: Cesium.CameraEventType.WHEEL, - modifier: Cesium.KeyboardEventModifier.CTRL, - }, - ]; - if (!alreadyHandlesControlWheel) - controller.zoomEventTypes = configuredZoomEventTypes; - - const relayedEvents = new WeakSet(); - const relayPinch = (event) => { - if ( - !event.ctrlKey || - relayedEvents.has(event) || - event.deltaMode !== 0 || - !Number.isFinite(event.deltaY) || - event.deltaY === 0 - ) - return; - let relayed; - try { - relayed = createWheelEvent('wheel', { - deltaX: event.deltaX, - deltaY: boundedPinchDelta(event.deltaY), - deltaZ: event.deltaZ, - deltaMode: event.deltaMode, - screenX: event.screenX, - screenY: event.screenY, - clientX: event.clientX, - clientY: event.clientY, - ctrlKey: true, - bubbles: true, - cancelable: true, - view: globalThis.window, - }); - } catch { - // The registered Ctrl+wheel binding can still consume the original. - return; - } - relayedEvents.add(relayed); - event.preventDefault(); - event.stopPropagation(); - canvas.dispatchEvent(relayed); - }; - container.addEventListener('wheel', relayPinch, { - capture: true, - passive: false, - }); - - let active = true; - return () => { - if (!active) return; - active = false; - container.removeEventListener('wheel', relayPinch, true); - if ( - !alreadyHandlesControlWheel && - controller.zoomEventTypes === configuredZoomEventTypes - ) - controller.zoomEventTypes = originalZoomEventTypes; - }; -} - -/** - * Allow Cesium's free look only below `maxHeight` and return its disposer. - * Orbit, tilt and zoom stay available at every height. A value other code - * sets later is kept as the one to allow below that height, and restored on - * dispose; a `false` written while the camera is above `maxHeight` cannot be - * told apart from this limit's own write, so dispose restores the earlier - * value then. `enableLook` gates the Shift+drag binding only: below its trackball - * height Cesium also turns the camera in place for a drag that starts on the - * stars. That height is lowered to `maxHeight` too, so above it such a drag - * orbits the globe, as it does above Cesium's own 7,500 km. - */ -export function installFreeLookHeightLimit( - viewer, - maxHeight = FREE_LOOK_MAX_HEIGHT_METERS, -) { - const scene = viewer?.scene; - const controller = scene?.screenSpaceCameraController; - const camera = viewer?.camera; - if (!controller || !camera || !scene?.preUpdate) - throw new TypeError('A complete Cesium viewer is required'); - - const originalTrackBallHeight = controller.minimumTrackBallHeight; - const trackBallHeight = Math.min(originalTrackBallHeight, maxHeight); - controller.minimumTrackBallHeight = trackBallHeight; - let wanted = controller.enableLook; - let written; - const sync = () => { - if (written !== undefined && controller.enableLook !== written) - wanted = controller.enableLook; - const height = camera.positionCartographic?.height; - written = wanted && !(Number.isFinite(height) && height > maxHeight); - controller.enableLook = written; - }; - sync(); - const removeListener = scene.preUpdate.addEventListener(sync); - - let active = true; - return () => { - if (!active) return; - active = false; - removeListener(); - if (controller.enableLook === written) controller.enableLook = wanted; - if (controller.minimumTrackBallHeight === trackBallHeight) - controller.minimumTrackBallHeight = originalTrackBallHeight; - }; -} - -// How often a moving camera is sampled to see whether it has come to rest, how -// far a pose may drift between samples and still count as at rest, and how -// long after the camera last moved the check gives up if Cesium never raises -// moveEnd. -const SETTLE_SAMPLE_MS = 250; -const SETTLE_POSITION_TOLERANCE_M = 1e-3; -const SETTLE_DIRECTION_TOLERANCE = 1e-9; -const SETTLE_GIVE_UP_MS = 5 * 60_000; - -/** - * Turn the camera back to the planet when a move ends above `minHeight` with - * no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about - * one sample cell thick can count as none), and return the disposer. Views with - * more surface, such as an oblique orbital shot, are left as they are. This - * catches a saved or shared view that looked away, or any other move that ends - * looking away from the planet. - * Heading and position are kept. Tracked cameras, locked ones (non-identity - * transform), a camera flight in progress, a pointer held down on the canvas - * (a drag held still), the 2D and Columbus modes, and any time `paused` - * returns true (an authored scene playing) are left alone; a check they defer - * runs once they end, however long they last. - * `keyholeRadius` - * returns the radius of the visible circle when a scope mask hides the rest of - * the frame (see `globeFrameShare`), or 0; it is read at every check. - * - * Cesium's `moveEnd` alone is not enough: Cesium compares the camera with the - * last frame's to the last rounding error, and at some of these poses the - * camera drifts by a rounding error every frame, so Cesium never sees it stop. - * So each `moveStart` also starts a check of its own that samples the pose - * every 250 ms, with a tolerance for that drift, and once the pose has held - * for half a second after moving runs the same recovery. It keeps watching - * until Cesium raises `moveEnd`, since under that drift Cesium raises no new - * `moveStart` for a later move, and gives up five minutes after the camera - * last moved. - * `setTimeout` and `clearTimeout` can be injected for tests. - */ -export function installGlobeInViewRecovery( - viewer, - { - minHeight = FREE_LOOK_MAX_HEIGHT_METERS, - keyholeRadius = () => 0, - paused = () => false, - setTimeout: schedule = globalThis.setTimeout, - clearTimeout: unschedule = globalThis.clearTimeout, - } = {}, -) { - const scene = viewer?.scene; - const camera = viewer?.camera; - if (!scene || !camera?.moveEnd || !camera?.moveStart) - throw new TypeError('A complete Cesium viewer is required'); - - // A pointer held on the globe is a gesture in progress, even when it holds - // still for half a second: the check waits until every pointer pressed on - // it (each finger of a pinch) is released. A release the page never sees, - // outside the window, is taken as given when the window loses focus, the - // page is hidden, the canvas loses the pointer's capture, or the pointer - // moves with no button down. - const canvas = scene.canvas; - const releaseTarget = canvas?.ownerDocument ?? canvas; - const releaseWindow = canvas?.ownerDocument?.defaultView; - const heldPointers = new Set(); - const onPointerDown = (event) => heldPointers.add(event?.pointerId); - const onPointerUp = (event) => heldPointers.delete(event?.pointerId); - const onPointerMove = (event) => { - if (event?.buttons === 0) heldPointers.delete(event.pointerId); - }; - const releaseAll = () => heldPointers.clear(); - const onVisibilityChange = () => { - if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll(); - }; - const listeners = [ - [canvas, 'pointerdown', onPointerDown], - [canvas, 'lostpointercapture', onPointerUp], - [releaseTarget, 'pointerup', onPointerUp], - [releaseTarget, 'pointercancel', onPointerUp], - [releaseTarget, 'pointermove', onPointerMove], - [canvas?.ownerDocument, 'visibilitychange', onVisibilityChange], - [releaseWindow, 'blur', releaseAll], - ]; - for (const [target, type, listener] of listeners) - target?.addEventListener?.(type, listener); - - // Returns false while a flight, a paused scene or a held pointer defers the - // check, so the caller can try again once it ends. - const recover = () => { - if (!isFreeGlobeCamera(viewer)) return true; - // Cesium has no public running-flight flag. - if (camera._currentFlight || paused() || heldPointers.size > 0) - return false; - const height = camera.positionCartographic?.height; - if ( - !(height > minHeight) || - !globeOutOfFrame(camera, { keyholeRadius: keyholeRadius() }) - ) - return true; - camera.setView({ - orientation: { - heading: camera.heading, - pitch: -Cesium.Math.PI_OVER_TWO, - roll: 0, - }, - }); - scene.requestRender?.(); - return true; - }; - - const lastPosition = new Cesium.Cartesian3(); - const lastDirection = new Cesium.Cartesian3(); - let settleTimer = null; - let settleElapsed = 0; - let restingSamples = 0; - let movedSinceCheck = false; - const stopSettling = () => { - if (settleTimer !== null) unschedule(settleTimer); - settleTimer = null; - }; - const sample = () => { - settleTimer = null; - settleElapsed += SETTLE_SAMPLE_MS; - const atRest = - Cesium.Cartesian3.equalsEpsilon( - camera.positionWC, - lastPosition, - 0, - SETTLE_POSITION_TOLERANCE_M, - ) && - Cesium.Cartesian3.equalsEpsilon( - camera.directionWC, - lastDirection, - 0, - SETTLE_DIRECTION_TOLERANCE, - ); - restingSamples = atRest ? restingSamples + 1 : 0; - if (!atRest) { - movedSinceCheck = true; - settleElapsed = 0; - } - // Two quiet samples in a row after a move: at rest for half a second, as - // for moveEnd. - if (restingSamples >= 2 && movedSinceCheck) { - if (recover()) movedSinceCheck = false; - // A flight or a playing scene bounds its own deferral. - else settleElapsed = 0; - } - if (settleElapsed >= SETTLE_GIVE_UP_MS) return; - Cesium.Cartesian3.clone(camera.positionWC, lastPosition); - Cesium.Cartesian3.clone(camera.directionWC, lastDirection); - settleTimer = schedule(sample, SETTLE_SAMPLE_MS); - }; - const startSettling = () => { - stopSettling(); - settleElapsed = 0; - restingSamples = 0; - movedSinceCheck = true; - Cesium.Cartesian3.clone(camera.positionWC, lastPosition); - Cesium.Cartesian3.clone(camera.directionWC, lastDirection); - settleTimer = schedule(sample, SETTLE_SAMPLE_MS); - }; - const removeMoveEnd = camera.moveEnd.addEventListener(() => { - if (recover()) stopSettling(); - // Deferred: keep sampling so the check runs once the flight or scene ends. - else if (settleTimer === null) startSettling(); - }); - const removeMoveStart = camera.moveStart.addEventListener(startSettling); - - let active = true; - return () => { - if (!active) return; - active = false; - stopSettling(); - removeMoveEnd(); - removeMoveStart(); - for (const [target, type, listener] of listeners) - target?.removeEventListener?.(type, listener); - heldPointers.clear(); - }; -} - -/** Cesium.Viewer options of the standard globe viewer. */ -export function applicationViewerOptions(creditContainer) { - return { - timeline: false, - animation: false, - baseLayerPicker: false, - geocoder: false, - homeButton: false, - sceneModePicker: false, - navigationHelpButton: false, - fullscreenButton: false, - vrButton: false, - selectionIndicator: false, - infoBox: false, - baseLayer: false, - // Replaces the blocky Tycho-2 default. An option, not `skyBox: false`, - // which would also stop CesiumWidget from creating the Sun and Moon. - skyBox: new StarrySky(), - creditContainer, - msaaSamples: 4, - contextOptions: { webgl: { preserveDrawingBuffer: true } }, - }; -} - -/** Create the standard globe viewer in caller-owned, visible containers. */ -export function createApplicationViewer({ container, creditContainer }) { - if (!container || !creditContainer) - throw new TypeError('Viewer and credit containers are required'); - const viewer = new Cesium.Viewer( - container, - applicationViewerOptions(creditContainer), - ); - try { - viewer.targetFrameRate = 60; - // A phone pinch spans fewer screen pixels than desktop zoom gestures. - // Keep Cesium's distance-aware zoom and collision limits, with less travel - // required on touch-first screens. Mouse/trackpad sensitivity stays native. - if (globalThis.matchMedia?.('(pointer: coarse)').matches) - viewer.scene.screenSpaceCameraController.zoomFactor *= 3; - limitZoomOut(viewer); - // Before any tile builds a draw command: Cesium's per-vertex model - // atmosphere fails to LINK on Apple's Metal backend and kills the - // render loop. See app/atmosphereCompat.js. - applyModelAtmosphereWorkaround(viewer.scene); - viewer.scene.globe.show = false; - viewer.scene.skyAtmosphere.show = true; - viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18; - viewer.scene.skyAtmosphere.saturationShift = -0.12; - viewer.scene.skyAtmosphere.brightnessShift = -0.08; - return viewer; - } catch (error) { - viewer.destroy(); - throw error; - } -} diff --git a/src/awarenessEcho.js b/src/awarenessEcho.js index 44a5e37fa7..c0f712543a 100644 --- a/src/awarenessEcho.js +++ b/src/awarenessEcho.js @@ -6,11 +6,12 @@ * awareness policy of its own: the publisher passes radius, pulse timing and * echo styling in, so the overlay never imports awareness internals. */ -import * as Cesium from 'cesium'; +import { scaleToGeodeticSurface } from './geo/ellipsoid.js'; +import { distance } from './geo/vector.js'; /** * @typedef {object} AwarenessEchoField - * @property {Cesium.Cartesian3} center Subject's ground point. The publisher + * @property {{x: number, y: number, z: number}} center Subject's ground point. The publisher * may move it in place; it is read on every query. * @property {number} radiusM Range the pulses grow to. * @property {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse @@ -22,7 +23,6 @@ import * as Cesium from 'cesium'; /** @type {AwarenessEchoField|null} */ let field = null; let layerIds = new Set(); -const groundScratch = new Cesium.Cartesian3(); /** * Start (or replace) the echo field. @@ -104,7 +104,7 @@ export function awarenessEchoStrength(nowMs, distanceM, radiusM, pulse, echo) { * field is set or the layer does not echo. Distance is measured between * ground points, so an aircraft's altitude does not shift its echo. * @param {string} layerId Owning layer of the contact. - * @param {Cesium.Cartesian3} position Contact's world position. + * @param {{x: number, y: number, z: number}} position Contact's world position. * @param {number} nowMs Monotonic clock in milliseconds. * @returns {number} 0 to 1. */ @@ -112,16 +112,13 @@ export function awarenessEchoAt(layerId, position, nowMs) { if (!field || !position || !layerIds.has(layerId)) return 0; const level = field.level?.(nowMs) ?? 1; if (!(level > 0)) return 0; - const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( - position, - groundScratch, - ); + const ground = scaleToGeodeticSurface(position); if (!ground) return 0; return ( level * awarenessEchoStrength( nowMs, - Cesium.Cartesian3.distance(field.center, ground), + distance(field.center, ground), field.radiusM, field.pulse, field.echo, @@ -138,7 +135,7 @@ export function awarenessEchoAt(layerId, position, nowMs) { * outside the contact's bracket, 0 as the front arrives, growing to the * field's `spreadPx` as it fades. * @param {string} layerId Owning layer of the contact. - * @param {Cesium.Cartesian3} position Contact's world position. + * @param {{x: number, y: number, z: number}} position Contact's world position. * @param {number} nowMs Monotonic clock in milliseconds. * @param {number} bracketAlpha The contact bracket's drawn alpha, 0 to 1. * @param {number} steps Alpha bands the overlay batches by. diff --git a/src/camera.js b/src/camera.js index 3fd49b58c0..57547071a2 100644 --- a/src/camera.js +++ b/src/camera.js @@ -1,36 +1,29 @@ -import * as Cesium from 'cesium'; +import { toRadians } from './geo/index.js'; +import { cameraOf } from './render/rendererOf.js'; /** - * Set camera to Austin on load with a cinematic fly-in. - * @returns {Function} Cancels the pending or active startup flight. + * The view the renderer starts from: the whole planet, looking straight + * down, centred where Cesium's default view rectangle is. */ -export function flyToAustin(viewer) { - // Start from a high altitude, then fly down - viewer.camera.setView({ - destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 25000), +export const START_VIEW = Object.freeze({ + lon: -82.5, + lat: 35, + height: 23000000, +}); + +/** + * Put the camera at a start view without a flight. A host may pass a city + * (`{ lon, lat, height, heading?, pitch? }`, angles in degrees) instead of + * the planet. + */ +export function applyStartView(viewer, view = START_VIEW) { + const { lon, lat, height, heading = 0, pitch = -90 } = view; + cameraOf(viewer).setView({ + destination: { lon, lat, height }, orientation: { - heading: Cesium.Math.toRadians(0), - pitch: Cesium.Math.toRadians(-90), - roll: 0.0, + heading: toRadians(heading), + pitch: toRadians(pitch), + roll: 0, }, }); - - // Cinematic fly-in after a brief pause - const timer = setTimeout(() => { - if (viewer.isDestroyed()) return; - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 600), - orientation: { - heading: Cesium.Math.toRadians(15), - pitch: Cesium.Math.toRadians(-30), - roll: 0.0, - }, - duration: 4.0, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - }); - }, 500); - return () => { - clearTimeout(timer); - if (!viewer.isDestroyed()) viewer.camera.cancelFlight(); - }; } diff --git a/src/cameraGlobeRotation.test.mjs b/src/cameraGlobeRotation.test.mjs index 8c3f20df23..1952f25e3e 100644 --- a/src/cameraGlobeRotation.test.mjs +++ b/src/cameraGlobeRotation.test.mjs @@ -1,3 +1,14 @@ +import { + bindFakeCesiumCamera, + followEntity, + followedEntity, +} from './testSupport/fakeCameraPort.mjs'; +import { rendererOf } from './render/rendererOf.js'; +import { followedOf } from './data/followed.js'; +import { + fakeSceneFrame, + fakeSceneQuery, +} from './testSupport/fakeCesiumScene.mjs'; import { GLOBE_VIEW } from './locations.js'; import { projectEarthDiscToViewport } from './celestialRing.js'; import assert from 'node:assert/strict'; @@ -13,11 +24,24 @@ import { moveCamera, } from './cameraVerbs.js'; import { getRenderGovernorDiagnostics } from './renderGovernor.js'; -import { - MIN_GLOBE_FRAME_SHARE, - globeFrameShare, - globeOutOfFrame, -} from './globeInView.js'; +import { MIN_GLOBE_FRAME_SHARE } from './globeInView.js'; +import * as globeInView from './globeInView.js'; + +// The frame measures take a camera pose; these read it off the real camera. +const framePose = (camera) => ({ + position: camera.positionWC, + direction: camera.directionWC, + up: camera.upWC, + right: camera.rightWC, + fovy: camera.frustum.fovy, + aspectRatio: camera.frustum.aspectRatio, + height: camera.positionCartographic.height, + pitch: camera.pitch, +}); +const globeFrameShare = (camera, options) => + globeInView.globeFrameShare(framePose(camera), options); +const globeOutOfFrame = (camera, options) => + globeInView.globeOutOfFrame(framePose(camera), options); import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js'; import { setScopeMaskEnabled } from './scopeMask.js'; @@ -136,7 +160,7 @@ function harness( mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL, mode: Cesium.SceneMode.SCENE3D, pixelRatio: 1, - tweens: [], + preUpdate: new Cesium.Event(), requestRender() {}, }; const camera = new Cesium.Camera(scene); @@ -154,13 +178,37 @@ function harness( roll: radians(roll), }, }); - const viewer = { + const double = { camera, scene, - trackedEntity: undefined, + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. trackedEntityChanged: new Cesium.Event(), - clock: { onTick: new Cesium.Event() }, + entities: {}, }; + const viewer = bindFakeCesiumCamera(double, { + query: fakeSceneQuery(double), + frame: fakeSceneFrame(double), + }); + // Count who listens for the port's follow changes. + const renderer = rendererOf(viewer); + const port = renderer.camera; + let followListeners = 0; + renderer.camera = Object.create(port, { + on: { + value(event, cb, options) { + const off = port.on(event, cb, options); + if (event !== 'followChanged') return off; + followListeners += 1; + let live = true; + return () => { + if (live) followListeners -= 1; + live = false; + off(); + }; + }, + }, + }); const target = Cesium.Cartesian3.fromDegrees( longitudeDeg, latitude, @@ -174,73 +222,21 @@ function harness( }); const tick = (seconds = 0.1) => { nowMs += seconds * 1000; - viewer.clock.onTick.raiseEvent(viewer.clock); + viewer.scene.preUpdate.raiseEvent(viewer.scene); }; const finishOnce = () => { for (let i = 0; i < 20 && getActiveCameraMotion(); i += 1) tick(); assert.equal(getActiveCameraMotion(), null, 'once motion must finish'); }; - return { viewer, camera, canvas, target, tick, finishOnce }; -} - -for (const [name, sceneMode] of [ - ['2D', Cesium.SceneMode.SCENE2D], - ['Columbus', Cesium.SceneMode.COLUMBUS_VIEW], - ['morphing', Cesium.SceneMode.MORPHING], -]) { - test(`globe rotation refuses ${name} before changing the prior owner`, (t) => { - const { viewer, camera } = harness(t); - assert.equal( - moveCamera({ motion: 'rotate', direction: 'right', mode: 'continuous' }) - .ok, - true, - ); - const priorId = activeCameraMotionId(); - const before = pose(camera); - const transform = Cesium.Matrix4.clone(camera.transform); - viewer.scene.mode = sceneMode; - let handoffs = 0; - let cancellations = 0; - camera.cancelFlight = () => { - cancellations += 1; - }; - for (const mode of ['once', 'continuous']) { - const result = moveCamera( - { motion: 'rotate_globe', direction: 'left', mode }, - () => { - handoffs += 1; - return { ok: true }; - }, - ); - assert.equal(result.ok, false); - assert.match(result.error, /3D/); - } - assert.equal(handoffs, 0); - assert.equal(cancellations, 0); - assert.equal(activeCameraMotionId(), priorId); - assert.equal(hasRenderHold(), true); - assert.ok(Cesium.Matrix4.equals(camera.transform, transform)); - samePose(camera, before); - }); - - test(`active globe rotation yields to ${name} without changing the camera`, (t) => { - const { viewer, camera, tick } = harness(t); - assert.equal( - moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, - true, - ); - viewer.scene.mode = sceneMode; - const before = pose(camera); - let rotations = 0; - camera.rotate = () => { - rotations += 1; - }; - tick(); - assert.equal(rotations, 0); - assert.equal(getActiveCameraMotion(), null); - assert.equal(hasRenderHold(), false); - samePose(camera, before); - }); + return { + viewer, + camera, + canvas, + target, + tick, + finishOnce, + followListeners: () => followListeners, + }; } test('globe rotation yields to tracking acquired and cleared before the next tick', (t) => { @@ -251,15 +247,13 @@ test('globe rotation yields to tracking acquired and cleared before the next tic ); const before = pose(camera); const entity = { id: 'cockpit-aircraft', position: {} }; - viewer.trackedEntity = entity; - viewer.trackedEntityChanged.raiseEvent(entity); + followEntity(viewer, entity); assert.equal( getActiveCameraMotion(), null, 'tracking acquisition must synchronously yield', ); - viewer.trackedEntity = undefined; - viewer.trackedEntityChanged.raiseEvent(undefined); + followEntity(viewer, null); tick(); samePose(camera, before); assert.equal(hasRenderHold(), false); @@ -272,33 +266,34 @@ test('tracking event keeps legacy yaw and an untracked globe rotation active', ( true, ); const yawId = activeCameraMotionId(); - viewer.trackedEntityChanged.raiseEvent({ id: 'aircraft' }); + followEntity(viewer, { id: 'aircraft' }); assert.equal(activeCameraMotionId(), yawId); + followEntity(viewer, null); assert.equal( moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, true, ); const globeId = activeCameraMotionId(); - viewer.trackedEntityChanged.raiseEvent(undefined); + followEntity(viewer, null); assert.equal(activeCameraMotionId(), globeId); }); test('replaced viewer releases the old tracking listener without duplicate subscriptions', (t) => { const first = harness(t); - assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1); + assert.equal(first.followListeners(), 1); initCameraVerbs(first.viewer); - assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1); + assert.equal(first.followListeners(), 1); const next = harness(t); - assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 0); - assert.equal(next.viewer.trackedEntityChanged.numberOfListeners, 1); + assert.equal(first.followListeners(), 0); + assert.equal(next.followListeners(), 1); assert.equal( moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, true, ); const id = activeCameraMotionId(); - first.viewer.trackedEntityChanged.raiseEvent({ id: 'stale-aircraft' }); + followEntity(first.viewer, { id: 'stale-aircraft' }); assert.equal(activeCameraMotionId(), id); - next.viewer.trackedEntityChanged.raiseEvent({ id: 'new-aircraft' }); + followEntity(next.viewer, { id: 'new-aircraft' }); assert.equal(getActiveCameraMotion(), null); assert.equal(hasRenderHold(), false); }); @@ -534,7 +529,7 @@ test('replacement motion rejects a stale globe owner cancellation', (t) => { assert.equal(hasRenderHold(), false); }); -test('replacing the viewer retires globe motion and its old clock listener', (t) => { +test('replacing the viewer retires globe motion and its old frame listener', (t) => { const { viewer, camera, tick } = harness(t); assert.equal( moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok, @@ -542,15 +537,16 @@ test('replacing the viewer retires globe motion and its old clock listener', (t) ); tick(); const before = pose(camera); - const nextViewer = { - ...viewer, - clock: { onTick: new Cesium.Event() }, - }; + const nextScene = { ...viewer.scene, preUpdate: new Cesium.Event() }; + const nextViewer = bindFakeCesiumCamera( + { ...viewer, scene: nextScene }, + { frame: fakeSceneFrame({ scene: nextScene }) }, + ); initCameraVerbs(nextViewer); assert.equal(getActiveCameraMotion(), null); assert.equal(hasRenderHold(), false); tick(); - nextViewer.clock.onTick.raiseEvent(nextViewer.clock); + nextScene.preUpdate.raiseEvent(nextScene); samePose(camera, before); }); @@ -580,7 +576,7 @@ for (const mode of ['once', 'continuous']) { tick(); assert.equal(hasRenderHold(), true); const tracked = { id: 'new-tracked-aircraft' }; - if (acquisition === 'tracking') viewer.trackedEntity = tracked; + if (acquisition === 'tracking') followEntity(viewer, tracked); else camera.lookAt( target, @@ -591,10 +587,9 @@ for (const mode of ['once', 'continuous']) { tick(); assert.equal(getActiveCameraMotion(), null); assert.equal(hasRenderHold(), false); - assert.equal( - viewer.trackedEntity, - acquisition === 'tracking' ? tracked : undefined, - ); + if (acquisition === 'tracking') + assert.equal(followedEntity(viewer), tracked); + else assert.equal(followedOf(viewer), null); assert.equal(Cesium.Matrix4.equals(camera.transform, transform), true); samePose(camera, before); tick(); @@ -605,7 +600,7 @@ for (const mode of ['once', 'continuous']) { test('direct globe rotation refuses a tracked camera without disturbing its reference frame', (t) => { const { viewer, camera, target } = harness(t); - viewer.trackedEntity = { id: 'tracked-aircraft' }; + followEntity(viewer, { id: 'tracked-aircraft', name: 'tracked-aircraft' }); camera.lookAt(target, new Cesium.HeadingPitchRange(0, radians(-40), 1_000)); const before = pose(camera); const transform = Cesium.Matrix4.clone(camera.transform); @@ -676,18 +671,19 @@ test('close-up refusal preserves an inherited target frame', (t) => { }); test('navigation callback never releases tracking for globe rotation', (t) => { const { viewer, camera } = harness(t); - const tracked = (viewer.trackedEntity = { id: 'tracked-aircraft' }); + const tracked = { id: 'tracked-aircraft' }; + followEntity(viewer, tracked); const before = pose(camera); let calls = 0; assert.equal( moveCamera({ motion: 'rotate_globe' }, () => { calls++; - viewer.trackedEntity = undefined; + followEntity(viewer, null); }).ok, false, ); assert.equal(calls, 0); - assert.equal(viewer.trackedEntity, tracked); + assert.equal(followedEntity(viewer), tracked); samePose(camera, before); }); test('direct globe request refuses Cockpit before navigation mutation', (t) => { @@ -878,8 +874,8 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) height: owner === 'close-up' ? 5000 : GLOBE_VIEW.heightM, }); const before = pose(camera); - if (owner === 'tracking') viewer.trackedEntity = { id: 'tracked-aircraft' }; - const tracked = viewer.trackedEntity; + if (owner === 'tracking') followEntity(viewer, { id: 'tracked-aircraft' }); + const tracked = followedEntity(viewer); let releases = 0, stamps = 0; const styleManager = { @@ -893,7 +889,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) }, release() { releases++; - viewer.trackedEntity = undefined; + followEntity(viewer, null); }, navigate, }); @@ -915,7 +911,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) assert.equal(result.ok, false); assert.equal(releases, 0); assert.equal(stamps, 0); - assert.equal(viewer.trackedEntity, tracked); + assert.equal(followedEntity(viewer), tracked); samePose(camera, before); if (owner === 'close-up') { assert.equal(result.reason, 'globe-view-required'); @@ -926,29 +922,6 @@ for (const owner of ['tracking', 'cockpit', 'close-up']) } }); -for (const [label, ellipsoid] of [ - ['nonfinite radii', { minimumRadius: 1, maximumRadius: Infinity }], - ['nonpositive radii', { minimumRadius: 0, maximumRadius: 1 }], - ['non-WGS84 radii', new Cesium.Ellipsoid(30_000_000, 30_000_000, 1_000_000)], -]) - test(`globe rotation refuses ${label} before handoff`, (t) => { - const { viewer, camera } = harness(t, { height: 100_000_000 }); - const before = pose(camera); - viewer.scene.globe.ellipsoid = ellipsoid; - let handedOff = false; - const result = moveCamera({ motion: 'rotate_globe' }, () => { - handedOff = true; - }); - assert.equal(result.ok, false); - assert.equal( - result.reason, - label === 'non-WGS84 radii' ? 'unsupported-view' : 'unsafe-ellipsoid', - ); - assert.equal(handedOff, false); - assert.equal(hasRenderHold(), false); - samePose(camera, before); - }); - test('an external radius change retires globe rotation without another write', (t) => { const { camera, tick } = harness(t); moveCamera({ motion: 'rotate_globe', mode: 'continuous' }); @@ -960,16 +933,6 @@ test('an external radius change retires globe rotation without another write', ( samePose(camera, changed); }); -test('a non-WGS84 ellipsoid fails closed rather than borrowing the WGS84 silhouette', (t) => { - const ellipsoid = new Cesium.Ellipsoid(10_000_000, 10_000_000, 8_000_000); - const { camera } = harness(t, { ellipsoid, latitude: 60 }); - const before = pose(camera); - const result = moveCamera({ motion: 'rotate_globe' }); - assert.equal(result.ok, false); - assert.equal(result.reason, 'unsupported-view'); - samePose(camera, before); -}); - test('untouched polar framing permits repeated direction and speed changes below preset altitude', (t) => { const { camera, finishOnce, tick } = harness(t, { latitude: 90 }); const radius = Cesium.Cartesian3.magnitude(camera.positionWC); @@ -1874,7 +1837,7 @@ test('a voice turn reported as done turns at least the half degree its check pro /** Track an entity below `camera`, locking it into that entity's frame. */ function trackFrom(viewer, camera) { - viewer.trackedEntity = { id: 'high-satellite' }; + followEntity(viewer, { id: 'high-satellite' }); const below = Cesium.Cartesian3.fromDegrees(10, 20, 400_000); camera.lookAtTransform(Cesium.Transforms.eastNorthUpToFixedFrame(below)); } @@ -1900,7 +1863,7 @@ test('a voice turn that releases a tracked camera is checked as released', (t) = }); trackFrom(viewer, camera); const releaseThenRun = (start) => { - viewer.trackedEntity = undefined; + followEntity(viewer, null); camera.lookAtTransform(Cesium.Matrix4.IDENTITY); return start(); }; @@ -1941,14 +1904,14 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => { for (let j = 0; j < 600 && getActiveCameraMotion(); j += 1) tick(1 / 60); } trackFrom(viewer, camera); - const tracked = viewer.trackedEntity; + const tracked = followedEntity(viewer); const transform = Cesium.Matrix4.clone(camera.transform); let released = false; const result = moveCamera( { motion: 'tilt', direction: 'up', mode: 'once' }, (start) => { released = true; - viewer.trackedEntity = undefined; + followEntity(viewer, null); camera.lookAtTransform(Cesium.Matrix4.IDENTITY); return start(); }, @@ -1957,7 +1920,7 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => { assert.equal(result.ok, false, label); assert.match(result.error, /globe out of view/, label); assert.equal(released, false, label); - assert.equal(viewer.trackedEntity, tracked, label); + assert.equal(followedEntity(viewer), tracked, label); assert.ok(Cesium.Matrix4.equals(camera.transform, transform), label); } }); @@ -1988,27 +1951,6 @@ test('a turn proven at one position is checked again after a release moves the c assert.match(result.error, /globe out of view/); }); -test('the voice frame limit leaves Columbus view alone', (t) => { - // At its limit in 3D a further tilt up is refused; the same tilt in Columbus - // view is not limited by the frame. - withScope(t, false); - const { viewer, finishOnce } = harness(t, { - pitch: -80, - viewportWidth: 1600, - viewportHeight: 900, - }); - assert.equal( - moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }).ok, - true, - ); - finishOnce(); - const refused = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }); - assert.match(refused.error || '', /globe out of view/); - viewer.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; - const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }); - assert.doesNotMatch(result.error || '', /globe out of view/); -}); - test('voice tilt below the free-look height is not limited by the frame', (t) => { const { camera, finishOnce } = harness(t, { height: 500_000, pitch: -60 }); const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }); diff --git a/src/cameraGroundGuard.js b/src/cameraGroundGuard.js index 3f9de0cabe..07c5431eaa 100644 --- a/src/cameraGroundGuard.js +++ b/src/cameraGroundGuard.js @@ -14,8 +14,11 @@ * lifts the eye if it sits below a usable clearance. Heading and pitch are * held, so the correction reads as the shot settling. */ -import * as Cesium from 'cesium'; +import { onFollowChanged } from './data/followed.js'; import { ownCameraArrival } from './data/cameraArrival.js'; +import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js'; +import { heightsOf } from './queries/heights.js'; +import { canvasOf, findCamera } from './render/rendererOf.js'; /** Minimum eye height above the rendered surface for a usable view. */ export const MIN_EYE_CLEARANCE_M = 120; @@ -24,35 +27,79 @@ const GUARD_ATTEMPTS = 8; const GUARD_INTERVAL_MS = 600; /** Ignore sub-metre noise rather than nudging the camera forever. */ const GUARD_EPSILON_M = 2; - -const probeScratch = new Cesium.Cartographic(); +/** Eye travel (m) and turn (cosine) that mean another owner moved the camera. */ +const MOVED_M = 0.01; +const TURNED_COS = 1 - 1e-9; /** * Highest rendered surface across a few cells, with how many cells answered. * A cell whose tiles are not streamed yet contributes nothing. - * @param {Cesium.Scene} scene Live scene. + * @param {import('./queries/heights.js').HeightService|null} heights The + * scene's height service. * @param {Array<{lat: number, lon: number}>} cells Cells to probe. * @returns {{heightM: number, sampled: number}} Reading. */ -function sampleSurfaceM(scene, cells) { +function sampleSurfaceM(heights, cells) { let heightM = Number.NaN; let sampled = 0; - if (typeof scene?.sampleHeight !== 'function') return { heightM, sampled }; + if (!heights) return { heightM, sampled }; for (const cell of cells) { - try { - const height = scene.sampleHeight( - Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, probeScratch), - ); - if (!Number.isFinite(height)) continue; - sampled += 1; - heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; - } catch { - /* tiles not ready for this cell */ - } + // A miss is a cell whose tiles are not ready. + const height = heights.now(cell); + if (!Number.isFinite(height)) continue; + sampled += 1; + heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; } return { heightM, sampled }; } +/** + * The eye as the camera port poses it: where it is (from its position) and + * which way it looks; null when the pose cannot be read. + */ +function eyeOf(camera) { + try { + const pose = camera?.pose(); + const at = pose?.position && toLonLatH(pose.position); + if (!at || !pose.direction || !pose.up) return null; + return { ...pose, lon: at.lon, lat: at.lat, height: at.height }; + } catch { + return null; + } +} + +/** The eye's ground point (height 0), its height, and which way it looks. */ +function poseOf(eye) { + if (!eye) return null; + return { + ground: fromDegrees(eye.lon, eye.lat), + height: eye.height, + direction: { ...eye.direction }, + up: { ...eye.up }, + }; +} + +/** + * Whether another owner has moved the camera off `pose`: across the ground, + * down, or around. A pure rise is not one: the renderer's terrain collision + * lifts a buried eye straight up as tiles load, which is the case the guard + * exists for, so `pose` follows the highest eye seen and the guard keeps + * measuring. + */ +function moved(now, pose) { + if (!now) return true; + const ground = fromDegrees(now.lon, now.lat); + if ( + distance(ground, pose.ground) > MOVED_M || + now.height < pose.height - MOVED_M || + dot(now.direction, pose.direction) < TURNED_COS || + dot(now.up, pose.up) < TURNED_COS + ) + return true; + pose.height = Math.max(pose.height, now.height); + return false; +} + /** * How far the camera must rise to clear the ground, given a measured surface. * Pure so the policy is testable without a scene. @@ -76,9 +123,11 @@ export function groundClearanceDeficitM( * Watch an arrival and lift the camera once the real surface can be measured. * * Stops quietly on a clear view, exhausted attempts, the user taking the - * controls (pointer or wheel on the canvas), or `isStale()` reporting that a - * newer arrival owns the camera. - * @param {Cesium.Viewer} viewer Live viewer. + * controls (pointer or wheel on the canvas), `isStale()` reporting that a + * newer arrival owns the camera, or any other caller moving the camera or + * starting a flight in the meantime: the guard only ever corrects the pose it + * was started on. + * @param {object} viewer Live viewer. * @param {{lat: number, lon: number}} at Destination being framed. * @param {{clearanceM?: number, attempts?: number, intervalMs?: number, * isStale?: () => boolean, onLift?: (liftM: number) => void}} [options] @@ -92,12 +141,16 @@ export function guardCameraAboveGround(viewer, at, options = {}) { isStale = () => false, onLift = null, } = options; - if (!viewer?.scene || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon)) + if (!viewer || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon)) return () => {}; + // Without a readable pose the guard could not tell a later owner's move. + const arrival = poseOf(eyeOf(findCamera(viewer))); + if (!arrival) return () => {}; + let timer = null; let done = false; - const canvas = viewer.scene.canvas; + const canvas = canvasOf(viewer); const documentRef = canvas?.ownerDocument; const removers = []; let release = () => {}; @@ -112,32 +165,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) { release(); }; release = ownCameraArrival(viewer, stop); - // Direct camera API callers (including duration-zero flights) must yield - // before moving the eye. Restore the exact method ownership on completion. - for (const name of [ - 'flyTo', - 'flyToBoundingSphere', - 'setView', - 'lookAt', - 'cancelFlight', - ]) { - const camera = viewer.camera; - const original = camera[name]; - if (typeof original !== 'function') continue; - const descriptor = Object.getOwnPropertyDescriptor(camera, name); - const wrapped = function (...args) { - stop(); - return original.apply(this, args); - }; - camera[name] = wrapped; - removers.push(() => { - if (camera[name] !== wrapped) return; - if (descriptor) Object.defineProperty(camera, name, descriptor); - else delete camera[name]; - }); - } - const removeTracking = viewer.trackedEntityChanged?.addEventListener(stop); - if (removeTracking) removers.push(removeTracking); + removers.push(onFollowChanged(viewer, stop)); documentRef?.addEventListener?.('keydown', stop, true); // A manual gesture ends the guard, as it interrupts camera motion elsewhere. for (const type of ['pointerdown', 'wheel']) @@ -147,40 +175,33 @@ export function guardCameraAboveGround(viewer, at, options = {}) { const attempt = () => { if (done) return; if (isStale() || viewer.isDestroyed?.()) return stop(); + const camera = findCamera(viewer); + const now = eyeOf(camera); + // Another caller owns the camera now; lifting would undo its move. + if (!camera || camera.flying || moved(now, arrival)) return stop(); remaining -= 1; - const camera = viewer.camera; - const carto = camera.positionCartographic; // The eye must clear both the framed target and the ground beneath it. - const below = { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), - }; - const { heightM, sampled } = sampleSurfaceM(viewer.scene, [ - { lat: at.lat, lon: at.lon }, - below, - ]); + const below = { lat: now.lat, lon: now.lon }; + const { heightM, sampled } = sampleSurfaceM( + viewer ? heightsOf(viewer) : null, + [{ lat: at.lat, lon: at.lon }, below], + ); if (sampled > 0 && Number.isFinite(heightM)) { - const deficit = groundClearanceDeficitM( - carto.height, - heightM, - clearanceM, - ); + const deficit = groundClearanceDeficitM(now.height, heightM, clearanceM); if (deficit > 0) { stop(); - camera.flyTo({ - destination: Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height + deficit, - ), - orientation: { - heading: camera.heading, - pitch: camera.pitch, - roll: camera.roll, + camera.flyTo( + { lon: now.lon, lat: now.lat, height: now.height + deficit }, + { + orientation: { + heading: now.heading, + pitch: now.pitch, + roll: now.roll, + }, + durationS: 0.9, + easing: 'cubicInOut', }, - duration: 0.9, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - }); + ); try { onLift?.(deficit); } catch { diff --git a/src/cameraGroundGuard.test.mjs b/src/cameraGroundGuard.test.mjs index 5c8f530303..fb751ce2a3 100644 --- a/src/cameraGroundGuard.test.mjs +++ b/src/cameraGroundGuard.test.mjs @@ -3,6 +3,12 @@ // Arrival framing is computed before the destination's tiles exist, so it // works from a predicted ground height. The guard measures the real surface // after arrival and lifts the eye; these tests pin when it acts. +import { + bindFakeCesiumCamera, + followEntity, +} from './testSupport/fakeCameraPort.mjs'; +import { rendererOf } from './render/rendererOf.js'; +import { fakeSceneQuery } from './testSupport/fakeCesiumScene.mjs'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; @@ -47,24 +53,71 @@ test('the clearance frames a subject without turning into an overflight', () => assert.ok(MIN_EYE_CLEARANCE_M <= 250); }); -function fakeViewer({ cameraHeightM, surfaceM }) { +/** + * Count the listeners for `viewer`'s camera port follow changes, from now on. + * @returns {() => number} + */ +function countFollowListeners(viewer) { + const renderer = rendererOf(viewer); + const port = renderer.camera; + let listeners = 0; + renderer.camera = Object.create(port, { + on: { + value(event, cb, options) { + const off = port.on(event, cb, options); + if (event !== 'followChanged') return off; + listeners += 1; + let live = true; + return () => { + if (live) listeners -= 1; + live = false; + off(); + }; + }, + }, + }); + return () => listeners; +} + +function fakeViewer({ cameraHeightM, surfaceM, tracks = false }) { const flights = []; - const position = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, cameraHeightM); - return { + const position = Cesium.Cartographic.fromDegrees( + -97.7603, + 30.3141, + cameraHeightM, + ); + const viewer = { flights, scene: { canvas: null, + sampleHeightSupported: true, sampleHeight: (carto) => typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM, }, camera: { positionCartographic: position, + positionWC: Cesium.Cartographic.toCartesian(position), + directionWC: new Cesium.Cartesian3(0, 0, -1), + upWC: new Cesium.Cartesian3(0, 1, 0), heading: 0.5, pitch: -0.55, roll: 0, - flyTo: (options) => flights.push(options), + // As Cesium does: a flight is under way until it completes. + _currentFlight: undefined, + flyTo(options) { + flights.push(options); + this._currentFlight = {}; + }, }, }; + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. + if (tracks) + Object.assign(viewer, { + trackedEntityChanged: new Cesium.Event(), + entities: {}, + }); + return bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) }); } test('the guard lifts a buried arrival once the surface answers', async () => { @@ -104,7 +157,11 @@ test('the guard waits for streaming tiles and yields to a newer arrival', async test('the guard leaves a clear view untouched', async () => { const viewer = fakeViewer({ cameraHeightM: 400, surfaceM: 171 }); - guardCameraAboveGround(viewer, { lat: 30.3125, lon: -97.765 }, { intervalMs: 1 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 1 }, + ); await new Promise((resolve) => setTimeout(resolve, 20)); assert.equal(viewer.flights.length, 0); }); @@ -116,39 +173,85 @@ import { LayerLifecycle } from './data/lifecycle.js'; function handoffFixture(t) { t.mock.timers.enable({ apis: ['setTimeout'] }); - const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 }); + const viewer = fakeViewer({ + cameraHeightM: 172, + surfaceM: 171, + tracks: true, + }); + const followListeners = countFollowListeners(viewer); viewer.scene.canvas = new EventTarget(); viewer.scene.canvas.ownerDocument = new EventTarget(); - viewer.trackedEntityChanged = new Cesium.Event(); viewer.camera.cancelFlight = () => {}; viewer.camera.lookAtTransform = () => {}; - viewer.camera.flyToBoundingSphere = () => {}; - viewer.camera.setView = () => {}; + viewer.camera.flyToBoundingSphere = function () { + this._currentFlight = {}; + }; + viewer.camera.setView = function () { + this.positionWC = Cesium.Cartesian3.add( + this.positionWC, + new Cesium.Cartesian3(0, 0, 50), + new Cesium.Cartesian3(), + ); + }; const originalFly = viewer.camera.flyTo; const navigation = new NavigationController({ viewer, - tracking: Object.fromEntries(['flightsLayer', 'militaryFlightsLayer', - 'satellitesLayer', 'aisLiveVesselsLayer', 'militaryAwarenessLayer', - 'rocketLaunchesLayer'].map((key) => [key, {}])), - cancelOrientation() {}, clearLocation() {}, cancelShareSelection() {}, - getDataManager() {}, interruptCameraMotion() {}, stopOrbit() {}, - isCockpitActive: () => false, showToast() {}, + tracking: Object.fromEntries( + [ + 'flightsLayer', + 'militaryFlightsLayer', + 'satellitesLayer', + 'aisLiveVesselsLayer', + 'militaryAwarenessLayer', + 'rocketLaunchesLayer', + ].map((key) => [key, {}]), + ), + cancelOrientation() {}, + clearLocation() {}, + cancelShareSelection() {}, + getDataManager() {}, + interruptCameraMotion() {}, + stopOrbit() {}, + isCockpitActive: () => false, + showToast() {}, }); guardCameraAboveGround(viewer, { lat: 30.3, lon: -97.7 }); - return { viewer, navigation, originalFly }; + return { viewer, navigation, originalFly, followListeners }; } -for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI', - 'flyTo', 'flyToBoundingSphere', 'setView', 'layer-disable', 'layer-destroy', 'app-stop']) { +for (const handoff of [ + 'Director', + 'tracking', + 'follow', + 'keyboard', + 'UI', + 'flyTo', + 'flyToBoundingSphere', + 'setView', + 'layer-disable', + 'layer-destroy', + 'app-stop', +]) { test(`arrival guard relinquishes and removes hooks on ${handoff}`, async (t) => { - const { viewer, navigation, originalFly } = handoffFixture(t); + const { viewer, navigation, originalFly, followListeners } = + handoffFixture(t); + const methods = [ + 'flyTo', + 'flyToBoundingSphere', + 'setView', + 'lookAt', + 'cancelFlight', + ].map((name) => viewer.camera[name]); if (handoff === 'Director') { SceneDirector.prototype._claimCameraOwnership.call({ - viewer, styleManager: { runImmediateNavigation: (noun, fn) => - navigation._runExplicitNavigation(noun, fn) }, + viewer, + styleManager: { + runImmediateNavigation: (noun, fn) => + navigation._runExplicitNavigation(noun, fn), + }, }); } else if (handoff === 'tracking') { - viewer.trackedEntityChanged.raiseEvent({ id: 'contact' }); + followEntity(viewer, { id: 'contact' }); } else if (handoff === 'follow' || handoff === 'UI') { navigation._stampNavigation({ cancelPendingSelection: false }); } else if (handoff === 'keyboard') { @@ -156,16 +259,81 @@ for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI', } else if (handoff === 'app-stop') navigation.stop(); else if (handoff.startsWith('layer-')) { const lifecycle = new LayerLifecycle(viewer); - lifecycle.register({ id: 'test', init() {}, enable() {}, disable() {}, destroy() {} }); + lifecycle.register({ + id: 'test', + init() {}, + enable() {}, + disable() {}, + destroy() {}, + }); await lifecycle.setEnabled('test', true); - if (handoff === 'layer-disable') await lifecycle.setEnabled('test', false); + if (handoff === 'layer-disable') + await lifecycle.setEnabled('test', false); else await lifecycle.destroyLayer('test'); } else viewer.camera[handoff]({}); + // A direct flyTo is itself one recorded flight; the guard adds none. const priorFlights = viewer.flights.length; t.mock.timers.tick(10000); - assert.equal(viewer.flights.length, priorFlights, 'the old probe cannot fly'); - assert.equal(viewer.camera.flyTo, originalFly, 'direct-call hook is removed'); - assert.equal(viewer.trackedEntityChanged.numberOfListeners, 0); + assert.equal( + viewer.flights.length, + priorFlights, + 'the old probe cannot fly', + ); + assert.equal(viewer.camera.flyTo, originalFly); + assert.deepEqual( + ['flyTo', 'flyToBoundingSphere', 'setView', 'lookAt', 'cancelFlight'].map( + (name) => viewer.camera[name], + ), + methods, + 'the guard never replaces camera methods', + ); + assert.equal(followListeners(), 0); navigation.destroy(); }); } + +test('the guard yields to a camera moved without any camera method', async () => { + const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 5 }, + ); + // A cockpit or follow frame writes the pose directly. + viewer.camera.directionWC = new Cesium.Cartesian3(1, 0, 0); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(viewer.flights.length, 0, 'the moved view is not corrected'); +}); + +test('Cesium lifting a buried eye straight up is not another owner', async () => { + const viewer = fakeViewer({ cameraHeightM: 104, surfaceM: 171 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 5 }, + ); + // Terrain collision raises the eye to just above the loaded ground. + const raised = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 172); + viewer.camera.positionCartographic = raised; + viewer.camera.positionWC = Cesium.Cartographic.toCartesian(raised); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(viewer.flights.length, 1, 'the guard still lifts the eye'); + const lifted = Cesium.Cartographic.fromCartesian( + viewer.flights[0].destination, + ); + assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5); +}); + +test('another owner lowering the eye is not corrected', async () => { + const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 }); + guardCameraAboveGround( + viewer, + { lat: 30.3125, lon: -97.765 }, + { intervalMs: 5 }, + ); + const lowered = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 150); + viewer.camera.positionCartographic = lowered; + viewer.camera.positionWC = Cesium.Cartographic.toCartesian(lowered); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(viewer.flights.length, 0); +}); diff --git a/src/cameraHandoff.test.mjs b/src/cameraHandoff.test.mjs index 1c41139c8a..747a2f0a97 100644 --- a/src/cameraHandoff.test.mjs +++ b/src/cameraHandoff.test.mjs @@ -44,8 +44,8 @@ test('Cockpit takeover invalidates deferred work before camera cancellation', () ordered(enter, [ 'if (!info || (!vessel && !satellite && !entity?.position)) return false;', 'this.onCameraTakeover?.();', - 'this.viewer.camera.cancelFlight();', - 'this.viewer.trackedEntity = undefined;', + 'cameraOf(this.viewer).cancelFlight();', + 'stopFollowing(this.viewer);', ], 'Cockpit takeover'); assert.match( ui, @@ -97,7 +97,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () => // The transaction has exactly two camera-owner mutations, and each one // stamps: // 1. selectedLayer.trackById(id) -> viewer.trackedEntity - // -> viewer.trackedEntityChanged -> _stampNavigation() + // -> onFollowChanged(viewer) -> _stampNavigation() // 2. cockpitView.enter() -> onCameraTakeover() -> _stampNavigation() const transaction = body( cockpitTracking, @@ -118,7 +118,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () => // Seam 1: any tracker handoff stamps, so the adoption step is covered. assert.match( ui, - /viewer\.trackedEntityChanged\.addEventListener\(\s*\(entity\) => \{\s*if \(entity && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/, + /onFollowChanged\(\s*this\.viewer,\s*\(followed\) => \{\s*if \(followed && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/, 'tracker handoff must stamp', ); // Seam 2 is pinned by "Cockpit takeover invalidates deferred work" above. @@ -191,10 +191,10 @@ test('accepted navigation releases through PR15-aware ownership before flight', 'origin: trackingOrigin', 'satellitesLayer.stopTracking?.({ origin: trackingOrigin })', 'rocketLaunchesLayer.releaseCameraOwnership?.()', - 'this.viewer.trackedEntity = undefined;', + 'stopFollowing(this.viewer);', "interruptCameraMotion('explicit-navigation')", - 'this.viewer.camera.cancelFlight();', - 'this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);', + 'camera?.cancelFlight();', + 'camera?.release();', ], 'follow release'); assert.match(release, /flightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/); assert.match(release, /militaryFlightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/); @@ -282,11 +282,11 @@ test('a direct globe gesture retires delayed camera and selection restore only', ); assert.match( ui, - /viewer\?\.canvas\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/, + /canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/, ); assert.match( ui, - /viewer\?\.canvas\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/, + /canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/, ); assert.match( ui, @@ -399,7 +399,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () => } const vesselClick = body( vessels, - /handler\.setInputAction\(\s*\(click\) => \{([\s\S]*?)\n\s*\},\s*Cesium\.ScreenSpaceEventType\.LEFT_CLICK,?\s*\);/, + /inputFor\(viewer\)\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/, 'vessel click', ); ordered(vesselClick, [ @@ -415,7 +415,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () => assert.match(vesselFocus, /requestWorldFocus\(\{/); const fireClick = body( firms, - /_clickHandler\.setInputAction\(\(click\) => \{([\s\S]*?)\n \}, Cesium\.ScreenSpaceEventType\.LEFT_CLICK\);/, + /input\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/, 'fire click', ); ordered(fireClick, [ diff --git a/src/cameraTilt.test.mjs b/src/cameraTilt.test.mjs index 8a3d1447f0..cac0d7e14f 100644 --- a/src/cameraTilt.test.mjs +++ b/src/cameraTilt.test.mjs @@ -9,6 +9,14 @@ import { moveCamera, } from './cameraVerbs.js'; import { createGevActionRunner } from './voice/gevActions.js'; +import { + bindFakeCesiumCamera, + followEntity, +} from './testSupport/fakeCameraPort.mjs'; +import { + fakeSceneFrame, + fakeSceneQuery, +} from './testSupport/fakeCesiumScene.mjs'; const radians = Cesium.Math.toRadians; const degrees = Cesium.Math.toDegrees; @@ -39,6 +47,7 @@ function harness( mode: Cesium.SceneMode.SCENE3D, pixelRatio: 1, tweens: [], + preUpdate: new Cesium.Event(), requestRender() {}, }; const camera = new Cesium.Camera(scene); @@ -47,13 +56,21 @@ function harness( destination: Cesium.Cartesian3.fromDegrees(-0.1276, 51.5072, height), orientation: { heading: radians(heading), pitch: radians(pitch), roll: 0 }, }); - const viewer = { + const double = { camera, scene, - trackedEntity: undefined, + // Cesium's entity tracking, without entities of its own: the camera + // port follows on a tracking widget of the fake's. trackedEntityChanged: new Cesium.Event(), + entities: {}, clock: { onTick: new Cesium.Event() }, }; + // The Cesium renderer's own camera port over the real camera; frames from + // the scene's preUpdate. + const viewer = bindFakeCesiumCamera(double, { + query: fakeSceneQuery(double), + frame: fakeSceneFrame(double), + }); // The app's view target: the ground point under the screen centre. const viewTarget = () => { const ray = new Cesium.Ray(camera.positionWC, camera.directionWC); @@ -68,7 +85,7 @@ function harness( }); const tick = (seconds = 1 / 30) => { nowMs += seconds * 1000; - viewer.clock.onTick.raiseEvent(viewer.clock); + viewer.scene.preUpdate.raiseEvent(viewer.scene); }; const finish = () => { for (let i = 0; i < 600 && getActiveCameraMotion(); i += 1) tick(); @@ -239,9 +256,7 @@ test('a pivoting tilt yields when tracking takes the camera', (t) => { const h = harness(t); assert.equal(moveCamera({ motion: 'tilt', pitchDeg: -45 }).ok, true); h.tick(); - const entity = { id: 'tracked' }; - h.viewer.trackedEntity = entity; - h.viewer.trackedEntityChanged.raiseEvent(entity); + followEntity(h.viewer, { id: 'tracked' }); assert.equal(getActiveCameraMotion(), null); }); @@ -548,10 +563,10 @@ test('a regional tilt-up nudge goes to the camera horizon limit', (t) => { test('a voice tilt from a tracked view judges its limit from the camera pitch', (t) => { const h = harness(t, { height: 20000, pitch: -5.2 }); - h.viewer.trackedEntity = { id: 'tracked' }; + followEntity(h.viewer, { id: 'tracked' }); // Voice releases the follow camera before the motion starts. const release = (start) => { - h.viewer.trackedEntity = undefined; + followEntity(h.viewer, null); return start(); }; const result = moveCamera({ motion: 'tilt', direction: 'up' }, release); diff --git a/src/cameraVerbs.js b/src/cameraVerbs.js index 5ac86bc365..ce61912b88 100644 --- a/src/cameraVerbs.js +++ b/src/cameraVerbs.js @@ -18,13 +18,14 @@ * globe motion, opposite to the camera's travel around Earth. */ -import * as Cesium from 'cesium'; +import { followedOf, isFollowing, onFollowChanged } from './data/followed.js'; import { GLOBE_VIEW } from './locations.js'; import { globeFrameShare, isFreeGlobeCamera, lookAngleWithinFrame, lookStepLosesGlobe, + lookedPose, } from './globeInView.js'; import { projectEarthDiscToViewport, @@ -37,6 +38,43 @@ import { holdContinuousRender, releaseContinuousRender, } from './renderGovernor.js'; +import { + PI_OVER_TWO, + WGS84, + add, + clamp, + cross, + distance, + dot, + eastNorthUp, + framePoint, + fromAxisAngle, + fromDegrees, + fromRadians, + frameVector, + geodeticSurfaceNormal, + headingPitchRollFrame, + inverseFramePoint, + lerpInto, + magnitude, + negativePiToPi, + normalize, + scale, + sub, + toAxes, + toCartographicRadians, + toDegrees, + toRadians, + vec, +} from './geo/index.js'; +import { eyeMoved, eyeRotatedAbout, eyeTurned } from './geo/eyeMoves.js'; +import { heightsOf } from './queries/heights.js'; +import { + cameraOf, + canvasOf, + findCamera, + findFrame, +} from './render/rendererOf.js'; let _isCockpitActive = null; /** °/s by speed word — orbit; pan uses fractions of view height/s. */ @@ -54,8 +92,8 @@ const ONCE = { panViewFraction: 0.25, durationS: 0.9, }; -const PITCH_MIN = Cesium.Math.toRadians(-89); -const PITCH_MAX = Cesium.Math.toRadians(-5); +const PITCH_MIN = toRadians(-89); +const PITCH_MAX = toRadians(-5); /** A bare "tilt the camera" / "oblique view" settles here. */ const TILT_DEFAULT_PITCH_DEG = -45; /** °/s for a tilt to a requested angle; short ones keep the once duration. */ @@ -82,7 +120,7 @@ const TILT_PIVOT_RANGE_SLACK_M = 1; * place's horizon; tilting the rest in place there would lift the crosshair * onto the sky, so the swing stops with the place this far above it. */ -const TILT_MIN_PIVOT_ELEVATION = Cesium.Math.toRadians(0.5); +const TILT_MIN_PIVOT_ELEVATION = toRadians(0.5); /* ── Route dolly: cinematic tuning ────────────────────────────────────────── * Every knob an owner may want to retune lives in this block. The shaping is @@ -341,30 +379,30 @@ export const ROUTE_CINEMA = Object.freeze({ /* ── Route dolly geometry ────────────────────────────────────────────────── */ -const _arcA = new Cesium.Cartesian3(); -const _arcB = new Cesium.Cartesian3(); -const _chordVertical = new Cesium.Cartesian3(); -const _turnCross = new Cesium.Cartesian3(); -const _framePos = new Cesium.Cartesian3(); -const _frameAheadPos = new Cesium.Cartesian3(); -const _frameUp = new Cesium.Cartesian3(); -const _frameIn = new Cesium.Cartesian3(); -const _frameOut = new Cesium.Cartesian3(); -const _frameGaze = new Cesium.Cartesian3(); -const _frameRight = new Cesium.Cartesian3(); -const _frameLevelUp = new Cesium.Cartesian3(); -const _frameDir = new Cesium.Cartesian3(); -const _frameEye = new Cesium.Cartesian3(); -const _frameBankedUp = new Cesium.Cartesian3(); -const _frameCarto = new Cesium.Cartographic(); -const _frameAheadCarto = new Cesium.Cartographic(); -const _bankQuat = new Cesium.Quaternion(); -const _bankMatrix = new Cesium.Matrix3(); -const _headingQuat = new Cesium.Quaternion(); -const _headingMatrix = new Cesium.Matrix3(); -const _warmPos = new Cesium.Cartesian3(); -const _warmCarto = new Cesium.Cartographic(); -const _probeCarto = new Cesium.Cartographic(); +/** Scratch points for the per-frame arc reads. */ +const _arcA = vec(); +const _arcB = vec(); +const _framePos = vec(); +const _frameAheadPos = vec(); +const _warmPos = vec(); + +/** `v` turned by `angle` radians about `axis`: quaternion, then its axes. */ +const rotateAbout = (v, axis, angle) => + frameVector(toAxes(fromAxisAngle(axis, angle)), v); + +/** `v` less its part along unit `up`. */ +function horizontalPart(v, up) { + const along = dot(v, up); + return vec(v.x - up.x * along, v.y - up.y * along, v.z - up.z * along); +} + +/** The ellipsoid's unit normal at geodetic `lon`, `lat` (radians). */ +function surfaceNormal(lon, lat) { + const cosLat = Math.cos(lat); + return normalize( + vec(cosLat * Math.cos(lon), cosLat * Math.sin(lon), Math.sin(lat)), + ); +} /** Point at arc length `s` along the polyline (binary search — queries jump * backwards for the inbound chord, so a forward cursor would not do). */ @@ -381,23 +419,17 @@ function arcPoint(state, s, result) { const segLen = cumM[lo + 1] - cumM[lo]; const t = segLen > 1e-6 ? Math.min(1, Math.max(0, (clamped - cumM[lo]) / segLen)) : 0; - return Cesium.Cartesian3.lerp(pts[lo], pts[lo + 1], t, result); + return lerpInto(pts[lo], pts[lo + 1], t, result); } /** Unit horizontal direction from arc `sA` to arc `sB`, or null when degenerate. */ -function horizontalChord(state, sA, sB, up, result) { +function horizontalChord(state, sA, sB, up) { const a = arcPoint(state, sA, _arcA); const b = arcPoint(state, sB, _arcB); - Cesium.Cartesian3.subtract(b, a, result); - const vertical = Cesium.Cartesian3.multiplyByScalar( - up, - Cesium.Cartesian3.dot(result, up), - _chordVertical, - ); - Cesium.Cartesian3.subtract(result, vertical, result); - const len = Cesium.Cartesian3.magnitude(result); + const horizontal = horizontalPart(vec(b.x - a.x, b.y - a.y, b.z - a.z), up); + const len = magnitude(horizontal); if (!(len > 1e-3)) return null; - return Cesium.Cartesian3.divideByScalar(result, len, result); + return vec(horizontal.x / len, horizontal.y / len, horizontal.z / len); } /** @@ -407,15 +439,14 @@ function horizontalChord(state, sA, sB, up, result) { * floating-point signed zeros, so an out-and-back route would flip the bank * direction frame to frame. A U-turn is resolved as a RIGHT turn, always — * arbitrary, but deterministic, which is the property that matters. - * @param {Cesium.Cartesian3} a Unit horizontal direction turned FROM. - * @param {Cesium.Cartesian3} b Unit horizontal direction turned TO. - * @param {Cesium.Cartesian3} up Local up, the axis the turn is measured about. + * @param {{x: number, y: number, z: number}} a Unit horizontal direction turned FROM. + * @param {{x: number, y: number, z: number}} b Unit horizontal direction turned TO. + * @param {{x: number, y: number, z: number}} up Local up, the axis the turn is measured about. * @returns {number} Radians, + = right. */ export function signedTurnRad(a, b, up) { - const cross = Cesium.Cartesian3.cross(a, b, _turnCross); - const sinLeft = Cesium.Cartesian3.dot(cross, up); - const cosTurn = Cesium.Cartesian3.dot(a, b); + const sinLeft = dot(cross(a, b), up); + const cosTurn = dot(a, b); if (cosTurn <= -1 + ANTIPODAL_EPS && Math.abs(sinLeft) < ANTIPODAL_EPS) return Math.PI; return -Math.atan2(sinLeft, cosTurn); @@ -447,14 +478,9 @@ export function routeCorridorCells( s <= end + 1e-6 && out.length < maxCells; s += ROUTE_WARM_STEP_M ) { - const point = arcPoint(state, s, _warmPos); - const carto = Cesium.Cartographic.fromCartesian( - point, - Cesium.Ellipsoid.WGS84, - _warmCarto, - ); - const lat = Number(Cesium.Math.toDegrees(carto.latitude).toFixed(3)); - const lon = Number(Cesium.Math.toDegrees(carto.longitude).toFixed(3)); + const carto = toCartographicRadians(arcPoint(state, s, _warmPos)); + const lat = Number(toDegrees(carto.lat).toFixed(3)); + const lon = Number(toDegrees(carto.lon).toFixed(3)); const key = `${lat},${lon}`; if (seen.has(key)) continue; seen.add(key); @@ -587,32 +613,24 @@ function acquireCorridorFloor(state, takeWhole) { * Highest rendered surface across a handful of corridor cells, with the number * of cells that actually answered — a cell whose tiles are not streamed yet * contributes nothing, and the caller must not mistake silence for flat ground. - * @param {Cesium.Scene|undefined} scene The live scene. + * @param {object|undefined} viewer The live scene object, asked through its + * renderer's heights (`heightsOf`). * @param {Array<{lat: number, lon: number}>} cells Cells to probe. * @returns {{heightM: number, sampled: number, requested: number}} The reading. */ -export function probeMeshFloorM(scene, cells) { +export function probeMeshFloorM(viewer, cells) { const requested = Array.isArray(cells) ? cells.length : 0; const empty = { heightM: Number.NaN, sampled: 0, requested }; - if (!scene || typeof scene.sampleHeight !== 'function' || !requested) - return empty; + if (!viewer || !requested) return empty; + const heights = heightsOf(viewer); let heightM = Number.NaN; let sampled = 0; for (const cell of cells) { - try { - const carto = Cesium.Cartographic.fromDegrees( - cell.lon, - cell.lat, - 0, - _probeCarto, - ); - const height = scene.sampleHeight(carto); - if (!Number.isFinite(height)) continue; - sampled += 1; - heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; - } catch { - /* tiles not ready for this cell */ - } + // A miss is a cell whose tiles are not ready. + const height = heights.now({ lon: cell.lon, lat: cell.lat }); + if (height === null) continue; + sampled += 1; + heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; } return { heightM, sampled, requested }; } @@ -620,7 +638,8 @@ export function probeMeshFloorM(scene, cells) { /** * Build the state for one cinematic route flight. * @param {Object} options - * @param {Cesium.Cartesian3[]} options.pts Route vertices. + * @param {Array<{x: number, y: number, z: number}>} options.pts Route + * vertices, ECEF. * @param {number[]} options.cumM Cumulative arc length per vertex. * @param {string} [options.speed] slow | normal | fast. * @param {Function|null} [options.floorFn] (latDeg, lonDeg) => floor metres. @@ -649,11 +668,7 @@ export function createRouteFlight({ // the mean: routes under 10 m (slow) / 20 m (normal) / 45 m (fast) fly slower // than asked. Those are shorter than the camera is tall — nothing to see. const durationS = Math.max(0.5, totalM / cruiseMps); - const pathHeightM = Cesium.Cartographic.fromCartesian( - pts[0], - Cesium.Ellipsoid.WGS84, - _warmCarto, - ).height; + const pathHeightM = toCartographicRadians(pts[0]).height; const state = { kind: 'route', mode: 'continuous', @@ -712,8 +727,8 @@ export function createRouteFlight({ * the viewer (so this stays testable without one). * @param {Object} state From createRouteFlight(). * @param {number} dt Seconds elapsed. - * @returns {{finished: boolean, eye: Cesium.Cartesian3, direction: Cesium.Cartesian3, - * up: Cesium.Cartesian3, bankDeg: number, heightM: number, aglM: number, + * @returns {{finished: boolean, eye: Object, direction: Object, + * up: Object, bankDeg: number, heightM: number, aglM: number, * groundSpeedMps: number, progress: number}} The frame. */ export function advanceRouteFlight(state, dt) { @@ -747,37 +762,17 @@ export function advanceRouteFlight(state, dt) { state.groundSpeedMps = cruiseMps * profile.speed; const pos = arcPoint(state, traveled, _framePos); - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - _frameCarto, - ); - const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormalCartographic( - carto, - _frameUp, - ); + const carto = toCartographicRadians(pos); + const up = surfaceNormal(carto.lon, carto.lat); // Planned turn: compare where we came from with where we are going, over a // window centred on the camera. Peaks AT the corner, tapers either side. const halfWindowM = Math.max(20, (ROUTE_BANK_WINDOW_S * cruiseMps) / 2); - const inbound = horizontalChord( - state, - traveled - halfWindowM, - traveled, - up, - _frameIn, - ); - const outbound = horizontalChord( - state, - traveled, - traveled + halfWindowM, - up, - _frameOut, - ); + const inbound = horizontalChord(state, traveled - halfWindowM, traveled, up); + const outbound = horizontalChord(state, traveled, traveled + halfWindowM, up); const turnRateDegS = inbound && outbound - ? Cesium.Math.toDegrees(signedTurnRad(inbound, outbound, up)) / - ROUTE_BANK_WINDOW_S + ? toDegrees(signedTurnRad(inbound, outbound, up)) / ROUTE_BANK_WINDOW_S : 0; const bankTarget = routeBankTargetDeg(turnRateDegS, state.reducedMotion); state.bankLeadDeg = approachValue( @@ -805,11 +800,10 @@ export function advanceRouteFlight(state, dt) { Math.max(ROUTE_LOOKAHEAD_MIN_M, ROUTE_LOOKAHEAD_S * cruiseMps), ); const gaze = - horizontalChord(state, traveled, traveled + lookaheadM, up, _frameGaze) || + horizontalChord(state, traveled, traveled + lookaheadM, up) || outbound || inbound; - if (gaze && !state.headingDir) - state.headingDir = Cesium.Cartesian3.clone(gaze); + if (gaze && !state.headingDir) state.headingDir = vec(gaze.x, gaze.y, gaze.z); else if (gaze) { // Rotate the heading TOWARD the gaze about the local up, rather than // lerping the two vectors. A Cartesian lerp cannot cross an antipodal pair @@ -820,67 +814,34 @@ export function advanceRouteFlight(state, dt) { const turnToGaze = signedTurnRad(state.headingDir, gaze, up); // signedTurnRad is + for a RIGHT turn; a positive rotation about up is a // LEFT turn, so the step is negated. - const rotation = Cesium.Matrix3.fromQuaternion( - Cesium.Quaternion.fromAxisAngle(up, -turnToGaze * k, _headingQuat), - _headingMatrix, - ); - const turned = Cesium.Matrix3.multiplyByVector( - rotation, - state.headingDir, - _frameDir, - ); - const vertical = Cesium.Cartesian3.multiplyByScalar( + const turned = horizontalPart( + rotateAbout(state.headingDir, up, -turnToGaze * k), up, - Cesium.Cartesian3.dot(turned, up), - _chordVertical, ); - Cesium.Cartesian3.subtract(turned, vertical, turned); - if (Cesium.Cartesian3.magnitude(turned) > 1e-6) { - Cesium.Cartesian3.normalize(turned, state.headingDir); - } + if (magnitude(turned) > 1e-6) state.headingDir = normalize(turned); } // A path with no horizontal extent (identical lat/lon, differing heights) // has no azimuth to fly: point east so the frame stays orthonormal. if (!state.headingDir) { - const east = Cesium.Cartesian3.fromElements(-pos.y, pos.x, 0, _frameGaze); - state.headingDir = - Cesium.Cartesian3.magnitude(east) > 1e-6 - ? Cesium.Cartesian3.normalize(east, new Cesium.Cartesian3()) - : Cesium.Cartesian3.fromElements(1, 0, 0, new Cesium.Cartesian3()); + const east = vec(-pos.y, pos.x, 0); + state.headingDir = magnitude(east) > 1e-6 ? normalize(east) : vec(1, 0, 0); } const heading = state.headingDir; // Locked pitch: heading gives the azimuth, the pitch never wanders. - const pitch = Cesium.Math.toRadians(ROUTE_PITCH_DEG); - const direction = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.add( - Cesium.Cartesian3.multiplyByScalar(heading, Math.cos(pitch), _frameDir), - Cesium.Cartesian3.multiplyByScalar(up, Math.sin(pitch), _frameLevelUp), - _frameDir, - ), - _frameDir, + const pitch = toRadians(ROUTE_PITCH_DEG); + const direction = normalize( + add(scale(heading, Math.cos(pitch)), scale(up, Math.sin(pitch))), ); // Orthonormal camera frame, then roll it about its own forward axis: a // positive rotation drops the right wing, which is what a right turn wants. - const right = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.cross(direction, up, _frameRight), - _frameRight, - ); - const levelUp = Cesium.Cartesian3.normalize( - Cesium.Cartesian3.cross(right, direction, _frameLevelUp), - _frameLevelUp, - ); - const bankRad = Cesium.Math.toRadians(appliedBankDeg); - let bankedUp = levelUp; - if (Math.abs(bankRad) > 1e-6) { - const quat = Cesium.Quaternion.fromAxisAngle(direction, bankRad, _bankQuat); - const rotation = Cesium.Matrix3.fromQuaternion(quat, _bankMatrix); - bankedUp = Cesium.Matrix3.multiplyByVector( - rotation, - levelUp, - _frameBankedUp, - ); - } + const right = normalize(cross(direction, up)); + const levelUp = normalize(cross(right, direction)); + const bankRad = toRadians(appliedBankDeg); + const bankedUp = + Math.abs(bankRad) > 1e-6 + ? rotateAbout(levelUp, direction, bankRad) + : levelUp; // Keep the corridor ahead of the camera warm. The batch dedupes to coarse // cells, skips warm ones and queues contenders, so a repeat costs nothing. @@ -894,20 +855,14 @@ export function advanceRouteFlight(state, dt) { // the camera reaches it. Both are cached reads — nothing samples the mesh. let sampledFloor = Number.NaN; if (typeof state.floorFn === 'function') { - const aheadPos = arcPoint(state, traveled + lookaheadM / 2, _frameAheadPos); - const aheadCarto = Cesium.Cartographic.fromCartesian( - aheadPos, - Cesium.Ellipsoid.WGS84, - _frameAheadCarto, + const aheadCarto = toCartographicRadians( + arcPoint(state, traveled + lookaheadM / 2, _frameAheadPos), ); try { - const here = state.floorFn( - Cesium.Math.toDegrees(carto.latitude), - Cesium.Math.toDegrees(carto.longitude), - ); + const here = state.floorFn(toDegrees(carto.lat), toDegrees(carto.lon)); const ahead = state.floorFn( - Cesium.Math.toDegrees(aheadCarto.latitude), - Cesium.Math.toDegrees(aheadCarto.longitude), + toDegrees(aheadCarto.lat), + toDegrees(aheadCarto.lon), ); const warm = [here, ahead].filter((value) => Number.isFinite(value)); if (warm.length) sampledFloor = Math.max(...warm); @@ -971,13 +926,7 @@ export function advanceRouteFlight(state, dt) { ); } state.appliedHeightM = heightM; - const eye = Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - heightM, - Cesium.Ellipsoid.WGS84, - _frameEye, - ); + const eye = fromRadians(carto.lon, carto.lat, heightM); state.appliedBankDeg = appliedBankDeg; return { @@ -997,6 +946,8 @@ let _viewer = null; let _getTarget = null; let _active = null; // { kind, motion, direction, speed, mode, motionId, ...state } let _tickRemover = null; +/** The frame port `_tickRemover` listens to. */ +let _tickPort = null; let _trackingRemover = null; let _inputRemovers = []; /** Monotonic id for the motion currently running; 0 means "no motion". */ @@ -1006,7 +957,7 @@ let _manualInputCount = 0; /** * Lets a caller holding a motion back (behind a fly-to) see whether the user - * took the camera meanwhile; Cesium does not cancel a flight on input. + * took the camera meanwhile; the camera does not cancel a flight on input. * @returns {number} Manual camera inputs so far. */ export function manualCameraInputCount() { @@ -1024,11 +975,25 @@ function setActiveMotion(state) { if (state) { _motionSeq += 1; state.motionId = _motionSeq; + listenForFrames(); } _active = state; return state; } +/** + * Run the motions on the frames of the viewer's frame port, the one there + * is now: a renderer bound after `initCameraVerbs` (which replaces the + * port the viewer had) is picked up when the next motion starts. + */ +function listenForFrames() { + const port = _viewer ? findFrame(_viewer) : null; + if (port === _tickPort) return; + _tickRemover?.(); + _tickPort = port; + _tickRemover = port?.on('preUpdate', onTick) ?? null; +} + /** * @returns {number} Id of the running motion, or 0 when the camera is idle. */ @@ -1066,7 +1031,7 @@ let _lookBaseline = null; // in view: which way, from which position and direction. A motion that starts from that // pose turns at least that far, so a request reported as done really moves // even when a smaller first step lands in a dip of the sampled share. -const PROVEN_TURN_RAD = Cesium.Math.toRadians(0.5); +const PROVEN_TURN_RAD = toRadians(0.5); let _provenLook = null; /** The part of the frame a viewer can see: the scope keyhole when it is on. */ @@ -1074,46 +1039,44 @@ function visibleFrame() { return { keyholeRadius: isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0 }; } -/** The frame share an in-place turn from `cam`'s pose is limited against. */ -function lookBaselineShare(cam) { - const share = globeFrameShare(cam, visibleFrame()); +/** Whether two vectors agree to `tolerance` in every component. */ +const within = (a, b, tolerance) => + Math.abs(a.x - b.x) <= tolerance && + Math.abs(a.y - b.y) <= tolerance && + Math.abs(a.z - b.z) <= tolerance; + +/** The frame share an in-place turn from `pose` is limited against. */ +function lookBaselineShare(pose) { + const share = globeFrameShare(pose, visibleFrame()); const continues = _lookBaseline && - Cesium.Cartesian3.equalsEpsilon( - _lookBaseline.position, - cam.positionWC, - 0, - 1, - ) && - Cesium.Cartesian3.equalsEpsilon( - _lookBaseline.direction, - cam.directionWC, - 0, - 1e-9, - ); + within(_lookBaseline.position, pose.position, 1) && + within(_lookBaseline.direction, pose.direction, 1e-9); _lookBaseline = { - position: Cesium.Cartesian3.clone(cam.positionWC), - direction: Cesium.Cartesian3.clone(cam.directionWC), + position: pose.position, + direction: pose.direction, share: continues ? Math.max(_lookBaseline.share, share) : share, }; return _lookBaseline.share; } /** - * One in-place look step of motion `m`. From orbit a free globe camera turns - * only as far as keeps the planet in frame, measured against the baseline the - * turn started from, then the motion ends there. + * One in-place look step of motion `m` (`look`: 'up', 'down', 'left' or + * 'right'). From orbit a free globe camera turns only as far as keeps the + * planet in frame, measured against the baseline the turn started from, then + * the motion ends there. */ -function lookWithinFrame(cam, m, look, angle) { +function lookWithinFrame(camera, m, look, angle) { let allowed = angle; if (isFreeGlobeCamera(_viewer)) { + const pose = camera.pose(); if (m.globeShareAtStart === undefined) { - m.globeShareAtStart = lookBaselineShare(cam); - m.provenTurnRad = lookProven(cam, look) ? PROVEN_TURN_RAD : 0; + m.globeShareAtStart = lookBaselineShare(pose); + m.provenTurnRad = lookProven(pose, look) ? PROVEN_TURN_RAD : 0; m.turnedRad = 0; } _provenLook = null; - allowed = lookAngleWithinFrame(cam, look, angle, { + allowed = lookAngleWithinFrame(pose, look, angle, { ...visibleFrame(), startShare: m.globeShareAtStart, }); @@ -1121,45 +1084,46 @@ function lookWithinFrame(cam, m, look, angle) { if (allowed < owed) allowed = owed; m.turnedRad += allowed; } - if (allowed > 0) cam[look](allowed); + if (allowed > 0) camera.setView(eyeTurned(camera.pose(), look, allowed)); // The pose this turn leaves, for a turn that continues from it. - if (_lookBaseline) - Cesium.Cartesian3.clone(cam.directionWC, _lookBaseline.direction); + if (_lookBaseline) _lookBaseline.direction = camera.pose().direction; if (allowed < angle) interruptCameraMotion('globe-out-of-frame'); } /** * The in-place look a pitch change from `fromPitch` to `goalPitch` makes: - * 'lookUp', 'lookDown', or null when it does not move. A tilt is judged by - * the way its pitch moves, whatever form or direction word it came in. + * 'up', 'down', or null when it does not move. A tilt is judged by the way + * its pitch moves, whatever form or direction word it came in. */ function tiltLook(fromPitch, goalPitch) { if (!Number.isFinite(fromPitch) || !Number.isFinite(goalPitch)) return null; - if (goalPitch > fromPitch) return 'lookUp'; - return goalPitch < fromPitch ? 'lookDown' : null; + if (goalPitch > fromPitch) return 'up'; + return goalPitch < fromPitch ? 'down' : null; } /** Tilt `m` in place to `goalPitch`, as far as the frame limit allows. */ -function tiltInPlaceWithinFrame(cam, m, goalPitch) { - const look = tiltLook(cam.pitch, goalPitch); - if (look) lookWithinFrame(cam, m, look, Math.abs(goalPitch - cam.pitch)); +function tiltInPlaceWithinFrame(camera, m, goalPitch) { + const pitch = camera.pose().pitch; + const look = tiltLook(pitch, goalPitch); + if (look) lookWithinFrame(camera, m, look, Math.abs(goalPitch - pitch)); } /** - * The pitch an in-place tilt from `cam`'s pose toward `goalPitch` reaches - * before the frame limit stops it, judged as its steps will be: `goalPitch` - * itself when the planet stays in frame the whole way, or the camera is not a - * free globe camera. The steps run on a copy of the camera, each looking by - * the pitch still to go as the tilt's frames do, because a rolled camera's - * look turns its pitch by less than the look angle. + * The pitch an in-place tilt from the camera's pose toward `goalPitch` + * reaches before the frame limit stops it, judged as its steps will be: + * `goalPitch` itself when the planet stays in frame the whole way, or the + * camera is not a free globe camera. The steps run on a copy of the pose, each + * looking by the pitch still to go as the tilt's frames do, because a rolled + * camera's look turns its pitch by less than the look angle. */ -function tiltPitchWithinFrame(cam, goalPitch) { - const look = tiltLook(cam.pitch, goalPitch); +function tiltPitchWithinFrame(camera, goalPitch) { + const pose = camera.pose(); + const look = tiltLook(pose.pitch, goalPitch); if (!look || !isFreeGlobeCamera(_viewer)) return goalPitch; - const frame = { ...visibleFrame(), startShare: lookBaselineShare(cam) }; + const frame = { ...visibleFrame(), startShare: lookBaselineShare(pose) }; // A proven half degree is turned whatever the sampled share says. - let owed = lookProven(cam, look) ? PROVEN_TURN_RAD : 0; - const probe = Cesium.Camera.clone(cam); + let owed = lookProven(pose, look) ? PROVEN_TURN_RAD : 0; + let probe = pose; for (let i = 0; i < 32; i += 1) { if (tiltLook(probe.pitch, goalPitch) !== look) return goalPitch; const angle = Math.abs(goalPitch - probe.pitch); @@ -1169,7 +1133,7 @@ function tiltPitchWithinFrame(cam, goalPitch) { Math.min(angle, owed), ); owed -= allowed; - if (allowed > 0) probe[look](allowed); + if (allowed > 0) probe = lookedPose(probe, look, allowed); if (allowed < angle) return probe.pitch; } return probe.pitch; @@ -1177,31 +1141,22 @@ function tiltPitchWithinFrame(cam, goalPitch) { /** The reply's note for a tilt the frame limit stops short of its angle. */ function tiltFrameNote(pitch) { - return `Stopped at ${Math.round(Cesium.Math.toDegrees(pitch))}°: from this height a shallower angle would turn the globe out of view. Zoom in to tilt further.`; + return `Stopped at ${Math.round(toDegrees(pitch))}°: from this height a shallower angle would turn the globe out of view. Zoom in to tilt further.`; } -/** True when the pre-check proved a half-degree `look` from `cam`'s pose. */ -function lookProven(cam, look) { +/** True when the pre-check proved a half-degree `look` from `pose`. */ +function lookProven(pose, look) { return ( _provenLook?.look === look && - Cesium.Cartesian3.equalsEpsilon( - _provenLook.position, - cam.positionWC, - 0, - 1, - ) && - Cesium.Cartesian3.equalsEpsilon( - _provenLook.direction, - cam.directionWC, - 0, - 1e-9, - ) + pose != null && + within(_provenLook.position, pose.position, 1) && + within(_provenLook.direction, pose.direction, 1e-9) ); } /** - * The check a voice in-place turn (`look`: 'lookUp', 'lookDown', 'lookLeft' - * or 'lookRight') must pass from orbit: refused when even half a degree would + * The check a voice in-place turn (`look`: 'up', 'down', 'left' or 'right') + * must pass from orbit: refused when even half a degree would * cross the frame limit, otherwise proven for that half degree from this pose. * With `released`, the turn runs through a navigation that first releases a * tracked or locked camera and keeps its world pose. The frame measure and the @@ -1212,13 +1167,13 @@ function lookProven(cam, look) { */ function checkLookFromOrbit(look, { released = false } = {}) { _provenLook = null; - if (_viewer.scene.mode !== Cesium.SceneMode.SCENE3D) return null; - const cam = _viewer.camera; if (!released && !isFreeGlobeCamera(_viewer)) return null; + const pose = findCamera(_viewer)?.pose(); + if (!pose) return null; if ( - lookStepLosesGlobe(cam, look, PROVEN_TURN_RAD, { + lookStepLosesGlobe(pose, look, PROVEN_TURN_RAD, { ...visibleFrame(), - startShare: lookBaselineShare(cam), + startShare: lookBaselineShare(pose), }) ) return { @@ -1229,15 +1184,15 @@ function checkLookFromOrbit(look, { released = false } = {}) { }; _provenLook = { look, - position: Cesium.Cartesian3.clone(cam.positionWC), - direction: Cesium.Cartesian3.clone(cam.directionWC), + position: pose.position, + direction: pose.direction, }; return null; } function clearLookAt() { try { - _viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); + findCamera(_viewer)?.release(); } catch { /* teardown race */ } @@ -1246,7 +1201,7 @@ function clearLookAt() { /** * Put the horizon back. * - * The route dolly is the only motion that rolls the camera, and Cesium keeps + * The route dolly is the only motion that rolls the camera, and the camera keeps * whatever world-space up vector it was last handed — so releasing a flight * mid-bank leaves the user holding a tilted horizon until some later motion * happens to level it. Heading, pitch and position are preserved; only the @@ -1255,13 +1210,11 @@ function clearLookAt() { */ function levelCameraRoll() { try { - const cam = _viewer?.camera; - if (!cam || typeof cam.setView !== 'function') return false; - const roll = Cesium.Math.negativePiToPi(cam.roll || 0); - if (Math.abs(roll) < 1e-5) return false; - cam.setView({ - orientation: { heading: cam.heading, pitch: cam.pitch, roll: 0 }, - }); + const camera = findCamera(_viewer); + if (!camera) return false; + const { heading, pitch, roll } = camera.pose(); + if (Math.abs(negativePiToPi(roll || 0)) < 1e-5) return false; + camera.setView({ orientation: { heading, pitch, roll: 0 } }); return true; } catch { return false; // teardown race @@ -1274,7 +1227,7 @@ export function interruptCameraMotion(reason = 'interrupt') { // While an entity is TRACKED, the follow camera owns the reference frame — // resetting the lookAt transform here flings the camera into space (field // finding). Leave the transform to the tracker; it re-asserts every frame. - const tracking = Boolean(_viewer?.trackedEntity); + const tracking = isFollowing(_viewer); const wasRoute = wasActive && _active.kind === 'route'; if ( wasActive && @@ -1316,6 +1269,9 @@ export function getActiveCameraMotion() { return info; } +/** A pan's direction as the camera move it makes; any other is down. */ +const PAN_MOVES = Object.freeze({ left: 'left', right: 'right', up: 'up' }); + function onTick() { if (!_active || !_viewer) return; // Wall-clock dt: clock.currentTime FREEZES when the app clock isn't @@ -1326,7 +1282,6 @@ function onTick() { Math.max(0.001, (nowMs - (_active.lastMs ?? nowMs)) / 1000), ); _active.lastMs = nowMs; - const cam = _viewer.camera; const m = _active; // `once` motions ease out and self-stop on budget exhaustion. @@ -1341,6 +1296,7 @@ function onTick() { } try { + const camera = cameraOf(_viewer); if (m.kind === 'orbit' && m.pending) { // Armed but target-less (started mid-flight, e.g. "fly to X and orbit // it"): keep trying for a ground target until the camera settles. @@ -1350,11 +1306,11 @@ function onTick() { return; } // pickEllipsoid hits the globe from ANY altitude — target existence - // alone is not arrival. Camera flights are scene tweens, and multi-stage - // flights have GAPS between tweens: require the tween queue quiet for a + // alone is not arrival. Multi-stage flights have GAPS between flights: + // require the camera out of any flight for a // continuous 0.8 s before capturing the orbit framing at the REAL // destination (field finding: Eiffel chain orbited from mid-flight). - if (_viewer.scene.tweens.length > 0) { + if (cameraFlying()) { m.settledS = 0; return; } @@ -1362,86 +1318,74 @@ function onTick() { if (m.settledS < 0.8) return; const target = _getTarget?.(_viewer); if (!target) return; - const cam2 = _viewer.camera; - const range = Cesium.Cartesian3.distance(cam2.positionWC, target); - const carto2 = Cesium.Cartographic.fromCartesian(cam2.positionWC); - const tCarto2 = Cesium.Cartographic.fromCartesian(target); - const dh2 = carto2.height - tCarto2.height; + const pose = camera.pose(); m.target = target; - m.hpr = new Cesium.HeadingPitchRange( - cam2.heading, - -Math.asin(Math.min(1, Math.max(-1, dh2 / Math.max(1, range)))), - range, - ); - m.hprStartHeading = cam2.heading; + m.hpr = orbitFraming(pose, target); + m.hprStartHeading = pose.heading; m.pending = false; m.elapsed = 0; // once-mode budget starts when the orbit actually begins return; } if (m.kind === 'orbit') { const rate = - Cesium.Math.toRadians(ORBIT_DEG_S[m.speed]) * - (m.direction === 'left' ? -1 : 1); + toRadians(ORBIT_DEG_S[m.speed]) * (m.direction === 'left' ? -1 : 1); if (m.mode === 'once') { const total = - Cesium.Math.toRadians(ONCE.orbitDeg) * - (m.direction === 'left' ? -1 : 1); + toRadians(ONCE.orbitDeg) * (m.direction === 'left' ? -1 : 1); m.hpr.heading = m.hprStartHeading + total * scale; } else { m.hpr.heading += rate * dt; } - cam.lookAt(m.target, m.hpr); + camera.lookAt(m.target, m.hpr); } else if (m.kind === 'pan') { - const heightM = Math.max(50, cam.positionCartographic.height); + const heightM = Math.max(50, camera.pose().height); const step = m.mode === 'once' ? heightM * ONCE.panViewFraction * (scale - (m.lastScale || 0)) : heightM * PAN_VIEW_FRACTION_S[m.speed] * dt; m.lastScale = scale; - if (m.direction === 'left') cam.moveLeft(step); - else if (m.direction === 'right') cam.moveRight(step); - else if (m.direction === 'up') cam.moveUp(step); - else cam.moveDown(step); + camera.setView( + eyeMoved(camera.pose(), PAN_MOVES[m.direction] ?? 'down', step), + ); } else if (m.kind === 'tilt') { - tickTilt(cam, m, scale, dt); + tickTilt(camera, m, scale, dt); } else if (m.kind === 'rotate' || m.kind === 'rotate_globe') { const degS = TILT_DEG_S[m.speed]; const stepRad = m.mode === 'once' - ? Cesium.Math.toRadians(ONCE.rotateDeg) * (scale - (m.lastScale || 0)) - : Cesium.Math.toRadians(degS) * dt; + ? toRadians(ONCE.rotateDeg) * (scale - (m.lastScale || 0)) + : toRadians(degS) * dt; m.lastScale = scale; if (m.kind === 'rotate_globe') { // Tracking can acquire the camera without going through navigation. // Yield without resetting its pose/frame: the world-space arc proof - // only describes Cesium's rotation while the frame is identity. + // only describes the camera's rotation while the frame is identity. + const pose = camera.pose(); if (!isFreeGlobeCamera(_viewer) || _isCockpitActive?.()) { interruptCameraMotion('globe-camera-owner-changed'); return; } - // Cesium rotates both position and basis about the reference-frame + // The camera rotates both position and basis about the reference-frame // origin. The captured screen-up axis keeps left/right horizontal even // in a tilted or rolled view; a positive angle moves the globe right. const angle = m.direction === 'left' ? -stepRad : stepRad; - if (globeRotationFitsKeyhole() !== true) { + if (globeRotationFitsKeyhole(liveView(camera, pose)) !== true) { interruptCameraMotion('globe-framing-changed'); return; } if ( - !globeRotationHasClearance(cam.positionWC) || - Math.abs( - Cesium.Cartesian3.magnitude(cam.positionWC) - m.rotationRadius, - ) > 0.01 + !globeRotationHasClearance(pose.position) || + Math.abs(magnitude(pose.position) - m.rotationRadius) > 0.01 ) { interruptCameraMotion('globe-surface-limit'); return; } - cam.rotate(m.rotationAxis, angle); + camera.setView(eyeRotatedAbout(pose, m.rotationAxis, angle)); } else { lookWithinFrame( - cam, + camera, m, - m.direction === 'left' ? 'lookLeft' : 'lookRight', + m.direction === 'left' ? 'left' : 'right', stepRad, ); } @@ -1453,7 +1397,7 @@ function onTick() { // user left it rather than teleporting to an altitude derived from // nothing. An interrupt during the arm is still instant. if (frame.arming) return; - cam.setView({ + camera.setView({ destination: frame.eye, orientation: { direction: frame.direction, up: frame.up }, }); @@ -1467,6 +1411,25 @@ function onTick() { } } +/** Whether the camera is in a flight. */ +const cameraFlying = () => Boolean(findCamera(_viewer)?.flying); + +/** + * An orbit offset that reproduces the current framing of `target` exactly: + * the view's heading, and pitch and range from the geometry. + */ +function orbitFraming(pose, target) { + const range = distance(pose.position, target); + const dh = + toCartographicRadians(pose.position).height - + toCartographicRadians(target).height; + return { + heading: pose.heading, + pitch: -Math.asin(Math.min(1, Math.max(-1, dh / Math.max(1, range)))), + range, + }; +} + /** * One frame of tilt. With a ground pivot the camera swings about it (lookAt), * so the place under the crosshair stays centred; without one it looks up or @@ -1481,15 +1444,14 @@ function onTick() { * keeps the place centred: tilting in place there would lift the crosshair * onto the sky. */ -function tickTilt(cam, m, scale, dt) { - const from = cam.pitch; +function tickTilt(camera, m, scale, dt) { + const pitchNow = () => camera.pose().pitch; + const from = pitchNow(); const want = m.mode === 'once' ? m.startPitch + (m.goalPitch - m.startPitch) * scale : from + - Cesium.Math.toRadians(TILT_DEG_S[m.speed]) * - dt * - (m.direction === 'up' ? 1 : -1); + toRadians(TILT_DEG_S[m.speed]) * dt * (m.direction === 'up' ? 1 : -1); const up = want > from; const limited = up ? Math.min(want, Math.max(from, PITCH_MAX)) @@ -1498,25 +1460,25 @@ function tickTilt(cam, m, scale, dt) { if (m.hpr) { // Apply a range a zoom set since the last frame, even when the pitch // then has nowhere to go (a zoom in to the clearance ends the pivot). - cam.lookAt(m.target, m.hpr); + camera.lookAt(m.target, m.hpr); // Up toward the horizon the swing lowers the camera: hold the clearance, // and keep the place below the horizon. const cap = up ? Math.max(m.hpr.pitch, tiltPivotPitchMax(m.hpr.range)) : Infinity; - for (let i = 0; i < 3 && Math.abs(limited - cam.pitch) > 1e-6; i += 1) { + for (let i = 0; i < 3 && Math.abs(limited - pitchNow()) > 1e-6; i += 1) { const pitch = Math.min( cap, - Math.max(-Cesium.Math.PI_OVER_TWO, m.hpr.pitch + limited - cam.pitch), + Math.max(-PI_OVER_TWO, m.hpr.pitch + limited - pitchNow()), ); if (pitch === m.hpr.pitch) break; m.hpr.pitch = pitch; - cam.lookAt(m.target, m.hpr); + camera.lookAt(m.target, m.hpr); } // A once motion that just completed released the lookAt frame before // this last step re-took it. if (_active !== m) clearLookAt(); - if (up && m.hpr.pitch >= cap && cam.pitch < limited - 1e-6) { + if (up && m.hpr.pitch >= cap && pitchNow() < limited - 1e-6) { if (tiltClearanceBinds(m.hpr.range)) { // Down to its clearance: let go of the pivot and tilt the rest in // place, which keeps the height. @@ -1529,7 +1491,7 @@ function tickTilt(cam, m, scale, dt) { } } } - if (!m.hpr) tiltInPlaceWithinFrame(cam, m, limited); + if (!m.hpr) tiltInPlaceWithinFrame(camera, m, limited); if (m.mode !== 'once' && (limited !== want || atLimit)) interruptCameraMotion('tilt-clamp'); } @@ -1580,36 +1542,27 @@ function tiltUpLimit({ target, pivot }) { /** The camera pitch lookAt gives for this pivot at the given pivot pitch. */ function pivotCameraPitch(target, { heading, range }, pitch) { - const offset = new Cesium.Cartesian3( - -range * Math.cos(pitch) * Math.sin(heading), - -range * Math.cos(pitch) * Math.cos(heading), - -range * Math.sin(pitch), - ); - const eye = Cesium.Matrix4.multiplyByPoint( - Cesium.Transforms.eastNorthUpToFixedFrame(target), - offset, - new Cesium.Cartesian3(), - ); - const look = Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()); - Cesium.Cartesian3.normalize(look, look); - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - const upAtEye = ellipsoid.geodeticSurfaceNormal(eye, new Cesium.Cartesian3()); - return Math.asin( - Cesium.Math.clamp(Cesium.Cartesian3.dot(look, upAtEye), -1, 1), - ); + const eye = framePoint(eastNorthUp(target), { + x: -range * Math.cos(pitch) * Math.sin(heading), + y: -range * Math.cos(pitch) * Math.cos(heading), + z: -range * Math.sin(pitch), + }); + const look = normalize(sub(target, eye)); + return Math.asin(clamp(dot(look, geodeticSurfaceNormal(eye)), -1, 1)); } /** * Where a tilt starts. It swings about the ground under the crosshair so the * place stays centred. It tilts in place with no ground there, from globe - * range, or while an entity is tracked (the follow camera owns that frame; + * range, or while something is followed (the follow camera owns that frame; * voice releases it before moving, so a voice tilt still pivots). */ -function tiltStartFrame(cam) { - const target = _viewer.trackedEntity ? null : _getTarget?.(_viewer); - let pivot = target ? tiltPivot(cam, target) : null; +function tiltStartFrame(camera) { + const pose = camera.pose(); + const target = isFollowing(_viewer) ? null : _getTarget?.(_viewer); + let pivot = target ? tiltPivot(pose, target) : null; if (pivot && !tiltPivotInReach(pivot.range)) pivot = null; - return { target, pivot, from: cam.pitch }; + return { target, pivot, from: pose.pitch }; } /** Whether a tilt may pivot at this range: up to and including the cutoff. */ @@ -1619,87 +1572,84 @@ function tiltPivotInReach(range) { /** The reply's note for a tilt the place's horizon stops short of its angle. */ function tiltHorizonNote(pitch) { - return `Stopped at ${Math.round(Cesium.Math.toDegrees(pitch))}°: from this range a shallower angle puts the place past the horizon. Zoom in to tilt further.`; + return `Stopped at ${Math.round(toDegrees(pitch))}°: from this range a shallower angle puts the place past the horizon. Zoom in to tilt further.`; } /** Ground pivot for a tilt: heading, pitch and range in the target's own frame. */ -function tiltPivot(cam, target) { - const local = Cesium.Matrix4.multiplyByPoint( - Cesium.Matrix4.inverseTransformation( - Cesium.Transforms.eastNorthUpToFixedFrame(target), - new Cesium.Matrix4(), - ), - cam.positionWC, - new Cesium.Cartesian3(), - ); - const range = Cesium.Cartesian3.magnitude(local); +function tiltPivot(pose, target) { + const local = inverseFramePoint(eastNorthUp(target), pose.position); + const range = magnitude(local); if (!(range > 1) || local.z <= 0) return null; // Near straight overhead the offset's heading is float noise (it flipped a // north-up London view to south); keep the camera's own. const heading = Math.hypot(local.x, local.y) > range * 0.01 ? Math.atan2(-local.x, -local.y) - : cam.heading; - return new Cesium.HeadingPitchRange( + : pose.heading; + return { heading, - -Math.asin(Math.min(1, local.z / range)), + pitch: -Math.asin(Math.min(1, local.z / range)), range, - ); + }; } -/** Rigid origin-centred rotation stays outside the actual ellipsoid's bounding sphere. */ +/** Rigid origin-centred rotation stays outside the ellipsoid's bounding sphere. */ function globeRotationHasClearance(position) { - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - const { minimumRadius, maximumRadius } = ellipsoid; - const radius = Cesium.Cartesian3.magnitude(position); - return ( - Number.isFinite(minimumRadius) && - minimumRadius > 0 && - Number.isFinite(maximumRadius) && - maximumRadius >= minimumRadius && - Number.isFinite(radius) && - radius > maximumRadius * (1 + 1e-12) - ); + const radius = magnitude(position); + return Number.isFinite(radius) && radius > WGS84.radii.x * (1 + 1e-12); } +/** + * The camera's view for the keyhole test: its pose, its projection, and + * whether it is the live camera (whose Earth disc the overlay projects). + */ +function liveView(camera, pose = camera.pose()) { + let projection = null; + try { + projection = camera.matrices().projection; + } catch { + /* no projection for these depth limits: unsupported below */ + } + return { ...pose, projection, live: true }; +} + +/** + * Whether a projection is a perspective one centred on the view: what the + * keyhole cone below assumes. Column-major, so element 11 is row 3 of + * column 2 (−1 for a perspective divide), 15 row 3 of column 3 (0), and 8 + * and 9 the off-centre shifts. + */ +const centredPerspective = (p) => + p?.[11] === -1 && p[15] === 0 && p[8] === 0 && p[9] === 0; + /** Use the existing WGS84/CSS-pixel projection; null means unsupported, not close-up. */ -function globeRotationFitsKeyhole(camera = _viewer.camera) { - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - if (!Cesium.Cartesian3.equals(ellipsoid.radii, Cesium.Ellipsoid.WGS84.radii)) - return null; - const canvas = _viewer.scene.canvas; +function globeRotationFitsKeyhole(view) { + const canvas = canvasOf(_viewer); const width = canvas.clientWidth; const height = canvas.clientHeight; - const frustum = camera.frustum; if ( !Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0 || - !(frustum instanceof Cesium.PerspectiveFrustum) || - !Number.isFinite(frustum.near) || - frustum.near <= 0 || - !Number.isFinite(frustum.far) || - frustum.far <= frustum.near || - frustum.xOffset !== 0 || - frustum.yOffset !== 0 + !centredPerspective(view.projection) || + !Number.isFinite(view.near) || + view.near <= 0 || + !Number.isFinite(view.far) || + view.far <= view.near ) return null; try { - const cam = camera; - const distance = Cesium.Cartesian3.magnitude(cam.positionWC); - const sphereRadius = ellipsoid.maximumRadius; - if (!Number.isFinite(distance) || distance <= 0) return null; - if (distance <= sphereRadius) return false; // Near-surface polar views are close-up too. - const radiusPx = earthDiscScreenRadius(distance, height, frustum.fovy); + const distanceM = magnitude(view.position); + const sphereRadius = WGS84.radii.x; + if (!Number.isFinite(distanceM) || distanceM <= 0) return null; + if (distanceM <= sphereRadius) return false; // Near-surface polar views are close-up too. + const radiusPx = earthDiscScreenRadius(distanceM, height, view.fovy); if (!radiusPx) return null; const keyhole = getKeyholeGeometry(width, height); // The known nadir reset probe uses the same exact cone below; projecting - // through SceneTransforms would read the live scene.camera instead. - if ( - camera === _viewer.camera && - !projectEarthDiscToViewport(_viewer, width, height) - ) { + // through the query port would read the live camera instead. + if (view.live && !projectEarthDiscToViewport(_viewer, width, height)) { // A near-surface horizon view cannot fit even when pointed at Earth; // an orbital camera looking away is unsupported, not a close-up offer. return radiusPx > Math.min(keyhole.radius, width / 2, height / 2) @@ -1710,33 +1660,26 @@ function globeRotationFitsKeyhole(camera = _viewer.camera) { // against the existing keyhole cone. Canvas-edge clipping does not change // framing during rigid globe rotation and is not a clearance condition, // without changing the UI projection or defining another keyhole/mask. - const toCenter = Cesium.Cartesian3.negate( - cam.positionWC, - new Cesium.Cartesian3(), - ); - const depth = Cesium.Cartesian3.dot(toCenter, cam.directionWC); - const right = Math.abs(Cesium.Cartesian3.dot(toCenter, cam.rightWC)); - const up = Math.abs(Cesium.Cartesian3.dot(toCenter, cam.upWC)); - const focalY = height / (2 * Math.tan(frustum.fovy / 2)); - const focalX = - width / (2 * Math.tan(frustum.fovy / 2) * frustum.aspectRatio); + const toCenter = vec(-view.position.x, -view.position.y, -view.position.z); + const depth = dot(toCenter, view.direction); + const right = Math.abs(dot(toCenter, view.right)); + const up = Math.abs(dot(toCenter, view.up)); + const focalY = height / (2 * Math.tan(view.fovy / 2)); + const focalX = width / (2 * Math.tan(view.fovy / 2) * view.aspectRatio); if ( ![depth, right, up, focalX, focalY].every(Number.isFinite) || focalX <= 0 || focalY <= 0 ) return null; - const halfAngle = Math.asin(sphereRadius / distance); + const halfAngle = Math.asin(sphereRadius / distanceM); const centerAngle = Math.atan2(Math.hypot(right, up), depth); const keyholeAngle = Math.atan(keyhole.radius / Math.max(focalX, focalY)); // No overlay visibility hysteresis: a fully contained smaller globe needs no reset. const framed = centerAngle + halfAngle <= keyholeAngle; if (!framed) return false; // Projection alone does not prove that a tiny globe is within depth planes. - if ( - depth - sphereRadius < frustum.near || - depth + sphereRadius > frustum.far - ) + if (depth - sphereRadius < view.near || depth + sphereRadius > view.far) return null; return true; } catch { @@ -1744,25 +1687,36 @@ function globeRotationFitsKeyhole(camera = _viewer.camera) { } } -/** Check the unchanged reset destination without moving the live camera. */ +/** + * Check the unchanged reset destination without moving the live camera: the + * view the Globe View preset sets above the current point, with the live + * camera's projection. Its axes are the camera convention's: heading, + * pitch and roll in the east-north-up frame, the view along the frame's x + * once heading is turned a quarter back. + */ function globeResetFitsKeyhole() { try { - const camera = Cesium.Camera.clone(_viewer.camera); - const { longitude, latitude } = _viewer.camera.positionCartographic; - camera.setView({ - destination: Cesium.Cartesian3.fromRadians( - longitude, - latitude, - GLOBE_VIEW.heightM, - ), - orientation: { - heading: 0, - pitch: Cesium.Math.toRadians(GLOBE_VIEW.pitchDeg), - roll: 0, - }, - endTransform: Cesium.Matrix4.IDENTITY, + const camera = cameraOf(_viewer); + const pose = camera.pose(); + const here = toCartographicRadians(pose.position); + const position = fromRadians(here.lon, here.lat, GLOBE_VIEW.heightM); + const axes = headingPitchRollFrame(position, { + heading: 0 - Math.PI / 2, + pitch: toRadians(GLOBE_VIEW.pitchDeg), + roll: 0, }); - return globeRotationFitsKeyhole(camera) === true; + const direction = axes.x; + const up = axes.z; + return ( + globeRotationFitsKeyhole({ + ...liveView(camera, pose), + live: false, + position, + direction, + up, + right: cross(direction, up), + }) === true + ); } catch { return false; } @@ -1809,21 +1763,20 @@ export function initCameraVerbs( typeof isCockpitActive === 'function' ? isCockpitActive : null; _viewer = viewer; _lookBaseline = null; - if (_tickRemover) _tickRemover(); - _tickRemover = viewer.clock.onTick.addEventListener(onTick); + listenForFrames(); if (_trackingRemover) _trackingRemover(); // Cockpit can acquire then clear tracking before the next clock tick. // Yield on acquisition itself without changing legacy camera motions. - _trackingRemover = viewer.trackedEntityChanged?.addEventListener((entity) => { - if (entity && _active?.kind === 'rotate_globe') + _trackingRemover = onFollowChanged(viewer, (followed) => { + if (followed && _active?.kind === 'rotate_globe') interruptCameraMotion('globe-camera-owner-changed'); // A pivoting tilt's lookAt would fight the follow camera every frame. - else if (entity && _active?.kind === 'tilt' && _active.hpr) + else if (followed && _active?.kind === 'tilt' && _active.hpr) interruptCameraMotion('tilt-camera-owner-changed'); }); for (const rm of _inputRemovers) rm(); _inputRemovers = []; - const canvas = viewer.scene.canvas; + const canvas = canvasOf(viewer); // ANY manual camera input reclaims control — the cancelFlight reflex. for (const evt of ['pointerdown', 'touchstart', 'wheel']) { const h = () => { @@ -1850,14 +1803,8 @@ function requestedTiltPitch(args, direction) { // The camera never looks above the horizon, so a positive angle can only // mean the same angle below it ("tilt 45 degrees" sent as 45). if (Number.isFinite(requested)) - return Cesium.Math.clamp( - Cesium.Math.toRadians(-Math.abs(requested)), - PITCH_MIN, - PITCH_MAX, - ); - return direction === null - ? Cesium.Math.toRadians(TILT_DEFAULT_PITCH_DEG) - : null; + return clamp(toRadians(-Math.abs(requested)), PITCH_MIN, PITCH_MAX); + return direction === null ? toRadians(TILT_DEFAULT_PITCH_DEG) : null; } /** @@ -1958,14 +1905,11 @@ export function moveCamera(args = {}, runNavigation = null) { if (motion === 'tilt' && tiltToPitch !== null) { // Angles and limits are the camera's own pitch, whatever the swing pivots // about; releasing the follow camera does not change it. - const from = _viewer.camera.pitch; + const from = cameraOf(_viewer).pose().pitch; // -89 or -90 means top-down, which a -90° view already is: the clamp // must not tilt it up 1°. const atTopDown = tiltToPitch <= PITCH_MIN && from <= PITCH_MIN; - if ( - atTopDown || - Math.abs(tiltToPitch - from) < Cesium.Math.toRadians(0.5) - ) { + if (atTopDown || Math.abs(tiltToPitch - from) < toRadians(0.5)) { // Still a camera request: it stops a running motion and releases the // follow camera, as a tilt that moves would. const hold = () => { @@ -1974,9 +1918,7 @@ export function moveCamera(args = {}, runNavigation = null) { ok: true, action: 'move_camera', motion, - pitchDeg: Math.round( - Cesium.Math.toDegrees(atTopDown ? from : tiltToPitch), - ), + pitchDeg: Math.round(toDegrees(atTopDown ? from : tiltToPitch)), unchanged: true, }; }; @@ -1986,8 +1928,8 @@ export function moveCamera(args = {}, runNavigation = null) { // as {direction:'down', pitchDeg:10} would tilt up from -45°. const towards = tiltToPitch > from ? 'up' : 'down'; if ((direction === 'up' || direction === 'down') && direction !== towards) { - const target = Math.round(Cesium.Math.toDegrees(tiltToPitch)); - const now = Math.round(Cesium.Math.toDegrees(from)); + const target = Math.round(toDegrees(tiltToPitch)); + const now = Math.round(toDegrees(from)); return { ok: false, action: 'move_camera', @@ -1996,25 +1938,20 @@ export function moveCamera(args = {}, runNavigation = null) { } if ( towards === 'up' && - from >= - tiltUpLimit(tiltStartFrame(_viewer.camera)) - Cesium.Math.toRadians(0.5) + from >= tiltUpLimit(tiltStartFrame(cameraOf(_viewer))) - toRadians(0.5) ) return tiltUpLimitRefusal(); } else if (motion === 'tilt') { // Honest limits: at the clamp a tilt is a no-op — say so instead of // reporting success and letting the model gaslight itself (field test). - const pitch = _viewer.camera.pitch; + const pitch = cameraOf(_viewer).pose().pitch; if ( direction === 'up' && - pitch >= - tiltUpLimit(tiltStartFrame(_viewer.camera)) - Cesium.Math.toRadians(0.5) + pitch >= tiltUpLimit(tiltStartFrame(cameraOf(_viewer))) - toRadians(0.5) ) { return tiltUpLimitRefusal(); } - if ( - direction === 'down' && - pitch <= PITCH_MIN + Cesium.Math.toRadians(0.5) - ) { + if (direction === 'down' && pitch <= PITCH_MIN + toRadians(0.5)) { return { ok: false, action: 'move_camera', @@ -2027,16 +1964,15 @@ export function moveCamera(args = {}, runNavigation = null) { const look = motion === 'tilt' ? tiltLook( - _viewer.camera.pitch, + cameraOf(_viewer).pose().pitch, tiltToPitch ?? - _viewer.camera.pitch + - Cesium.Math.toRadians(ONCE.tiltDeg) * - (direction === 'up' ? 1 : -1), + cameraOf(_viewer).pose().pitch + + toRadians(ONCE.tiltDeg) * (direction === 'up' ? 1 : -1), ) : motion === 'rotate' ? direction === 'left' - ? 'lookLeft' - : 'lookRight' + ? 'left' + : 'right' : null; // Honest limits from orbit too: a stopped turn rests within 0.05° of its // limit, so one that cannot go half a degree further is refused rather than @@ -2053,15 +1989,14 @@ export function moveCamera(args = {}, runNavigation = null) { if ( (motion === 'rotate_globe' || (motion === 'orbit' && typeof runNavigation !== 'function')) && - _viewer?.trackedEntity + isFollowing(_viewer) ) { // The follow camera owns a tracked view; a lookAt orbit fights it frame // by frame and stop rips the camera out (field finding). Honest refusal // until tracked-orbit rides the follow camera natively (roadmap). + const followed = followedOf(_viewer); const label = - _viewer.trackedEntity?.name || - _viewer.trackedEntity?.id || - 'the tracked target'; + followed?.name || followed?.labelModel?.title || 'the tracked target'; return { ok: false, action: 'move_camera', @@ -2070,19 +2005,23 @@ export function moveCamera(args = {}, runNavigation = null) { } let globePose; if (motion === 'rotate_globe') { - if (_viewer.scene.mode !== Cesium.SceneMode.SCENE3D) { + const camera = cameraOf(_viewer); + let pose; + try { + pose = camera.pose(); + } catch { + // A frustum the camera cannot describe (depth limits out of order). return { ok: false, action: 'move_camera', - error: 'Globe rotation requires a 3D view.', + reason: 'unsupported-view', + error: 'Globe rotation requires a supported perspective view.', }; } - const cam = _viewer.camera; globePose = { - position: Cesium.Cartesian3.clone(cam.positionWC), - direction: Cesium.Cartesian3.clone(cam.directionWC), - up: Cesium.Cartesian3.normalize(cam.upWC, new Cesium.Cartesian3()), - right: Cesium.Cartesian3.clone(cam.rightWC), + position: vec(pose.position.x, pose.position.y, pose.position.z), + direction: vec(pose.direction.x, pose.direction.y, pose.direction.z), + up: normalize(pose.up), }; if (_isCockpitActive?.()) return { @@ -2091,14 +2030,7 @@ export function moveCamera(args = {}, runNavigation = null) { reason: 'camera-owned', error: 'Exit Cockpit before rotating the globe.', }; - const ellipsoid = _viewer.scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84; - if (!( - Number.isFinite(ellipsoid.minimumRadius) && - ellipsoid.minimumRadius > 0 && - Number.isFinite(ellipsoid.maximumRadius) && - ellipsoid.maximumRadius >= ellipsoid.minimumRadius && - Number.isFinite(Cesium.Cartesian3.magnitude(globePose.position)) - )) + if (!Number.isFinite(magnitude(globePose.position))) return { ok: false, action: 'move_camera', @@ -2106,7 +2038,7 @@ export function moveCamera(args = {}, runNavigation = null) { error: 'Globe rotation requires a finite supported ellipsoid and a clear globe view.', }; - const fits = globeRotationFitsKeyhole(); + const fits = globeRotationFitsKeyhole(liveView(camera, pose)); if (fits === null) return { ok: false, @@ -2140,7 +2072,7 @@ export function moveCamera(args = {}, runNavigation = null) { interruptCameraMotion('replaced'); // Checked again only if the release left the camera somewhere other than // where the check above expected it. - if (look && !lookProven(_viewer.camera, look)) { + if (look && !lookProven(findCamera(_viewer)?.pose(), look)) { const refusal = checkLookFromOrbit(look); if (refusal) return refusal; } @@ -2151,7 +2083,7 @@ export function moveCamera(args = {}, runNavigation = null) { mode, }; if (motion === 'tilt') { - const frame = tiltStartFrame(_viewer.camera); + const frame = tiltStartFrame(cameraOf(_viewer)); const { target, pivot, from } = frame; if (pivot) { state.target = target; @@ -2170,7 +2102,7 @@ export function moveCamera(args = {}, runNavigation = null) { // From orbit an in-place tilt stops where the planet would leave the // frame: aim it there, and say so. if (!pivot) { - const framed = tiltPitchWithinFrame(_viewer.camera, goal); + const framed = tiltPitchWithinFrame(cameraOf(_viewer), goal); if (framed !== goal) { goal = framed; stopNote = tiltFrameNote(goal); @@ -2184,13 +2116,12 @@ export function moveCamera(args = {}, runNavigation = null) { state.askedPitch = tiltToPitch; state.durationS = Math.max( ONCE.durationS, - Math.abs(Cesium.Math.toDegrees(goal - from)) / TILT_TO_DEG_S, + Math.abs(toDegrees(goal - from)) / TILT_TO_DEG_S, ); if (goal !== tiltToPitch) stoppedAt = goal; } else { // A nudge stops at the limit it travels toward. - const step = - Cesium.Math.toRadians(ONCE.tiltDeg) * (direction === 'up' ? 1 : -1); + const step = toRadians(ONCE.tiltDeg) * (direction === 'up' ? 1 : -1); state.goalPitch = step > 0 ? Math.min(from + step, Math.max(from, upLimit)) @@ -2200,21 +2131,28 @@ export function moveCamera(args = {}, runNavigation = null) { if (motion === 'rotate_globe') { // Convert an inherited ground-target frame without changing the world // pose. Rotation must pivot about Earth, never the previous local target. - const cam = _viewer.camera; - cam.cancelFlight(); - cam.lookAtTransform(Cesium.Matrix4.IDENTITY); - // Handoff may level a route's bank. Keep the caller's exact world pose. - // Copy the basis directly: setView's heading/pitch conversion is singular - // at nadir and can change the captured orientation near the poles. - Cesium.Cartesian3.clone(globePose.position, cam.position); - Cesium.Cartesian3.clone(globePose.direction, cam.direction); - Cesium.Cartesian3.clone(globePose.up, cam.up); - Cesium.Cartesian3.clone(globePose.right, cam.right); + const camera = cameraOf(_viewer); + camera.cancelFlight(); + camera.release(); + // Handoff may level a route's bank. Keep the caller's world pose, but + // write it only when the handoff changed it: a heading and pitch + // conversion inside the camera is singular at nadir, so an unchanged + // pose is left exactly as it is. + const now = camera.pose(); + if ( + distance(now.position, globePose.position) > 1e-6 || + distance(now.direction, globePose.direction) > 1e-9 || + distance(normalize(now.up), globePose.up) > 1e-9 + ) + camera.setView({ + destination: globePose.position, + orientation: { direction: globePose.direction, up: globePose.up }, + }); state.rotationAxis = globePose.up; - state.rotationRadius = Cesium.Cartesian3.magnitude(globePose.position); + state.rotationRadius = magnitude(globePose.position); } if (motion === 'orbit') { - if (_viewer.scene.tweens.length > 0) { + if (cameraFlying()) { // A camera flight is in progress — ALWAYS arm and capture at the // destination; a target existing right now is meaningless (the globe // is always under the crosshair). The voice runner already holds an @@ -2260,18 +2198,11 @@ export function moveCamera(args = {}, runNavigation = null) { armed: 'waiting-for-arrival', }; } - const cam = _viewer.camera; - const range = Cesium.Cartesian3.distance(cam.positionWC, target); // Pitch from geometry so lookAt reproduces the CURRENT framing exactly. - const carto = Cesium.Cartographic.fromCartesian(cam.positionWC); - const tCarto = Cesium.Cartographic.fromCartesian(target); - const dh = carto.height - tCarto.height; - const pitch = -Math.asin( - Math.min(1, Math.max(-1, dh / Math.max(1, range))), - ); + const pose = cameraOf(_viewer).pose(); state.target = target; - state.hpr = new Cesium.HeadingPitchRange(cam.heading, pitch, range); - state.hprStartHeading = cam.heading; + state.hpr = orbitFraming(pose, target); + state.hprStartHeading = pose.heading; } setActiveMotion(state); // Verb motion drives the camera per clock tick — hold until interrupted; @@ -2285,15 +2216,13 @@ export function moveCamera(args = {}, runNavigation = null) { speed, mode: state.mode, ...(tiltToPitch !== null && { - pitchDeg: Math.round(Cesium.Math.toDegrees(stoppedAt ?? tiltToPitch)), + pitchDeg: Math.round(toDegrees(stoppedAt ?? tiltToPitch)), }), ...(stopNote !== null && { note: stopNote }), }; }; const preserveCameraFlight = - motion === 'orbit' && - _viewer.scene.tweens.length > 0 && - !_viewer.trackedEntity; + motion === 'orbit' && cameraFlying() && !isFollowing(_viewer); return typeof runNavigation === 'function' ? runNavigation(start, { preserveCameraFlight }) : start(); @@ -2344,7 +2273,7 @@ export function adjustOrbitRange(factor) { function retargetTiltAfterZoom(m) { if (m.kind !== 'tilt' || m.mode !== 'once' || m.askedPitch === undefined) return {}; - let from = _viewer.camera.pitch; + let from = cameraOf(_viewer).pose().pitch; if (!(m.askedPitch > from)) return {}; if (m.hpr) { // At the same pivot pitch a longer range looks down more steeply (the @@ -2356,11 +2285,7 @@ function retargetTiltAfterZoom(m) { for (let i = 0; i < 4; i += 1) { const error = from - pivotCameraPitch(m.target, m.hpr, m.hpr.pitch); if (Math.abs(error) < 1e-7) break; - const pitch = Cesium.Math.clamp( - m.hpr.pitch + error, - -Cesium.Math.PI_OVER_TWO, - cap, - ); + const pitch = clamp(m.hpr.pitch + error, -PI_OVER_TWO, cap); if (pitch === m.hpr.pitch) break; m.hpr.pitch = pitch; } @@ -2380,14 +2305,14 @@ function retargetTiltAfterZoom(m) { m.elapsed = 0; m.durationS = Math.max( ONCE.durationS, - Math.abs(Cesium.Math.toDegrees(goal - from)) / TILT_TO_DEG_S, + Math.abs(toDegrees(goal - from)) / TILT_TO_DEG_S, ); const limited = goal !== m.askedPitch; return { - pitchDeg: Math.round(Cesium.Math.toDegrees(goal)), + pitchDeg: Math.round(toDegrees(goal)), note: limited ? tiltHorizonNote(goal) - : `The tilt now reaches ${Math.round(Cesium.Math.toDegrees(goal))}°.`, + : `The tilt now reaches ${Math.round(toDegrees(goal))}°.`, }; } @@ -2462,12 +2387,10 @@ export function flyRoute( error: 'The selected route has an invalid waypoint.', }; } - const pts = route.path.map((p) => - Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0), - ); + const pts = route.path.map((p) => fromDegrees(p.lon, p.lat, p.height || 0)); const cumM = [0]; for (let i = 1; i < pts.length; i += 1) { - cumM.push(cumM[i - 1] + Cesium.Cartesian3.distance(pts[i - 1], pts[i])); + cumM.push(cumM[i - 1] + distance(pts[i - 1], pts[i])); } if (!Number.isFinite(cumM.at(-1)) || cumM.at(-1) <= 0) { return { @@ -2485,8 +2408,8 @@ export function flyRoute( speed, floorFn, warmFn, - probeFn: (cells) => probeMeshFloorM(_viewer?.scene, cells), - cameraHeightM: _viewer?.camera?.positionCartographic?.height, + probeFn: (cells) => probeMeshFloorM(_viewer, cells), + cameraHeightM: findCamera(_viewer)?.pose().height, reducedMotion: prefersReducedMotion(), }), ); diff --git a/src/cctvFocusPolicy.js b/src/cctvFocusPolicy.js index e11c1e1caa..1cabba37f3 100644 --- a/src/cctvFocusPolicy.js +++ b/src/cctvFocusPolicy.js @@ -1,22 +1,23 @@ /** * Activates the nearest CCTV record on layer enable and flies only when no - * aircraft tracker or cockpit camera owns the view. + * followed target or cockpit camera owns the view. * @param {Object} options Layer-enable focus inputs. - * @param {*} options.trackedEntity Current Cesium tracked entity, if any. + * @param {*} options.followed What the camera follows, if anything + * (`followedOf`). * @param {boolean} options.cockpitActive Whether cockpit mode owns the camera. * @param {() => (string|null)} options.activate Nearest-camera activation. * @param {(cameraId: string) => *} options.fly Optional camera flight. * @returns {*} Activated camera ID for a held view, or the flight result. */ export function runCctvLayerEnableFocus({ - trackedEntity = null, + followed = null, cockpitActive = false, activate, fly, } = {}) { const cameraId = activate?.(); if (!cameraId) return false; - if (trackedEntity || cockpitActive) return cameraId; + if (followed || cockpitActive) return cameraId; return fly?.(cameraId); } @@ -25,11 +26,11 @@ export function runCctvLayerEnableFocus({ * chain. Either observation suppresses the optional CCTV focus flight. * @param {Object} [before={}] Ownership immediately before the await. * @param {Object} [after={}] Ownership immediately after the await. - * @returns {{ trackedEntity: *, cockpitActive: boolean }} Conservative ownership. + * @returns {{ followed: *, cockpitActive: boolean }} Conservative ownership. */ function mergeCctvEnableOwnership(before = {}, after = {}) { return { - trackedEntity: before.trackedEntity || after.trackedEntity || null, + followed: before.followed || after.followed || null, cockpitActive: !!(before.cockpitActive || after.cockpitActive), }; } @@ -60,7 +61,7 @@ export async function runCctvLayerEnableTransition({ const ownershipBefore = readOwnership?.() || {}; if (target === true) { debug?.('[UI:CCTV] ownership before setEnabled await', { - trackedId: ownershipBefore.trackedEntity?.id ?? null, + trackedId: ownershipBefore.followed?.key ?? null, cockpitActive: !!ownershipBefore.cockpitActive, }); } @@ -68,7 +69,7 @@ export async function runCctvLayerEnableTransition({ const ownershipAfter = readOwnership?.() || {}; if (target === true) { debug?.('[UI:CCTV] ownership after setEnabled await', { - trackedId: ownershipAfter.trackedEntity?.id ?? null, + trackedId: ownershipAfter.followed?.key ?? null, cockpitActive: !!ownershipAfter.cockpitActive, }); } diff --git a/src/cctvFocusPolicy.test.mjs b/src/cctvFocusPolicy.test.mjs index 333926a0f9..fd0913294d 100644 --- a/src/cctvFocusPolicy.test.mjs +++ b/src/cctvFocusPolicy.test.mjs @@ -8,8 +8,8 @@ import { test('CCTV layer enable activates nearest without stealing a tracked or cockpit view', () => { for (const ownership of [ - { trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }, - { trackedEntity: null, cockpitActive: true }, + { followed: { key: 'tracked-plane' }, cockpitActive: false }, + { followed: null, cockpitActive: true }, ]) { const calls = []; const result = runCctvLayerEnableFocus({ @@ -48,15 +48,15 @@ test('CCTV layer enable activates nearest without stealing a tracked or cockpit }); test('CCTV enable retains a pre-await tracking snapshot when tracking clears during enable', async () => { - let trackedEntity = { id: 'tracked-plane' }; + let followed = { key: 'tracked-plane' }; let flyCalls = 0; const diagnostics = []; const result = await runCctvLayerEnableTransition({ target: true, - readOwnership: () => ({ trackedEntity, cockpitActive: false }), + readOwnership: () => ({ followed, cockpitActive: false }), setEnabled: async () => { await Promise.resolve(); - trackedEntity = null; + followed = null; }, shouldFocus: () => true, activate: () => 'cam-near', @@ -83,7 +83,7 @@ test('CCTV disable transition does not emit enable-ownership diagnostics', async const result = await runCctvLayerEnableTransition({ target: false, - readOwnership: () => ({ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }), + readOwnership: () => ({ followed: { key: 'tracked-plane' }, cockpitActive: false }), setEnabled: async (target) => transitions.push(target), shouldFocus: () => true, activate: () => 'cam-near', diff --git a/src/celestialRing.js b/src/celestialRing.js index 525ded44ef..65e128ea85 100644 --- a/src/celestialRing.js +++ b/src/celestialRing.js @@ -1,5 +1,25 @@ -import * as Cesium from 'cesium'; import { governorRequestRender } from './renderGovernor.js'; +import { + cameraOf, + canvasOf, + findCamera, + findFrame, + findQuery, +} from './render/rendererOf.js'; +import { + moonPositionInertial, + sunPositionInertial, + temeToPseudoFixed, +} from './geo/celestial.js'; +import { WGS84 } from './geo/ellipsoid.js'; +import { frameVector } from './geo/frames.js'; +import { + dot, + magnitude, + normalize, + PI_OVER_TWO, + toRadians, +} from './geo/vector.js'; import { worldClock, worldTimeFor } from './time/worldClock.js'; // The ring shows the sun and moon at the time the sky is drawn. @@ -38,7 +58,13 @@ const EPHEMERIS_WORLD_STEP_MS = 60_000; const RING_INSET_PX = 11; const MARKER_INSET_PX = 36; const COLLIDING_MARKER_EXTRA_INSET_PX = 32; -const MARKER_COLLISION_ANGLE = Cesium.Math.toRadians(6); +const MARKER_COLLISION_ANGLE = toRadians(6); +/** The ellipsoid's largest radius, metres. */ +const EARTH_MAX_RADIUS_M = Math.max( + WGS84.radii.x, + WGS84.radii.y, + WGS84.radii.z, +); const FULL_GLOBE_RADIUS_RATIO = 0.61; const TAU = Math.PI * 2; // This overlay is a secondary HUD treatment. Keep it smooth while reserving @@ -218,7 +244,7 @@ export function isFullGlobeInsideKeyhole(geometry, wasVisible = false) { /** Return the Earth-disc radius in CSS pixels for a perspective camera. */ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) { - const earthRadiusM = Cesium.Ellipsoid.WGS84.maximumRadius; + const earthRadiusM = EARTH_MAX_RADIUS_M; if ( !Number.isFinite(cameraDistance) || cameraDistance <= earthRadiusM || @@ -234,15 +260,19 @@ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) { return Number.isFinite(radius) && radius > 0 ? radius : null; } +const EARTH_CENTRE = Object.freeze({ x: 0, y: 0, z: 0 }); + /** - * Project the visible Earth disc into viewport coordinates. + * Project the visible Earth disc into viewport coordinates, through the + * renderer's camera pose and its query port's projection. * Shared by full-globe UI treatments that must agree on visual containment. * - * @param {object} viewer - Cesium Viewer-like object. + * @param {object} viewer - The scene object the renderer is found from. * @param {number} width - Viewport width in CSS pixels. * @param {number} height - Viewport height in CSS pixels. - * @param {object} [scratchCenter] - Reusable Cesium Cartesian2 result. - * @param {object} [scratchToCenter] - Reusable Cesium Cartesian3 result. + * @param {{x:number,y:number}} [scratchCenter] - Takes the projected centre. + * @param {{x:number,y:number,z:number}} [scratchToCenter] - Takes the + * vector from the eye to the Earth's centre. * @returns {object|null} */ export function projectEarthDiscToViewport( @@ -252,36 +282,32 @@ export function projectEarthDiscToViewport( scratchCenter = undefined, scratchToCenter = undefined, ) { - const camera = viewer?.camera; - const scene = viewer?.scene; - if (!camera || !scene || !(width > 0) || !(height > 0)) return null; + const camera = findCamera(viewer); + if (!camera || !(width > 0) || !(height > 0)) return null; + const pose = camera.pose(); + const eye = pose.position; - const distance = Cesium.Cartesian3.magnitude(camera.positionWC); + const distance = magnitude(eye); + if (!Number.isFinite(distance) || distance <= EARTH_MAX_RADIUS_M) return null; + + const toCenter = scratchToCenter || { x: 0, y: 0, z: 0 }; + toCenter.x = -eye.x; + toCenter.y = -eye.y; + toCenter.z = -eye.z; + if (dot(pose.direction, toCenter) <= 0) return null; + + const projected = findQuery(viewer)?.project(EARTH_CENTRE); if ( - !Number.isFinite(distance) || - distance <= Cesium.Ellipsoid.WGS84.maximumRadius + !projected || + !Number.isFinite(projected.x) || + !Number.isFinite(projected.y) ) return null; + const center = scratchCenter || { x: 0, y: 0 }; + center.x = projected.x; + center.y = projected.y; - const toCenter = Cesium.Cartesian3.negate( - camera.positionWC, - scratchToCenter || new Cesium.Cartesian3(), - ); - if (Cesium.Cartesian3.dot(camera.directionWC, toCenter) <= 0) return null; - - const center = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - Cesium.Cartesian3.ZERO, - scratchCenter, - ); - if (!center || !Number.isFinite(center.x) || !Number.isFinite(center.y)) - return null; - - const earthRadius = earthDiscScreenRadius( - distance, - height, - camera.frustum?.fovy, - ); + const earthRadius = earthDiscScreenRadius(distance, height, pose.fovy); if (!earthRadius) return null; const keyhole = getKeyholeGeometry(width, height); @@ -396,14 +422,23 @@ let rings = 0; */ export class CelestialRing { /** - * @param {Cesium.Viewer} viewer - * @param {{enabled?:boolean,onAutoDisable?:Function,store:object}} options + * @param {object} viewer - The scene object the renderer is found from; + * the ring reads its canvas and container (DOM) and reaches the rest + * through the renderer's camera, frame and query ports. + * @param {{enabled?:boolean,onAutoDisable?:Function,store:object,preciseFrameAt?:Function}} options * `store` is the celestial ring store (src/ui/stores/celestialRing.js); * the keyhole helpers here stay free of Vue for the packages that use - * them. + * them. `preciseFrameAt(ms)` gives the ICRF-to-fixed rotation as axes, + * or null while its tables have not loaded; without it, or while it has + * no answer, the ring uses the pseudo-fixed frame. */ - constructor(viewer, { enabled = true, onAutoDisable = null, store }) { + constructor( + viewer, + { enabled = true, onAutoDisable = null, store, preciseFrameAt = null }, + ) { this.viewer = viewer; + this._preciseFrameAt = + typeof preciseFrameAt === 'function' ? preciseFrameAt : null; this.enabled = !!enabled; this.visible = false; this._onAutoDisable = @@ -426,18 +461,14 @@ export class CelestialRing { this._moonCanvas = null; this._moonCtx = null; - this._sunInertial = new Cesium.Cartesian3(); - this._moonInertial = new Cesium.Cartesian3(); - this._sunFixed = new Cesium.Cartesian3(); - this._moonFixed = new Cesium.Cartesian3(); - this._toCenter = new Cesium.Cartesian3(); - this._screenCenter = new Cesium.Cartesian2(); - this._fixedMatrix = new Cesium.Matrix3(); + this._sunFixed = { x: 0, y: 0, z: 0 }; + this._moonFixed = { x: 0, y: 0, z: 0 }; + this._toCenter = { x: 0, y: 0, z: 0 }; + this._screenCenter = { x: 0, y: 0 }; this._initView(store); - this._removePostRender = viewer.scene.postRender.addEventListener(() => - this._draw(), - ); + this._removePostRender = + findFrame(viewer)?.on('postRender', () => this._draw()) ?? null; // Pre-existing staleness fix (perf wave 2 review): the ephemeris was // sampled once per visible-enable from the FROZEN app clock, so the // sun/moon markers aged with the app. Resample real wall time each @@ -453,8 +484,6 @@ export class CelestialRing { governorRequestRender('celestial-ephemeris'); }, 60_000); // A jump in the world time moves the sun and moon at once. - this._skyDate = new Date(); - this._skyTime = new Cesium.JulianDate(); // Played through, the sky moves on each minute of world time it passes. this._ephemerisWorldMs = null; this._unsubscribeWorldTime = worldClock.subscribe(({ timeMs }) => { @@ -554,9 +583,14 @@ export class CelestialRing { }); } + /** The renderer's canvas; a viewer with no renderer bound, its own. */ + _canvas() { + return canvasOf(this.viewer); + } + /** Whether the current camera already frames the complete globe inside the keyhole. */ isGlobeFullyVisible() { - const canvas = this.viewer.scene.canvas; + const canvas = this._canvas(); const width = canvas.clientWidth || canvas.width; const height = canvas.clientHeight || canvas.height; if (!(width > 0 && height > 0)) return false; @@ -571,13 +605,15 @@ export class CelestialRing { * @returns {boolean} Whether a valid camera flight was started. */ focusFullGlobe({ duration = 2.4 } = {}) { - const canvas = this.viewer.scene.canvas; + const canvas = this._canvas(); const height = canvas.clientHeight || canvas.height; - const cartographic = this.viewer.camera.positionCartographic; - const fovy = this.viewer.camera.frustum?.fovy; + const camera = cameraOf(this.viewer); + const pose = camera.pose(); + const fovy = pose.fovy; if ( !(height > 0) || - !cartographic || + !Number.isFinite(pose.lon) || + !Number.isFinite(pose.lat) || !Number.isFinite(fovy) || fovy <= 0 || fovy >= Math.PI @@ -585,7 +621,7 @@ export class CelestialRing { return false; } - const earthRadius = Cesium.Ellipsoid.WGS84.maximumRadius; + const earthRadius = EARTH_MAX_RADIUS_M; const keyholeRadius = getKeyholeGeometry( canvas.clientWidth || canvas.width, height, @@ -600,27 +636,25 @@ export class CelestialRing { this._focusInProgress = true; const finishFocus = () => { this._focusInProgress = false; - this.viewer.scene.requestRender?.(); + findFrame(this.viewer)?.requestRender('celestial-focus'); }; - this.viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromRadians( - cartographic.longitude, - cartographic.latitude, - altitude, - ), - orientation: { - heading: this.viewer.camera.heading, - pitch: -Cesium.Math.PI_OVER_TWO, - roll: 0, + camera.flyTo( + { lon: pose.lon, lat: pose.lat, height: altitude }, + { + orientation: { + heading: pose.heading, + pitch: -PI_OVER_TWO, + roll: 0, + }, + durationS: duration, + easing: 'cubicInOut', + onComplete: finishFocus, + onCancel: () => { + finishFocus(); + if (!this.isGlobeFullyVisible()) this._autoDisable(); + }, }, - duration, - easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT, - complete: finishFocus, - cancel: () => { - finishFocus(); - if (!this.isGlobeFullyVisible()) this._autoDisable(); - }, - }); + ); return true; } @@ -671,31 +705,16 @@ export class CelestialRing { /** * Sample Earth-fixed directions once per enable. Camera movement only * re-projects these cached vectors; it never re-runs the planetary model. + * The precise ICRF frame serves once its tables have loaded, the + * pseudo-fixed one before. + * @param {number} ms Epoch milliseconds. */ - _updateEphemeris(time) { + _updateEphemeris(ms) { if (!this._ephemerisDirty) return true; - Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( - time, - this._sunInertial, - ); - Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame( - time, - this._moonInertial, - ); - const matrix = - Cesium.Transforms.computeIcrfToFixedMatrix(time, this._fixedMatrix) || - Cesium.Transforms.computeTemeToPseudoFixedMatrix(time, this._fixedMatrix); - if (!matrix) return false; - - Cesium.Matrix3.multiplyByVector(matrix, this._sunInertial, this._sunFixed); - Cesium.Matrix3.multiplyByVector( - matrix, - this._moonInertial, - this._moonFixed, - ); - Cesium.Cartesian3.normalize(this._sunFixed, this._sunFixed); - Cesium.Cartesian3.normalize(this._moonFixed, this._moonFixed); + const frame = this._preciseFrameAt?.(ms) ?? temeToPseudoFixed(ms); + this._sunFixed = normalize(frameVector(frame, sunPositionInertial(ms))); + this._moonFixed = normalize(frameVector(frame, moonPositionInertial(ms))); this._ephemerisDirty = false; this._ephemerisUpdateCount += 1; return true; @@ -792,7 +811,7 @@ export class CelestialRing { const now = performance.now(); if (now < this._nextDrawAt) return; this._nextDrawAt = now + 1000 / CELESTIAL_MAX_FRAME_RATE; - const canvas = this.viewer.scene.canvas; + const canvas = this._canvas(); const width = canvas.clientWidth || canvas.width; const height = canvas.clientHeight || canvas.height; if (!(width > 0 && height > 0)) return; @@ -822,19 +841,17 @@ export class CelestialRing { return; } - this._skyDate.setTime(skyTime()); - const time = Cesium.JulianDate.fromDate(this._skyDate, this._skyTime); - if (!this._updateEphemeris(time)) return; + if (!this._updateEphemeris(skyTime())) return; this._present({ ephemerisUpdates: String(this._ephemerisUpdateCount) }); - const camera = this.viewer.camera; + const pose = cameraOf(this.viewer).pose(); const sunProjection = celestialScreenAngle( - Cesium.Cartesian3.dot(this._sunFixed, camera.rightWC), - Cesium.Cartesian3.dot(this._sunFixed, camera.upWC), + dot(this._sunFixed, pose.right), + dot(this._sunFixed, pose.up), this._sunAngle, ); const moonProjection = celestialScreenAngle( - Cesium.Cartesian3.dot(this._moonFixed, camera.rightWC), - Cesium.Cartesian3.dot(this._moonFixed, camera.upWC), + dot(this._moonFixed, pose.right), + dot(this._moonFixed, pose.up), this._moonAngle, ); if (sunProjection.stable) this._sunAngle = sunProjection.angle; diff --git a/src/celestialRingView.test.mjs b/src/celestialRingView.test.mjs index c834ed53a6..841f42d746 100644 --- a/src/celestialRingView.test.mjs +++ b/src/celestialRingView.test.mjs @@ -9,7 +9,14 @@ import { createPinia } from 'pinia'; import { useCelestialRingStore } from './ui/stores/celestialRing.js'; import CelestialRingView from './ui/views/panels/CelestialRing.vue'; import * as Cesium from 'cesium'; -import { CelestialRing } from './celestialRing.js'; +import { + CelestialRing, + earthDiscScreenRadius, + projectEarthDiscToViewport, +} from './celestialRing.js'; +import { bindRenderer } from './render/rendererOf.js'; +import { bindFakeCesiumCamera } from './testSupport/fakeCameraPort.mjs'; +import { fakeSceneFrame } from './testSupport/fakeCesiumScene.mjs'; // happy-dom has no 2D context; a stand-in takes every drawing call. const context = new Proxy( @@ -19,18 +26,26 @@ const context = new Proxy( globalThis.HTMLCanvasElement.prototype.getContext = () => context; function fakeViewer(container) { - return { + const canvas = { + clientWidth: 400, + clientHeight: 300, + width: 400, + height: 300, + }; + const viewer = { container, + canvas, camera: { rightWC: new Cesium.Cartesian3(1, 0, 0), upWC: new Cesium.Cartesian3(0, 1, 0), }, scene: { - canvas: { clientWidth: 400, clientHeight: 300, width: 400, height: 300 }, + canvas, postRender: { addEventListener: () => () => {} }, requestRender() {}, }, }; + return bindFakeCesiumCamera(viewer, { frame: fakeSceneFrame(viewer) }); } function fixture(t) { @@ -157,8 +172,7 @@ const FRAMED = { /** Run one rendered frame, past the frame-rate throttle. */ function frame(ring, disc) { ring._projectedEarthDisc = () => disc; - // Fixed sun and moon directions; Cesium's own model would fetch its - // orientation data. + // Fixed sun and moon directions, so markers do not move with the clock. ring._updateEphemeris = () => { if (ring._ephemerisDirty) { Cesium.Cartesian3.clone(new Cesium.Cartesian3(1, 0, 0), ring._sunFixed); @@ -249,3 +263,119 @@ test('a ring the store no longer shows stops drawing', async (t) => { assert.equal(earlier.enabled, true); assert.equal(disabled, 0); }); + +test('the sun and moon directions are the planetary model in the pseudo-fixed frame', () => { + const pinia = createPinia(); + const ring = new CelestialRing(fakeViewer({}), { + enabled: false, + store: useCelestialRingStore(pinia), + // The precise frame's tables have not loaded. + preciseFrameAt: () => null, + }); + const ms = Date.UTC(2026, 10, 7, 12, 30); + ring._ephemerisDirty = true; + assert.equal(ring._updateEphemeris(ms), true); + // Cesium's own, before the sky has loaded the precise frame's tables. + const time = Cesium.JulianDate.fromDate(new Date(ms)); + const matrix = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time); + const expected = (inertial) => + Cesium.Cartesian3.normalize( + Cesium.Matrix3.multiplyByVector( + matrix, + inertial, + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + const sun = expected( + Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( + time, + ), + ); + const moon = expected( + Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame( + time, + ), + ); + for (const [got, want] of [ + [ring._sunFixed, sun], + [ring._moonFixed, moon], + ]) + for (const axis of ['x', 'y', 'z']) + assert.ok(Object.is(got[axis], want[axis]), axis); + assert.equal(ring._ephemerisUpdateCount, 1); + ring.destroy(); +}); + +test('the projected disc reads the camera and query ports', () => { + const canvas = { clientWidth: 800, clientHeight: 600 }; + const viewer = { canvas }; + const distance = 3 * 6378137; + const pose = { + position: { x: distance, y: 0, z: 0 }, + direction: { x: -1, y: 0, z: 0 }, + fovy: Math.PI / 3, + }; + const unbind = bindRenderer(viewer, { + canvas, + camera: { pose: () => pose }, + query: { project: () => ({ x: 410, y: 290 }) }, + }); + const toCenter = { x: 0, y: 0, z: 0 }; + const centre = { x: 0, y: 0 }; + const disc = projectEarthDiscToViewport(viewer, 800, 600, centre, toCenter); + assert.equal(disc.earthCenterX, 410); + assert.equal(disc.earthCenterY, 290); + assert.deepEqual(centre, { x: 410, y: 290 }); + // The scratch takes the eye-to-centre vector, as callers read it after. + assert.deepEqual(toCenter, { x: -distance, y: -0, z: -0 }); + assert.ok( + Math.abs( + disc.earthRadius - earthDiscScreenRadius(distance, 600, pose.fovy), + ) < 1e-9, + ); + // Facing away: null, with the eye-to-centre vector still written, as + // radio navigation reads it after. + pose.direction = { x: 1, y: 0, z: 0 }; + const away = { x: 0, y: 0, z: 0 }; + assert.equal(projectEarthDiscToViewport(viewer, 800, 600, null, away), null); + assert.deepEqual(away, { x: -distance, y: -0, z: -0 }); + // Inside the ellipsoid's largest radius: null, the scratch untouched. + pose.position = { x: 6378137, y: 0, z: 0 }; + const inside = { x: 1, y: 2, z: 3 }; + assert.equal( + projectEarthDiscToViewport(viewer, 800, 600, null, inside), + null, + ); + assert.deepEqual(inside, { x: 1, y: 2, z: 3 }); + unbind(); +}); + +test('the precise frame serves once it answers', () => { + const pinia = createPinia(); + // A quarter turn about z: x goes to y. + const quarter = { + x: { x: 0, y: 1, z: 0 }, + y: { x: -1, y: 0, z: 0 }, + z: { x: 0, y: 0, z: 1 }, + }; + const ring = new CelestialRing(fakeViewer({}), { + enabled: false, + store: useCelestialRingStore(pinia), + preciseFrameAt: () => quarter, + }); + const ms = Date.UTC(2026, 10, 7, 12, 30); + ring._ephemerisDirty = true; + ring._updateEphemeris(ms); + const time = Cesium.JulianDate.fromDate(new Date(ms)); + const sun = Cesium.Cartesian3.normalize( + Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( + time, + ), + new Cesium.Cartesian3(), + ); + assert.ok(Math.abs(ring._sunFixed.x + sun.y) < 1e-12); + assert.ok(Math.abs(ring._sunFixed.y - sun.x) < 1e-12); + assert.ok(Math.abs(ring._sunFixed.z - sun.z) < 1e-12); + ring.destroy(); +}); diff --git a/src/cockpitCloudEffects.js b/src/cockpitCloudEffects.js index c1cc796b45..db1495391d 100644 --- a/src/cockpitCloudEffects.js +++ b/src/cockpitCloudEffects.js @@ -1,5 +1,6 @@ import { applicationServices } from './services/application.js'; -import * as Cesium from 'cesium'; +import { toRadians } from './geo/vector.js'; +import { findCamera } from './render/rendererOf.js'; import { greatCircleMeters } from './geoDistance.js'; import { deriveWeatherEffectProfile, @@ -341,15 +342,14 @@ class CockpitCloudEffectsController { } cameraPoint() { - const cartographic = this.viewer?.camera?.positionCartographic; - if (!cartographic) return null; - const latitude = Cesium.Math.toDegrees(cartographic.latitude); - const longitude = Cesium.Math.toDegrees(cartographic.longitude); + const pose = this.viewer ? findCamera(this.viewer)?.pose() : null; + if (!pose) return null; + const { lat: latitude, lon: longitude } = pose; if (![latitude, longitude].every(Number.isFinite)) return null; return { latitude, longitude, - altitudeM: Math.max(0, Number(cartographic.height) || 0), + altitudeM: Math.max(0, Number(pose.height) || 0), }; } @@ -543,7 +543,7 @@ class CockpitCloudEffectsController { render(timeSec) { const gl = this.gl; if (!gl || !this.program || !this.locations) return; - const windRadians = Cesium.Math.toRadians(this.windDirectionDeg); + const windRadians = toRadians(this.windDirectionDeg); const windScale = 0.008 + this.windStrength * 0.022; gl.useProgram(this.program); gl.uniform2f( diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index 06db3aeff1..3c1e3ed142 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -26,10 +26,7 @@ import { setSignalCollapsed, } from './ui/cockpitLayout.js'; import { createBriefState } from './ui/cockpitBriefPages.js'; -import { - publishBriefView, - setBriefAutoRotate, -} from './ui/cockpitBriefing.js'; +import { publishBriefView, setBriefAutoRotate } from './ui/cockpitBriefing.js'; import { CockpitDisplayPortal } from './ui/cockpitDisplayPortal.js'; import { _handleContextLayerChange } from './ui/contextLayerChanges.js'; import { clearSelectedLayers } from './ui/contextActions.js'; @@ -228,7 +225,7 @@ test('Cockpit Escape handling precedes form-control shortcut suppression and foc assert.doesNotMatch(exit, /applyTrackedCameraFrame/); assert.match( ui, - /restoreTrackingFrame: \(entity\) => \{[\s\S]*?gevTrackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/, + /restoreTrackingFrame: \(entity\) => \{[\s\S]*?readEntityRecord\(entity\)\?\.trackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/, 'Cockpit exit must return camera-frame ownership through the source layer so Contact Focus cannot accumulate a second owner', ); }); @@ -294,14 +291,14 @@ test('the Contact panel never hides itself out from under its own NEXT button', ); }); -test('the cockpit reads its aircraft from the layer that owns Cesium tracking', () => { +test('the cockpit reads its aircraft from the layer the camera follows', () => { const read = readAircraftInfo.toString(); assert.ok(read, 'readAircraftInfo is missing'); assert.match(read, /resolveTrackedAircraftInfo\(\{/); - assert.match(read, /gevTrackedId/); - // In cockpit mode the controller moves the entity off viewer.trackedEntity, - // so its own handle is the tracked identity there. - assert.match(read, /this\.viewer\?\.trackedEntity \|\| this\.trackedEntity/); + assert.match(read, /trackedId: followed\?\.key/); + // In cockpit mode the controller stops the camera following, so its own + // handle is the tracked identity there. + assert.match(read, /followedOf\(this\.viewer\) \|\| this\.trackedFollow/); }); test('programmatic Context layer changes cannot bypass explicit expansion policy', () => { @@ -438,13 +435,10 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls', /data-cockpit-launcher="radio"[\s\S]*?id="cockpit-radio-toggle-btn"/, ); const cockpitRadio = html.match( - /id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<\/aside>/, + /id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*
Effects<[\s\S]*?id="celestial-toggle"/, ); assert.equal( (html.match(/id="param-slider-panel"/g) || []).length, @@ -811,18 +805,27 @@ test('Reset releases Contact camera ownership through its selection-preserving r ); assert.match(ui, /onReset: \(\) => this\.resetToGlobeView\(\)/); assert.match(ui, /this\._connectGlobeReset\?\.\(this\._locationControls\)/); - assert.match(controls, /reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/); + assert.match( + controls, + /reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/, + ); // Both reset buttons ask the one reset owner. const globeActions = fs.readFileSync( path.join(ROOT, 'src', 'ui', 'views', 'panels', 'GlobeActions.vue'), 'utf8', ); - assert.match(globeActions, /id="reset-globe-view"[^>]*@click="act\('reset'\)"/); + assert.match( + globeActions, + /id="reset-globe-view"[^>]*@click="act\('reset'\)"/, + ); const cockpitView = readRadioSource( new URL('./ui/views/CockpitView.vue', import.meta.url), 'utf8', ); - assert.match(cockpitView, /id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/); + assert.match( + cockpitView, + /id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/, + ); assert.match( cockpitEnter.toString(), /Object\.assign\(this\.presence, \{\s*active: true,/, @@ -1170,7 +1173,7 @@ test('cockpit route direction uses self-contained vector artwork, not a font lig test('cockpit aircraft handoff invalidates the prior world-position anchor', () => { const match = _adoptTrackedEntity.toString(); assert.ok(match, 'cockpit tracked-entity handoff block is missing'); - assert.match(match, /this\.viewer\.trackedEntity = undefined;/); + assert.match(match, /stopFollowing\(this\.viewer\);/); assert.match(match, /this\.cockpitAnchorValid = false;/); assert.match( match, @@ -1193,7 +1196,10 @@ test('cockpit summary presents the focused item as Contact', () => { const match = html.match(/