Merge branch 'main' into german/recent-imagery-auto-successor

This commit is contained in:
German Khokhlov authored and GitHub committed 2026-11-20 17:03:24 +04:00
commit 4262829e27
178 files changed
+18826 -537

No files matched your search

+10
View File
@@ -37,6 +37,8 @@ GOOGLE_MAPS_API_KEY=
GOOGLE_MAPS_SERVER_API_KEY=
# Per-IP rate limit for the Google Places cost endpoints
# (/api/google/nearby-places + /api/google/text-search), in requests per minute.
# The CCTV Street View fallback counts in its own window with the same cap;
# over it, a frame gets the placeholder image instead of a 429.
# DEFAULTS TO 120, the value the Pinokio build already ships. Raise or lower it
# with a positive integer; 60 is a sensible tightening whenever HOST is not
# localhost. Set it to exactly 0 to run unthrottled. An unreadable value (a
@@ -136,6 +138,14 @@ OPENSKY_CLIENT_SECRET=
# Optional paid Patreon tokens raise request limits; there is no free API key.
LL2_API_TOKEN=
# Optional: NASA's public ISS telemetry (the ISSLive feed, served by
# Lightstreamer). Off by default: the feed publishes no terms of use, so the
# server contacts it only when this is 1. It then holds one connection, open
# only while a browser has the ISS model on screen, and the model's solar
# arrays, radiators and Ku-band dish take their real angles from it. No key.
# See DATA_SOURCES.md.
# ISS_TELEMETRY_ENABLED=
# Optional: OpenSky credentials JSON file path, used when the two values above
# are empty: the credentials.json your OpenSky account page downloads when you
# create an API client. Use an absolute path for compatibility with launchers.
+10 -6
View File
@@ -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. 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)).
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, except NASA's ISS model (`public/models/iss.glb`) ([`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.
- **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.
- **The bundled 3D models are the project's own, but one.** Every model under `public/models/` except `iss.glb` is a procedural model generated by the project maintainers (the fleet, and Tiangong from `scripts/build-tiangong-model.py`) and covered by the repository's MIT license; `iss.glb` is NASA's public-domain model of the ISS (see NASA 3D Resources below); [`public/models/README.md`](public/models/README.md) describes the set.
---
@@ -34,6 +34,10 @@ How to read this:
| **Open Vessel Photos** (`openvesselphotos.org/v1/mmsi/{mmsi}`) | One photo of the selected vessel, by MMSI, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI | Free, keyless public API ([README](https://github.com/louptheron/openvesselphotos)); each photo keeps the open licence its author chose (CC BY, CC BY-SA, CC0, or public domain), given with it in the API | "Photo: {photographer} · {licence}" beside every photo, linked to the vessel's Open Vessel Photos page; "Open Vessel Photos" in Data attribution |
| **AISStream.io** | Live vessels (AIS) | Free, beta, no formal ToS; AIS is a public broadcast | "AISStream.io" (courtesy) |
| **CelesTrak** | Satellite TLEs (SGP4) and SATCAT records (object type, operational status, owner) that file each satellite under a class | US-government-origin data, no license; citation requested | "CelesTrak (celestrak.org), Dr. T.S. Kelso" |
| **NASA 3D Resources** (`public/models/iss.glb`) | The ISS drawn as a 3D model when the camera is near it (satellites layer): NASA/JSC IGOAL's "International Space Station (ISS) (D)" (https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/), reduced and re-rigged as `public/models/README.md` records. Its moving parts are computed by the app unless the telemetry relay in the next row is switched on: arrays and radiators from the Sun's position, the Ku-band dishes toward the TDRS fleet's nominal slots (41°W, 171°W, 85°E), the robotic arms as an illustrative sway | NASA media, not subject to copyright in the United States; NASA's Images and Media Usage Guidelines (https://www.nasa.gov/nasa-brand-center/images-and-media) ask that use not imply endorsement and that the insignia not be used; the model's textures carry the NASA insignia and the ESA, Columbus, JAXA and Nanoracks marks as flown on the station, kept to show it as it is, implying no endorsement by NASA or any partner | "ISS model: NASA 3D Resources" |
| **Project model** (`public/models/tiangong.glb`) | Tiangong drawn as a 3D model when the camera is near it (satellites layer): an original model of the station's T configuration (Tianhe, Wentian, Mengtian, a Shenzhou forward and nadir, a Tianzhou aft) made for God's Eye View from primitives with procedurally generated textures; dimensions from Wang, Zhang & Wang 2023, "Design and Application Prospect of China's Tiangong Space Station", Space: Science & Technology (https://doi.org/10.34133/space.0035, CC BY 4.0) and eoPortal's Tiangong page, the approximate parts listed in `public/models/README.md`. Its moving parts are computed by the app: the wings from the Sun's position, the high-gain antenna toward the Tianlian II nominal slots (79.9°E, 171.04°E, 10.5°E), the two arms as an illustrative sway; China publishes no live telemetry for the station | MIT, with the rest of the project's own work (`LICENSE`): an original asset with no third-party geometry, textures or images; the published dimensions are facts taken from a CC BY 4.0 paper and eoPortal | "Tiangong model: made for God's Eye View; dimensions from Wang, Zhang & Wang 2023 (CC BY 4.0) and eoPortal" |
| **NASA ISSLive telemetry** (`push.lightstreamer.com`, adapter set `ISSLIVE`) | **Off by default.** With `ISS_TELEMETRY_ENABLED=1` the server holds one connection to NASA's public ISS telemetry stream, open only while a browser has the ISS model on screen, and relays the latest joint angles at `/api/iss-telemetry`: the two alpha joints, the eight array beta joints, the two radiator joints and the Ku-band dish (Canadarm2's joints are relayed but not used yet). While the station has signal the ISS model takes those angles in place of the computed ones. The app stores nothing from it | The public subset of ISS telemetry NASA released as the ISSLive project, served for NASA by Lightstreamer. No terms of use are published for the feed, so it is opt-in and no request is made by default | "ISS joint telemetry: NASA ISSLive, via Lightstreamer" |
| **NASA ISS live streams on YouTube** (`youtube-nocookie.com/embed/ROboUHfPUrU`, `.../M3HKLzjvKPc`) | NASA's official live video from the ISS, two broadcasts ("Live High-Definition Views from the International Space Station" from the exterior cameras, and the live video with space-to-ground audio), offered in a LIVE section of Context, and on the Cockpit briefing's LIVE page, while the ISS is selected on the map, and played, muted, in YouTube's own embedded player only after the viewer presses Play; collapsing the section, closing Context or leaving the Cockpit page removes the player; the app stores nothing from it (`src/data/liveStreams.js`) | NASA video, not subject to copyright in the United States, distributed through YouTube under YouTube's Terms of Service, which permit embedding with the public embeddable player; the player API script loads from `www.youtube.com` and the video from the privacy-enhanced host `www.youtube-nocookie.com`, and the viewer's IP address reaches YouTube only once they press Play, under a line that says so | "NASA video, via YouTube", with a link to the stream's own page |
| **The Space Devs — Launch Library 2 v2.3** | Recent launch, payload, stage, and recovery metadata for Space Missions (30d) | [The Space Devs terms of use](https://github.com/TheSpaceDevs/Tutorials/blob/main/faqs/faq_TSD.md#terms-of-use): data may be used and shared in any form; avoid forwarding it without added value; attribution is encouraged (not mandatory). [Official API limits](https://ll.thespacedevs.com/docs/): 15 unauthenticated calls/hour; optional token | "Launch Library 2 — The Space Devs" (courtesy attribution) |
| **Esri World Imagery** (ArcGIS Online tile service) | The keyless satellite basemap — the default landing when no Google/ion credential is configured, and the "Esri Satellite" map stack | [Esri Master Agreement](https://www.esri.com/en-us/legal/terms/full-master-agreement): the public World Imagery service is usable in public-facing apps with attribution; no key is required for this classic endpoint, but Esri governs and can change access — an app at scale should review current ArcGIS Location Platform terms | "Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community" (provider carries the service's own credit line) |
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
@@ -68,7 +72,7 @@ How to read this:
| **Caltrans (cwwp2.dot.ca.gov)** | CCTV camera catalogs + frames, California districts | Public Caltrans traffic camera data | "Caltrans — cwwp2.dot.ca.gov" (courtesy) |
| **DelDOT (video.deldot.gov)** | CCTV camera catalog (`tmc.deldot.gov/json/videocamera.json`, cached for 15 minutes) + live HTTPS HLS video, Delaware. Keyless | Public DelDOT traffic camera streams via the [DelDOT traffic map](https://deldot.gov/map/) | "DelDOT — Delaware Department of Transportation" (courtesy) |
| **TfL Open Data (JamCams)** | CCTV camera catalog + frames, London | [TfL Open Data terms](https://tfl.gov.uk/info-for/open-data-users/) — attribution REQUIRED | "Powered by TfL Open Data. Contains OS data © Crown copyright and database rights" |
| **Ontario 511** | CCTV camera catalog + frames, Ontario highways including Kitchener-area routes | [Open Government Licence – Ontario](https://www.ontario.ca/page/open-government-licence-ontario) | "Ontario 511" plus Open Government Licence - Ontario |
| **Ontario 511** | CCTV camera catalog + frames, Ontario highways including Kitchener-area routes | [Open Government Licence – Ontario](https://www.ontario.ca/page/open-government-licence-ontario) | "Ontario 511. Contains information licensed under the Open Government Licence – Ontario" |
| **Fintraffic / Digitraffic (weathercams)** | CCTV camera catalog + frames, Finland | [CC BY 4.0](https://www.digitraffic.fi/en/terms-of-service/) — attribution REQUIRED | "Fintraffic / digitraffic.fi, license CC BY 4.0" |
| **DriveBC** (Government of British Columbia) | CCTV camera catalog + frames, British Columbia highways | [Open Government Licence – British Columbia](https://www2.gov.bc.ca/gov/content/data/open-data/open-government-licence-bc) — attribution REQUIRED | "DriveBC. Contains information licensed under the Open Government Licence – British Columbia" |
| **Open Calgary** (`data.calgary.ca`) | CCTV camera catalog + frames, Calgary | [Open Government Licence – City of Calgary](https://data.calgary.ca/stories/s/Open-Calgary-Terms-of-Use/u45n-7awa) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – City of Calgary" |
@@ -247,7 +251,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Open Vessel Photos.** When you select a vessel with a nine-digit MMSI, the browser asks `https://openvesselphotos.org/v1/mmsi/{mmsi}` directly (the API is keyless and answers cross-origin, so no key and no server proxy are involved; account credentials are never sent) for that vessel only, once per MMSI per session, with an 8-second timeout. A miss (a 404 or a vessel without photos) is remembered for the session; a failed request may be asked again after five minutes. The first photo whose image is an `https://openvesselphotos.org` URL and which names a licence is shown, at the 800 px size, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI (`src/ui/views/panels/AwarenessPanel.vue`), and nowhere else (`src/data/openVesselPhoto.js`, `src/layers/vessels/photos.js`). The image is hotlinked from the URL the API gives (never copied or re-hosted); the photographer and licence are visible text next to it ("Photo: {photographer} · {licence}", or "Photo · {licence}" when the answer names no one), and the photo and credit link to the vessel's Open Vessel Photos page with `target="_blank" rel="noopener"`. If the image fails to load, the photo and its credit are hidden.
- **Launch Library 2.** `/api/launches` makes a server-side rolling-30-day query against the supported v2.3 detailed launch endpoint, caches successful responses for 15 minutes in memory and on disk, and serves the last successful response during a throttle or transient outage. Anonymous access is limited to 15 calls/hour; deployments can provide `LL2_API_TOKEN` for authenticated access. The Space Devs' published terms permit using and sharing the API data in any form, ask users not to forward it without adding value, disclaim complete accuracy, and encourage—but do not require—attribution. This app keeps a courtesy credit. Payload and stage/recovery records are shown only when supplied. Failed launches expose their source status and never receive fallback orbit geometry or a live/estimated marker. LL2 supplies launch context and event timing, not continuous ascent telemetry or live orbital state.
- **TfL JamCams.** The camera list comes from the keyless `api.tfl.gov.uk` endpoint (an optional `TFL_APP_KEY` raises its rate limit); frames come from TfL's public S3 bucket. The "Powered by TfL Open Data" attribution is required by TfL's terms and is registered in the Data attribution popover.
- **Ontario 511 CCTV.** The camera list comes from the `511on.ca/api/v2/get/cameras` endpoint, which now requires a free developer key (`ONTARIO_511_API_KEY`: sign up at 511on.ca/my511/register, then request it while logged in at 511on.ca/developers/doc; throttled to 10 calls a minute). Without the key the pack is skipped. Frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario. Access is governed by Ontario 511's Developer's Access Agreement (511on.ca/developers/resources): the data stays under the Open Government Licence - Ontario unless otherwise specified; key requests are reviewed case by case and ask for the intended use and any third parties that will receive the data; attribution by link to 511on.ca is encouraged, and the Ontario 511 logo may not be altered or used to imply endorsement (this app links and shows no logo); and the data is provided "as is", a disclaimer distributors should pass on, which the credit does.
- **Ontario 511 CCTV.** The camera list comes from the `511on.ca/api/v2/get/cameras` endpoint, which now requires a free developer key (`ONTARIO_511_API_KEY`: sign up at 511on.ca/my511/register, then request it while logged in at 511on.ca/developers/doc; throttled to 10 calls a minute). Without the key the pack is skipped. Frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence – Ontario. Access is governed by Ontario 511's Developer's Access Agreement (511on.ca/developers/resources): the data stays under the Open Government Licence – Ontario unless otherwise specified; key requests are reviewed case by case and ask for the intended use and any third parties that will receive the data; attribution by link to 511on.ca is encouraged, and the Ontario 511 logo may not be altered or used to imply endorsement (this app links and shows no logo); and the data is provided "as is", a disclaimer distributors should pass on, which the credit does.
- **DelDOT live video cameras.** The keyless `tmc.deldot.gov/json/videocamera.json` catalog supplies active cameras and official `https://video.deldot.gov/live/…/playlist.m3u8` links. The local server transiently buffers bounded MPEG-TS segments in memory and deletes them on session release or idle expiry. No recordings are retained. `CCTV_DELDOT_ENABLED=0` disables the pack. Public availability is not a blanket redistribution license; deployment beyond personal local viewing needs confirmation of applicable DelDOT terms.
- **Fintraffic weathercams.** The camera list is one keyless GeoJSON request to `tie.digitraffic.fi/api/weathercam/v1/stations` (809 stations / 2,275 presets), sent with the `Digitraffic-User: gods-eye-view` header the service asks clients to identify themselves with and with gzip; frames are stills on `weathercam.digitraffic.fi`, refreshed on each station's 600 s collection interval, which is also the client's ambient-still refresh cadence for this pack (the active camera keeps the usual 10-second refresh). One preset (a fixed camera view) is one camera; stations not `GATHERING` and presets not `inCollection` are dropped. Attribution is required by the CC BY 4.0 licence and is registered in the Data attribution popover. `CCTV_FINTRAFFIC_ENABLED=0` is the kill switch.
- **DriveBC highway cameras.** The camera list comes from the keyless `https://www.drivebc.ca/api/webcams/` endpoint served by the DriveBC.ca site ([bcgov/DriveBC.ca](https://github.com/bcgov/DriveBC.ca)); frames come from `https://www.drivebc.ca/images/<id>.jpg`, built from the numeric camera id. DataBC's [DriveBC HighwayCams](https://catalogue.data.gov.bc.ca/dataset/bc-highwaycams) catalogue entry publishes the same cameras under the Open Government Licence – British Columbia, but its CSV still lists the retired `images.drivebc.ca` frame URLs, which now return a placeholder. The licence's attribution statement is required and is registered in the Data attribution popover. By default the 250 cameras nearest Vancouver and Victoria load; `CCTV_DRIVEBC_MAX_SOURCES` changes the cap and `CCTV_DRIVEBC_ENABLED=0` turns the pack off. Some cameras in the feed are supplied by partners (TransLink, the City of Vancouver, the City of Surrey, Parks Canada / Alberta Motor Association and others); the feed's per-camera credit is carried onto the camera record and shown beside the provider in the CCTV panel.
@@ -411,7 +415,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p
| Dataset | Folder | License | Commercial use? | Attribution |
| --------------------------------------------------------------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------- |
| **Datacenters** (4,352) | `datacenters/` | **ODbL 1.0** (OpenStreetMap extract) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) |
| **Dams** (704) | `dams/` | **ODbL 1.0** (OpenInfraMap / OSM extract) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + Open Infrastructure Map |
| **Dams** (706) | `dams/` | **ODbL 1.0** (OpenInfraMap / OSM extract + OSM API) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + Open Infrastructure Map |
| **Military area names** (36,466) | `osm_military_names/` | **ODbL 1.0** (OpenStreetMap, via Overture Maps) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + Overture Maps Foundation |
| **Ukraine outline** (Rail layer no-positions rule; 1 ring, 7,801 points) | `src/data/railNoPositions.js` | **ODbL 1.0** (OpenStreetMap, via geoBoundaries gbOpen UKR ADM0, commit 9469f09; simplified to 0.0005°) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + geoBoundaries |
| **Québec CCTV source catalog** (1,120 locations) | `public/quebec-cameras.json` | Mixed: MTQ locations CC BY 4.0; Montréal camera nodes ODbL 1.0; scenic records retain per-record provenance. No video files are bundled or cached. | Location data is per-record; video remains hosted by Québec 511 and its platform terms apply; scenic source pages may have separate terms | MTQ / Données Québec CC BY 4.0; © OpenStreetMap contributors (ODbL); scenic operator and position source shown in the selected-camera panel |
@@ -485,7 +489,7 @@ credits it anyway as `SPECS: CCTV-DATABASE.COM` beside any spec line it renders.
### Bundled OpenStreetMap data
Bundled OSM-derived data is distributed under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/), separately from the MIT code: [datacenters](src/data/local_data/datacenters/), [dams](src/data/local_data/dams/) (via Open Infrastructure Map), [military names](src/data/local_data/osm_military_names/), the Rail layer's Ukraine outline in [`railNoPositions.js`](src/data/railNoPositions.js) (OpenStreetMap via geoBoundaries gbOpen, Runfola et al. 2020, simplified; the module's code stays MIT), and [OSM test fixtures](src/data/fixtures/). Keep © OpenStreetMap contributors and offer modified databases under ODbL.
Bundled OSM-derived data is distributed under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/), separately from the MIT code: [datacenters](src/data/local_data/datacenters/), [dams](src/data/local_data/dams/) (from Open Infrastructure Map and the OpenStreetMap API), [military names](src/data/local_data/osm_military_names/), the Rail layer's Ukraine outline in [`railNoPositions.js`](src/data/railNoPositions.js) (OpenStreetMap via geoBoundaries gbOpen, Runfola et al. 2020, simplified; the module's code stays MIT), and [OSM test fixtures](src/data/fixtures/). Keep © OpenStreetMap contributors and offer modified databases under ODbL.
### NASA FIRMS acknowledgement
+1 -1
View File
@@ -480,7 +480,7 @@ 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 |
**Also on the globe:** neighborhood overlays · an optional cockpit WX cloud effect. **Bundled static infrastructure:** Datacenters (4,352), Dams (704), and Submarine Cables (712).
**Also on the globe:** neighborhood overlays · an optional cockpit WX cloud effect. **Bundled static infrastructure:** Datacenters (4,352), Dams (706), and Submarine Cables (712).
**Missing a layer you want?** Open an issue — or add it and send the PR.
+4 -2
View File
@@ -68,10 +68,12 @@ browser-key fallback for existing single-key setups.
The data proxies under `server/providers/` are written so the browser cannot turn the server into an open relay:
- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). Other proxies target fixed upstream hosts.
- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). The key-bearing Street View fallback likewise answers only for a registered camera, at its catalog position; a request sets only the heading, field of view and pitch, never the location. Other proxies target fixed upstream hosts.
- **Live HLS is bounded and origin-pinned.** Registered HTTP(S) HLS sources use a Node puller that rejects redirects and off-origin playlist references, bounds playlists to 256 KiB and segment bodies to 8 MiB while streaming, and aborts timed-out or released sessions. At most two sessions retain 12 segments/24 MiB each, plus bounded download buffers. Stores are memory-only and idle sessions expire after 15 seconds. RTMP/ffmpeg execution is not enabled. Locally configured source URLs remain an operator trust boundary.
- **Radio is not an audio relay.** `/api/radio/stations` contacts only allowlisted Radio Browser HTTPS hosts and paths, rejects redirects, rejects any hostname with a loopback/private/link-local/metadata/non-public A or AAAA result, and pins each TLS connection to a validated address. It returns normalized public HTTPS stream URLs; `/api/radio/click/:uuid` applies the same destination policy and accepts only station IDs from the current bounded catalog. The browser then connects directly to the broadcaster after an explicit playback action, so the broadcaster sees the listener's IP address. GEV never proxies, caches, records, or redistributes audio.
- **Québec 511 video plays in the browser, opt-in and after Play.** With `CCTV_QUEBEC_VIDEO_ENABLED=1`, `/api/cctv/sources` lists, for each MTQ camera, one URL built server-side from its numeric id on `https://www.quebec511.info/Carte/Fenetres/camera.ashx`; the overlay accepts no other host, path or format. The browser loads that clip only after the viewer presses Play for the selected camera, so Québec 511 sees the viewer's IP address, and the panel says so before Play. Selecting a camera by click, auto-hop, a scene or voice never loads it, and switching cameras stops playback. GEV never proxies, caches or reads the video's pixels. With the flag unset (the default) the browser makes no request to Québec 511.
- **Station live video plays only after Play.** The LIVE section of Context and the Cockpit briefing's LIVE page load YouTube's player (the IFrame API from `www.youtube.com`, the video on `www.youtube-nocookie.com`) only after the viewer presses Play, under a line saying that YouTube sees their IP address. Selecting a station by click, a share link that follows it, a scene or voice shows the poster and loads nothing. The player goes when the section is collapsed, Context is closed or collapsed, the Cockpit leaves its LIVE page, the Cockpit is entered or left, or the selection moves to an object without that stream. GEV never proxies, caches or reads the video's pixels.
- **The ISS telemetry relay is opt-in, keyless and read-only.** With `ISS_TELEMETRY_ENABLED=1`, `/api/iss-telemetry` answers from one shared WebSocket the server opens to NASA's public ISSLive feed (`wss://push.lightstreamer.com`), only while a browser has asked in the last two minutes; every byte from the feed is parsed as untrusted text, a frame over 64 KB closes the socket (retried on the backoff ladder), and only the listed joint and clock items are kept. The route uses the keyless same-site checks and a per-client rate limit; with the flag unset (the default) it answers `{ configured: false }` and the server opens no socket.
- **No verbatim client headers upstream.** The CCTV media route is the one route that relays a request header (`Range`, for video seeking). It is parsed and canonicalized before it is forwarded: one `bytes=` range only, with every accepted form — explicit span, open-ended and suffix — bounded to the same 64 MiB ceiling the relay applies to a declared response body. Multi-range, malformed, inverted and non-`bytes` values are dropped and the request proceeds without a `Range`, as RFC 7233 §3.1 prescribes. Bounding the request bounds what is asked for: a response that declares no length — live streamed media, or a chunked body from an upstream that ignores the `Range` — has no ceiling. An upstream request the browser has stopped waiting for is cancelled rather than left running, whether the viewer leaves before the headers arrive or during the body.
- **The Data Library proxy fetches manifest upstreams only.** `/api/library/data/<id>`, `/api/library/tile/<id>/<z>/<x>/<y>` and `/api/library/index/<id>` (a partitioned GeoParquet entry's file index, built from an S3 ListObjectsV2 listing and one ranged footer read per file, cached in memory for the entry's `cacheSeconds`) resolve the id against the validated manifests in `src/library/entries/`; the browser never supplies a URL, and every derived request must stay on the manifest's https host. Redirects are refused, dataset bodies are capped while streaming at the manifest's `maxBytes` (at most 32 MiB) and tiles at 2 MiB of `image/png`, `image/jpeg` or `image/webp`, responses are cached in memory only (at most 512 tiles), requests are rate-limited per client, and upstream error text is never returned. A keyed entry must be proxied; its key is read from this server's environment through the key registry and its routes refuse cross-site and forwarded requests like the other cost-bearing routes. Browser-direct entries are fetched by the browser with no cookies or referrer.
- **Transit fetches registered feeds only.** `/api/transit/vehicles/<id>` resolves the id against `src/data/transitFeeds.js`; the browser never supplies a URL, and a feed that is registered but disabled does not resolve at all. Redirects are followed manually and each hop is validated against the feed's own https origin before it is requested, so an off-origin or downgraded hop is refused rather than contacted. Bodies are capped at 8 MB, the protobuf is decoded server-side under entity-count and string-length ceilings, a differential feed is refused, and snapshots live 15 s in memory with no disk cache. A per-feed admission limiter and a failure cooldown ladder bound what this process can ask of any operator.
@@ -98,7 +100,7 @@ The dev server is a **key broker**: every server-side key above is spendable by
- **Local-only by default.** `./scripts/dev-fresh.sh` (and the Vite config itself) bind to `localhost`, so only your machine can reach the server — and only local names are accepted (`allowedHosts` stays restricted, which also blunts DNS-rebinding tricks). Binding to all interfaces keeps that restriction: IP addresses and `localhost` work, and LAN hostnames must be listed in `GEV_ALLOWED_HOSTS` (for example `GEV_ALLOWED_HOSTS=globe.lan`); suffix and wildcard entries are ignored.
- **LAN exposure is an explicit opt-in**: `HOST=0.0.0.0 ./scripts/dev-fresh.sh`. The launcher prints a prominent warning plus your LAN URL. Understand what opting in means: **every device on that network can drive the proxies and spend your OpenAI / Google / OpenSky / AISStream / TomTom / FIRMS quota** for as long as the server runs. Do this only on networks you trust.
- **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). Typed chat keeps its own per-IP window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`; left unset, each takes its provider's resolved cap (`GEV_RATELIMIT_OPENAI_PER_MIN`, or `GEV_RATELIMIT_GEMINI_PER_MIN`, default `30`), so lowering a provider throttle lowers chat too, while an explicit chat value, including `0`, wins. Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**.
- **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). The CCTV Street View fallback has its own per-IP window on `GEV_RATELIMIT_GOOGLE_PER_MIN`, separate from the Places and Geocoding one; over it, a frame gets the placeholder instead of a `429`. Typed chat keeps its own per-IP window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`; left unset, each takes its provider's resolved cap (`GEV_RATELIMIT_OPENAI_PER_MIN`, or `GEV_RATELIMIT_GEMINI_PER_MIN`, default `30`), so lowering a provider throttle lowers chat too, while an explicit chat value, including `0`, wins. Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**.
- **Docker trusts one address, and only because the port is on loopback.**
Docker delivers the host's own browser to the container from the container
network's gateway, never from `127.0.0.1`, so a loopback-only Provider
+6 -4
View File
@@ -55,7 +55,8 @@ function photonEndpointSetting(value) {
* Content-Security-Policy for every document the dev/preview server serves.
* No inline script is permitted, and the only foreign script origins are the
* three that the Bhote Koshi event's embedded media needs (YouTube, Facebook
* and X), which frame-src matches for their players and posts. 'unsafe-eval' is
* and X), which frame-src matches for their players and posts; the stations'
* LIVE video uses the same YouTube player, after the viewer presses Play. 'unsafe-eval' is
* required: Knockout (bundled inside @cesium/widgets) resolves the global
* object with `(0, eval)("this")` at module load, and without it the Cesium
* widget never initializes (verified in headless Chrome). It also covers
@@ -66,9 +67,10 @@ function photonEndpointSetting(value) {
*/
export const BROWSER_CSP = [
"default-src 'self'",
// The Bhote Koshi event's embedded media: the YouTube player API, the
// Facebook video SDK and X's post widget (src/data/bhoteKoshiEmbeddedMedia.js);
// and the Maps JavaScript API that Street Level's Google Street View runs on.
// The Bhote Koshi event's embedded media: the YouTube player API (also the
// stations' LIVE video, src/data/youtubeLivePlayer.js), the Facebook video
// SDK and X's post widget (src/data/bhoteKoshiEmbeddedMedia.js); and the
// Maps JavaScript API that Street Level's Google Street View runs on.
"script-src 'self' 'unsafe-eval' blob: https://www.youtube.com https://connect.facebook.net https://platform.twitter.com https://maps.googleapis.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' data: https://fonts.gstatic.com",
+3
View File
@@ -0,0 +1,3 @@
- Add the Acaray and Yacyretá dams from OpenStreetMap to the Dams layer, and
credit the layer to OpenStreetMap / OpenInfraMap instead of USACE (radianx,
#1152).
+13
View File
@@ -0,0 +1,13 @@
- Refuse Ontario 511 catalog redirects and keep the key-bearing request URL
and upstream error text out of failure logs, which now name only the error
class and system code; release the body of an error response. Credit
Ontario 511 with the Open Government Licence – Ontario attribution statement
(asturksever, #1266).
- Abort the other Tarktee (Estonia) DATEX request as soon as one fails, before
its headers or while its body is read, instead of waiting out the shared
30 s deadline; a response that arrives after the failure is released too.
The Lithuania pack reads its two catalogs through the same helper
(asturksever, #1266).
- Frame the calibration gizmo before the CCTV QA drag regression drags it;
default autofocus could leave the arrow shorter than the 10 px grab
threshold (asturksever, #1266).
@@ -0,0 +1,9 @@
- Keep the phone Cockpit's Display and Radio launchers off the flight
instruments. In the phone layout (720 px wide and below), the collapsed row
of the flight and bridge views now sits centred on the Reset/Exit axis
above the reticle, clear of the destination cue, instead of right-anchored
over the ground speed and altitude readouts. On short landscape phones it
stays on screen and tappable below the vision controls, though it may cover
the top of the readouts. Very short or narrow split-screen windows keep
the old place above Reset/Exit. The first-visit Stories announcement waits until
Cockpit closes (Denis Groshev, @ZloyS, #1549).
@@ -0,0 +1,2 @@
- Stop the browser caching a refused Google Places or Geocoding answer, so a
fixed key works at once (Rudy Celekli, @rudycelekli, #1570).
@@ -0,0 +1,5 @@
- The CCTV Street View fallback answers only for cameras the server lists, at
their catalog position; a request sets only the view. Bundled seed cameras
get the placeholder. A per-IP limit on `GEV_RATELIMIT_GOOGLE_PER_MIN`
(default 120) keeps the Google key from serving as an unmetered Street View
service (asturksever, #1602).
@@ -0,0 +1,5 @@
- Keep the CCTV camera picked with NEAREST, FOCUS or by a scene when it is
the camera CCTV switched to after the view moved. The pick did not stick:
NEAREST's own flight, or the next pan, switched to another camera, so the
panel showed a camera nobody had picked. To keep the camera the list
already shows, press FOCUS (gekh, #1702).
+42
View File
@@ -0,0 +1,42 @@
- Draw the ISS as NASA's 3D model of the current station when the camera is
near it, its moving parts following computed rules: the solar arrays and
radiators by the Sun, the Ku-band dishes toward the relay satellites, the
robotic arms in an illustrative sway. The model draws through the renderer
contract, whose model items gain `nodes` for a model's moving joints
(Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767).
- Draw China's Tiangong station as a 3D model up close, the second station
after the ISS: an original model of the T configuration with a Shenzhou
forward and nadir and a Tianzhou aft, its wings following the Sun, its
antenna aimed at the Tianlian relay satellites and its two arms swaying for
illustration (computed values; China publishes no telemetry). The model
stands in for the dots of the entries docked to it (Denis Groshev, @ZloyS,
#1767).
- Add a STATION section to Context while a space station is selected on the
map: Automatic says where the moving parts' angles come from, Manual offers
Sun positions, array and radiator folding as a labelled demonstration, dish
aim and the arms joint by joint, and Zoom brings the camera to the station.
Selecting a module or a docked vehicle offers it as selecting the station
does (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767).
- Let the ISS model's solar arrays, radiators and Ku-band dish take their
real angles from NASA's public ISSLive telemetry. Off by default: set
`ISS_TELEMETRY_ENABLED=1` and the server relays the feed over one
connection, open only while the model is on screen; without signal the
joints keep their computed rules (Denis Groshev, @ZloyS; Kevin Rajan,
@kvnloo, #1767).
- Add a LIVE section to Context while the ISS is selected: NASA's two live
streams (exterior cameras; live video with space-to-ground audio), stepped
with arrows, in YouTube's embedded player. Nothing loads until you press
Play, under a line saying YouTube sees your IP address, and collapsing the
section stops it. In the Cockpit the same stream is the briefing's fourth
page, LIVE (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767).
- Ride a space station in the Cockpit from views on its model instead of
the straight-down picture: Nauka, Zarya, Poisk, the Cupola, Kibo and a
docked vehicle on the ISS; Tianhe, Wentian, Mengtian and a docked vehicle
on Tiangong. Two arrows step through them, the readout describes the module
each view is from, and leaving selects the station (Denis Groshev, @ZloyS,
#1767).
- Let a click on a mapped installation's label box select the site, as a
click on its 7 px dot does: from orbit the label is what a click lands on.
The label takes a click only where nothing else is drawn under it, so an
aircraft or vessel under a base's label stays selectable (Denis Groshev,
@ZloyS, #1767).
+3
View File
@@ -31,6 +31,8 @@ const ctx = {
toEcef,
assets: {
model: '/models/fleet/aircraft/c172.glb',
// Its one node, which the `nodes` check moves.
modelNode: 'c172',
// Not served: the model failure check loads it.
missingModel: '/models/conformance-missing.glb',
},
@@ -47,6 +49,7 @@ const HARNESSES = {
cesium: () => [
createCesiumHarness({
model: ctx.assets.model,
modelNode: ctx.assets.modelNode,
missingModel: ctx.assets.missingModel,
}),
{ only: (id) => CESIUM_CHECKS.has(id) },
+271 -16
View File
@@ -2025,7 +2025,13 @@ and follows redirects only on the camera's origin. Catalog image URLs, and
redirects on those hosts, are pinned by parsed URL to the agency's image
directory. Every `/api/cctv` route refuses cross-site browser requests but
accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded
request skips the key-bearing Street View fallback and gets the placeholder.
request skips the key-bearing Street View fallback and gets the placeholder. The
fallback answers only for cameras the server lists, at their catalog position,
so position calibration never reaches it. Heading, field of view (clamped to
20–120°) and pitch (clamped to −40–20°) come from the request, else from the
catalog pose. A bundled seed camera, shown when the server catalog is empty,
gets the placeholder. The fallback counts in its own per-IP Google window (see
the cost-bearing proxies below).
The CCTV layer draws only the cameras on or near the screen. Zoomed out, a
ground cell with two or more cameras shows one marker at their mean position. A
@@ -2055,6 +2061,19 @@ in view finishes loading. The camera picker lists the active camera first, then
one camera per visible cell, preferring healthy feeds. It ends with the count of
catalog cameras missing from the list.
Turning CCTV on opens on the camera nearest the view. Until someone picks a
camera, each settled move, such as a shared view's flight landing, moves it to
the camera then nearest the view. Automatic selection ends at the first pick:
NEAREST, PREV or NEXT, FOCUS, a camera chosen in the picker, a click on a
camera, a click on empty ground that deselects, an auto-hop step, or a call to
`selectCamera`, `focusNearest`, `focusNearestToPoint` or
`setParams({ selectedCameraId })`, which voice and scenes use. Picking the
camera that is already active counts. The picker shows the automatic camera
as its own option, and a native list sends no change for the option it
already shows, so the list cannot pick that camera: FOCUS does, and so does
NEAREST when that camera is the nearest. Closing the list without a choice
keeps automatic selection.
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
@@ -2092,6 +2111,213 @@ 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 ISS (NORAD 25544, by number, not name) is drawn as NASA's 3D model within
1,500 km of the camera and as its dot beyond; the two split the distance range,
so exactly one draws (the tracked dot too). The model is at its real 109 m span
with a 72 px floor, flies the station's usual attitude (modules along the
velocity, the same side to the Earth) from its own per-frame SGP4 sample, sits
on the follow camera's sample while tracked, loads only once the ISS is shown,
and hides with the dot's own rules. A click on it tracks the ISS.
The station has several catalog entries that are one body: the ISS itself
(listed as ISS (ZARYA)), ISS (NAUKA) and whatever vehicle is docked, each with
a dot of its own, so a click on the station's dot can land on any of them.
`issTrackedOnStation` (`policy.js`) treats a tracked entry as the station when
it is the ISS or the ISS shares its position (`_dockedCompanions`). For such
an entry the model sits on the tracked entry's own per-frame sample, as it
does for the ISS (drawn from a later sample it stood a frame of orbital
motion, over 100 m, off the camera's centre); its tracked dot and orbit ring
leave the near range to the model, its card keeps clear of the model, and the
command panel and the live video show as they do for the ISS. Such an entry
draws no orbit ring of its own (its elements would put a second line beside
the ISS's through the same station): when tracking judges it docked (both
orbits at one instant within 5 km) the ISS's ring shows for it, even with the
Stations class hidden.
In the Cockpit, a station entry is ridden from the station itself instead of
the straight-down picture: the camera sits at a point on the model
(`issMounts.js`), with the model drawn, and looks out, away from the station.
There are six views, the same whichever entry was selected: from Nauka (the
one it opens on; its lower end, out ahead to port), from Zarya (its port
side, out across the track), from Poisk (its top, out behind to starboard),
from the Cupola (just below it, out aft past the Russian segment), from Kibo
(outside the two windows on its port end, out over the Exposed Facility;
the port solar arrays turn through it as they follow the Sun, as they do past
the real windows)
and, while a vehicle is docked, from that vehicle (behind Zvezda's aft port,
out behind the station; the catalog does not say which port a vehicle is
on). The Cupola and Kibo have no catalog entries: their views ride the ISS's
and show cards of their own (`ISS_MOUNT_CARDS`: the Cupola as ESA's
observation module with 7 windows, launched 8 Feb 2010 on STS-130, on
Tranquility's Earth-facing port; Kibo as JAXA's laboratory module with 2
windows, launched 31 May 2008 on STS-124, on Harmony's port side) in place of
the entry's NORAD number, owner and TLE; altitude, velocity and the
sub-satellite point stay the station's.
Each looks 20° to 30° below level, which keeps the Earth's limb in the frame.
The points were chosen by casting rays across the view against the model at
rest: over a meter clear of every surface, at most a tenth of the frame
meeting the station and none of it nearer than 12 m. The satellites layer's
`getCockpitMount(key)` gives the eye point, the view frame, the view shown,
the catalog entry it belongs to (ISS (NAUKA), the ISS itself for Zarya,
POISK, the docked vehicle) and the views on offer, worked out from the same
sample the model is then placed on, so the camera stays on the model. The
Cockpit rides the view's own entry (`switchOrbitalSatellite`, as riding
another satellite from Live Signals), so the readout, the TLE and the signals
describe the module the view is from; a view whose entry is missing or cannot
be tracked keeps the entry ridden, and is not retried until the view changes.
Leaving the Cockpit from a station view selects Nauka (when the catalog has
it) and puts the follow camera on it, whichever view it ended on; leaving
any other satellite's view refocuses that satellite as before. `cockpitOrbitalView.js` puts the
camera there, turns the arrow-key look about the view's own frame, keeps the
chosen view for the session (also while the model is away) and publishes its
name (`mount`) and the number on offer (`mountViews`). The HUD shows STATION
VIEW with the view's name between two arrows that step back and forth
through them, wrapping round,
and leaves out the nadir reticle, north pointer, swath and sensor strip. A
ground focus (a click on a mapped installation, or its Live Signals row)
works from a station view as from the nadir picture: it aims from the
view's camera point and turns about the view's own frame, with the same
±45° reach, so the sites listed and focusable are those within reach of
where the view looks; their rows still give the angle from straight down.
Switching views ends a focus.
Until the model has loaded, or with the model not shown, the entry keeps the
nadir picture, and the TRACK ACQUIRED line follows the change. Zoom, the
place line and the identity readouts are unchanged.
While the station is selected on the map, Context gains a LIVE section
(`src/ui/liveControls.js`, `LivePanel.vue`, the `gev-live` store): the live
streams attached to the selected object. The list is fixed
(`src/data/liveStreams.js`: NASA's exterior cameras, and its live video with
space-to-ground audio, both on YouTube) and each stream names the subject
keys it belongs to; a layer names its selected subject's keys with
`getLiveSubjectKeys` (the satellites layer answers `station:iss` for the ISS,
Nauka and a docked vehicle, and `station:tiangong` for Tiangong's entries,
which no stream is listed for yet), and the keys are read again every 2 s while
something is selected, since a docked entry is judged so only once both
orbits have been compared. The section shows the subject, the stream's name
with two arrows when there are several, a screen and a status line. It
starts collapsed, and nothing loads on selection: the screen is a poster
with Play, under the line "Video plays from YouTube, which sees your IP
address." Play is the one thing that loads the player:
`youtubeLivePlayer.js` builds YouTube's player (the IFrame API from
`www.youtube.com`, the video on `www.youtube-nocookie.com`), muted, and reads
its state back. Collapsing the section, collapsing or closing Context, or the
section leaving the page removes the player, so nothing plays unseen. ON AIR
with a blinking red dot while it plays; LOADING with an amber dot while it
starts; an offline card ("Stream is offline", with Try again) when
the player reports the video ended, errored or did not start within 25 s,
which is how an off-air broadcast shows, or when YouTube's player API does not
load (Try again loads it afresh); "This stream cannot play here" when the
owner refuses embedding. Stepping to another
stream hands a playing one over; a selection that moves to an object
without that stream, clearing it or turning the layer off removes the
player, while another entry of the same station (a module, a docked vehicle,
the Cockpit stepping between views) keeps it. In the Cockpit the rail is hidden, so the
briefing card gains a fourth page, LIVE (SIG / NEWS / LOCAL / LIVE,
`CockpitLivePage.vue`), with the same subject line, arrows, screen, states
and credit, and the same poster with Play under the IP line; it is offered
only while the ridden subject has a stream, and with none the briefing keeps
its three pages. There is one player: entering or leaving the Cockpit
removes it (an embedded player cannot change parents without reloading, and
the view it was in is hidden), and so does leaving the LIVE page; the view
now shown offers Play again. Previous, Next and the tabs reach the LIVE page;
the automatic 9-second cycle never turns to it and waits while it is shown.
The credit links the owner and the stream's own page.
The model is NASA/JSC IGOAL's current-configuration station, reduced to 3 MB
with its joints kept as nodes (`public/models/README.md`), fetched only once
the camera nears its range, and drawn as an item of a `models` set of the
renderer's draw port, its joints posed through the item's `nodes`.
`issArticulation.js` turns them every frame, by default from computation: the two alpha joints and eight beta joints face
the arrays to the Sun (feathered along the flight direction in the Earth's
shadow, taken as a cylinder), the two radiator joints keep the radiators
edge-on to it, the two Ku-band dishes aim at the highest TDRS nominal slots
(41°W, 171°W, 85°E) above the station's horizon plane, and Canadarm2, Dextre's
arms and the Japanese arm sway a few degrees about NASA's filed pose, which is
illustrative only (no public source gives their real pose; the European arm has
no joints in the file). Joints turn at most 12°/s of wall time. Docked objects
are found by comparing both orbits at one instant, since dots are moved at
different moments. Selecting the station on the map also gives Context a
STATION section (`stationPanel.js` presents it through the `gev-station`
store; `StationPanel.vue` renders it; `issStation.js` describes the ISS, and
another station plugs in with a description of its own): the station's badge
and the selected entry's name, **Automatic** / **Manual**, a status line, and
**Zoom to the ISS** (offered beyond 1 km while the viewer's follow camera is
on the station's entity; it shortens the camera's offset from the station,
a step per frame, to 260 m, and never moves along the view direction, which
ran away when the camera was not looking at the station).
Automatic (the default) leaves the joints to their rules and says where the
angles come from: "Telemetry · updated 4 s ago" with a green dot while the
relay's answer is fresh, "No signal since 12:04 · computed values" when the
feed lost the station, "Telemetry unavailable · last update 3 min ago ·
computed values" when the relay cannot be reached, "Telemetry not enabled on
this server · computed values" when it is switched off, and a lit/shadow
line. Manual pauses telemetry ("Manual · telemetry paused") and offers the
controls: replace the Sun with a chosen position or a 40 s orbit, fold the
arrays and radiators as a labelled demonstration, aim the dishes and pose
Canadarm2 by joint. Automatic, a new selection, the Cockpit (the rail is
hidden there, and the section with it) or turning the layer off hand every
joint back. `issCommand.js` keeps the rules these share (the zoom's range and
step, the fast orbit, the status wording).
With `ISS_TELEMETRY_ENABLED=1` (off by default: the feed publishes no terms)
`server/providers/space/issTelemetry.js` relays NASA's public ISSLive telemetry
at `/api/iss-telemetry`. It speaks Lightstreamer's text protocol over `ws`,
holds one connection for the whole server, opens it on the first request,
closes it after two minutes without one, retries on a 5 s to 5 min ladder and
recycles a socket that is silent for 30 s. The body is
`{ configured, status, generatedAt, items }`: `status` is `live` only while the
station clock ticked with signal in the last 20 s, and each item is
`[value, epoch ms it was true at]`. On a socket loss the relay discards that
connection's joint samples and station-clock credit, so fresh signal after
reconnection cannot present old angles as live telemetry. Unset, the route answers
`{ configured: false }` without contacting the feed, and the browser asks once.
`issTelemetry.js` in the satellites layer polls it every 5 s while the model is
drawn and, in Automatic, replaces the computed targets with the feed's: each
alpha joint its own angle (port `+`, starboard `-`), each beta joint
`±angle + 90°`, each radiator joint its angle, and the first dish the direction
its elevation and cross-elevation give (the second holds still: the feed
reports one dish and not which). The mapping was fitted on a recording of the
feed: the dish direction stayed within 0.3° of a TDRS satellite across a
hand-over, and the arrays sat 5° to 9° off the Sun; the radiator joints did not
move in the recording, so their sign is not fitted. With no relay, no signal,
an answer older than 20 s, Manual, or a Sun chosen by hand, the joints keep the
computed rules, and the STATION section's status line and note say which
holds. The arms still sway for illustration.
Tiangong is the second station, drawn the same way: `stationModel.js` is the
station-independent model part (load on approach, placement from its own SGP4
sample or the tracked entry's, dot and companion hand-over, ring hidden up
close, card anchor and clearance), driven by a spec; `issModel.js` gives the
ISS's and `tiangongModel.js` Tiangong's (`CSS (TIANHE)`, NORAD 48274, with
`CSS (WENTIAN)`, `CSS (MENGTIAN)` and the Shenzhou and Tianzhou ships as its
docked entries). `policy.js` lists both stations (`STATIONS`) and
`stationModels.js` says which station a tracked entry belongs to, so the card,
the detection marks, the LIVE keys, the Cockpit's mounts and the STATION
section work per station rather than for the ISS alone (tracking records
`_trackedDockedToStation`; the ISS's ring keeps its own rules). The model
(`public/models/tiangong.glb`, 382 KB, 26 k triangles) is the project's own,
built from primitives with procedural textures, in meters and in the ISS
file's frame, so it takes the ISS's flight-axes mapping: the station is
assumed to fly with Tianhe along the velocity, the node forward, the labs
across the orbit and nadir to the Earth. `tiangongJoints.js` carries the
file's 37 joint and dock nodes (pivot, axis, kind) and
`tiangongArticulation.js` drives them, all computed, since China publishes no
telemetry: Tianhe's and the ships' one-axis wings turn about their booms to
face the Sun, the lab wings turn about the lab's axis then their own (the
SARJ/BGA pair), in the Earth's shadow every wing turns flat to the Earth
(edge into the flight direction), the high-gain antenna aims at the highest
Tianlian II nominal slot (79.9°E, 171.04°E, 10.5°E) above the horizon plane,
and the two arms sway a few degrees on one side of their folded pose (so they
lift off the hull), at the ISS's 12°/s cap. The STATION section for Tiangong
(`tiangongStation.js`) says "No public telemetry · computed values", offers
the Sun positions and the fast orbit, every wing on a slider of its own
(Tianhe's two; the labs' four, alpha and beta each: a wing set by hand holds
its angle, reached at the joint rate, while the rest keep following the Sun,
and "Follow the Sun" frees them), and the Tianhe and Wentian arms by joint;
**Zoom to Tiangong** uses the ISS's zoom range. In the Cockpit, Tiangong is
ridden from views on its model (`tiangongMounts.js`), as the ISS is: from
Tianhe (the one it opens on; its port side, out across the track), from the
outer end of Wentian and of Mengtian (out past their wings, which turn through
the view as they follow the Sun) and from the docked vehicle (standing in on
the aft port, looking behind the station); each rides its own catalog entry,
so no cards are needed, and leaving selects Tianhe. The visiting ships are
always drawn; they are not yet toggled by what the catalog shows docked.
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
@@ -2815,9 +3041,16 @@ frame the arrows tilt, so the site stays at the centre as the satellite
moves. The turn onto it (and between sites) eases what is left of the swing
with the arrows' easing on a slower clock (250 ms time constant, about
0.75 s to 95%), then holds the site exactly, and cuts under
`prefers-reduced-motion`. A single click on a site's marker focuses it too:
the pick is resolved through the layer's own pick ids (`findByPick`: a named
marker's `{ installationId }` or a site entity). A click anywhere else
`prefers-reduced-motion`. A single click on a site's marker, or on the label
box the overlay paints for it, focuses it too: the click is resolved through
the layer's own lookup (`findAt`: `scene.pick` for a named marker's
`{ installationId }` or a site entity, else the box the overlay painted for
the label; from orbit the dot is 7 px, so the label is what a click lands
on). The map's own click selection reads the label the same way, through a
click claim (`registerClickClaim`) rather than as an interactive card: the
label takes a click only where nothing another layer draws is under it, so
an aircraft or vessel drawn under a base's label stays selectable, and
another layer's card painted over the label keeps its click. A click anywhere else
(a site beyond the reach included), the
focused site's row, NADIR, Home or `0` ends the focus and the view eases
back to nadir on the same clock; an arrow ends it (or the ease back) and
@@ -3579,6 +3812,9 @@ unaffected. `GEV_RATELIMIT_OPENAI_PER_MIN` and `GEV_RATELIMIT_GOOGLE_PER_MIN` ov
those; exactly `0` disables the limiter, while a value that cannot be read as a
number falls back to the default rather than to unlimited. Over-limit requests
receive a sanitized `429` with `Retry-After: 5` and never reach the provider.
The CCTV Street View fallback counts in a separate window with the Google cap.
An IPv6 /64 counts as one client. Over the cap, a frame gets the placeholder
image instead of a `429`.
Typed chat (`/api/openai/chat`, `/api/gemini/chat`) counts in its own window,
set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`.
Left unset, each takes its provider's resolved cap — `GEV_RATELIMIT_OPENAI_PER_MIN`
@@ -5162,9 +5398,20 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
> stacking. Narrow mobile Cockpit
> viewports suppress the legacy layer stack, peripheral HUD, and secondary
> Context/briefing panes so the flight instruments and primary controls remain
> unobstructed. Outside Cockpit, Radio starts collapsed while off and lives
> only in its section inside Context; the detailed panel's normal accordion
> control owns its disclosure and its Enable/Disable action owns power.
> unobstructed. In the phone layout (720 px wide and below) the flight and
> bridge views put the collapsed Display and Radio launchers in one row
> centred on the Reset/Exit axis, above the reticle and clear of the
> destination cue: below the roll arc in portrait, over the arc's lower tick
> ends in landscape. On short landscape screens the row stays
> on screen and tappable below the vision controls but may cover the top of
> the speed and altitude readouts. Windows under 240 px tall, and those under
> 390 px wide and 450 px tall, keep the row above Reset/Exit at the right.
> Satellite and provider views keep the row
> above Reset/Exit at the right, where their own layouts expect it. The
> first-visit Stories announcement waits, unread, until Cockpit closes.
> Outside Cockpit, Radio starts collapsed while off and lives only in its
> section inside Context; the detailed panel's normal accordion control
> owns its disclosure and its Enable/Disable action owns power.
> Radio volume in the full and Cockpit surfaces, plus Space Mission
> replay speed, use Display / Sharpen's muted 3px rail, circular cyan thumb,
> glow, and mono value treatment. Their larger transparent hit areas, keyboard
@@ -7593,7 +7840,7 @@ silently demoting every later lookup for the session.
requires a developer key, so the pack needs `ONTARIO_511_API_KEY` and is skipped without one
(#1228). All sources are RAW PRIOR
poses, and the layer is stills-first.
sources. Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_SOURCES`,
Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_SOURCES`,
kill switch `CCTV_FINTRAFFIC_ENABLED=0`) are the fourth pack: one keyless GeoJSON station list
covering the whole country, where one _preset_ (a station's fixed view) is one camera — 806
GATHERING stations carry 2,256 in-collection presets, prioritized to 300 against seven anchors
@@ -7608,11 +7855,17 @@ silently demoting every later lookup for the session.
empty keeps the old catalog and is retried after another 15 minutes, not on the next
request. Estonia's Tarktee DATEX feeds, which answer in 2 to 16.6 s, get 30 s
(`TARKTEE_FETCH_TIMEOUT_MS`) where other packs get 15 s.
Both Tarktee XML catalogs refuse redirects and have a 4 MiB per-document
limit, enforced against declared length and streamed bytes. A rejected fetch,
unsuccessful response, or body-read failure releases both available response
bodies; read failures also cancel an active sibling reader. Cameras sharing
an image number are deduplicated before the Tarktee pack cap is applied.
Ontario catalog requests refuse redirects and log only the error class and
system code for transport/JSON failures, never the request URL or key.
Both Tarktee XML catalogs share that 30 s deadline, refuse redirects and
have a 4 MiB per-document limit, enforced against declared length and
streamed bytes. A failed request, unsuccessful response or body read aborts
the other feed at once and releases every response body, including one that
arrives after the failure. The Lithuania pack reads its two catalogs
through the same helper (`readCatalogsTogether`,
`server/providers/cctv/catalogPair.js`) with its 15 s deadline. An Ontario
error response has its body released. Cameras sharing an image number are
deduplicated before the Tarktee pack cap is applied.
- **CCTV v3 UX — viewshed + calibration gizmo** (built 2026-07-05 and field
validated 2026-07-21): the COVERAGE toggle is a
tri-state cycle `OFF → ON → VIEWSHED`; viewshed mode renders each visible camera's frustum
@@ -8400,7 +8653,8 @@ Providers normalize coordinates, canonical name, label, place types and optional
bounds. Camera framing, nearby landmark recovery and footprint selection remain
in their consumers, including the Capitol identity/containment safeguards.
Radio keeps localized country names in labels rather than station filters.
Nearby/text-search endpoints retain their existing behavior.
Nearby/text-search cache and error rules are listed under Proxy/Security
Baseline below.
**Google geocoding is a server route, not a browser call** (#363). Forward and
reverse lookups go to `/api/google/geocode` and `/api/google/reverse-geocode`,
@@ -8720,6 +8974,7 @@ apply to `public/` assets or built-preview serving.
- `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/vessels` cache.
- `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context.
- `/api/google/text-search` keeps the Google key server-side for view-biased Places recovery used by annotation resolution.
- The Places and geocode routes cache only an answer (`private, max-age=300`). For geocode, that means an HTTP success with `OK` or `ZERO_RESULTS`, because Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200. Every other reply, including an unreadable Places 200 (now a 502), is `no-store`.
- `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded.
- `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity.
- `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors; routing outages return 502.
@@ -8820,7 +9075,7 @@ apply to `public/` assets or built-preview serving.
The ship bridge and the orbital view have their own own-layer gates
(`bridgeEntryAllowed`, `orbitEntryAllowed`; see
[Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)).
- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical layout), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOURCE} · LAST 24 H` footer; earlier results kept after a failed refresh under `CACHED · REFRESH FAILED` with the cached age in the footer; `NO NEWS IN THE LAST 24 H` when a source answered with nothing Line truncated
- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical layout), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a **cockpit briefing carousel** of three pages: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo; a fourth page, LIVE, is offered while the ridden subject has a live stream (the ISS; see the LIVE section) and shows the same muted player. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus, never turns to the LIVE page and waits while it is shown, and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOLine truncated
- **Cockpit left-panel clearance:** the Cockpit Contact card and peripheral HUD participate in the adaptive left accordion's live obstacle measurements, including live viewport-height changes. Expanding Layers or Authoring keeps the active panel in the available upper-left corridor with internal scrolling; it does not cover the Contact card, lower Cockpit controls, or Cesium credit line. Outside Cockpit the hidden card does not alter the normal corridor.
- **Cockpit Context scope:** the 250 km radius applies to the air/sea proximity cohorts. Installation counts come only from the currently loaded viewport and are labeled `CURRENT VIEWPORT ONLY` in the cockpit as well as the normal Context panel; neither surface presents them as a complete 250 km installation survey.
- **Cockpit camera anchor:** first-person mode does not write feed-boundary corrections directly into the camera. A cockpit-only inertial anchor advances from the selected aircraft's displayed course and speed, then converges toward the authoritative delayed track with correction capped below forward motion. The displayed kinematics are derived from the same consecutive fix segment as the rendered position, with raw feed speed/course used only as fallback; a transient zero/missing feed speed therefore cannot freeze a visibly moving aircraft after layer enable or a map/cockpit handoff. Rendered altitude continues to come from that interpolated track position. Late ADS-B fixes and short render stalls can remove drift without accelerating or reversing the view. Camera placement runs before scene update/culling at a bounded 20 Hz so a moving cockpit does not force Photoreal 3D Tiles to retraverse on every display frame; textual instruments update at 10 Hz and context/layout work at 4 Hz. Every far Cockpit contact pip shares one stable Cesium texture-atlas entry and skips unused screen-projected course calculations, while only in-range 2D aircraft silhouettes pay the screen-projected rotation cost; ambient glTF collections are hidden/retained rather than synchronously destroyed at cockpit entry, and context rails lay out only on explicit content/state changes and viewport resize. The deliberate 15/30-second layer interpolation delays and per-Cesium-frame position caches remain unchanged.
@@ -8831,7 +9086,7 @@ apply to `public/` assets or built-preview serving.
- **Cockpit weather status:** the earlier multi-canvas atmospheric compositor remains fail-closed and is not attached to the live viewer. Cockpit clouds are a separate transparent WebGL pass with a capped 520×320 framebuffer, 24 ray steps, three FBM octaves, and a 12 FPS ceiling. It defaults off and starts only when local storage explicitly contains the persisted `WX ON` opt-in (`'1'`). When opted in, observations refresh after five minutes or 25 km of aircraft movement, fail transparent when unavailable or clear, and stop on exit or disable. `WX OFF` governs atmospheric rendering only: the briefing still fetches source-backed Natural Earth region, headline, and Open-Meteo local-information data, aborting and replacing any in-flight request when the selected aircraft changes. No weather effect runs in map mode and no synthetic fallback is shown.
- **Cockpit trail visibility:** entering cockpit hides the selected aircraft's trail body and head so they cannot cross the first-person view; exit restores them. This cockpit-only presentation change does not alter the normal map-mode invariant that aircraft trails render through terrain using their depth-fail material.
- **Aircraft course slew:** civilian and military 3D models retain the 60°/s course limiter, but each rendered frame can consume at most 250 ms of accumulated slew time. A long tile/render stall therefore catches up over multiple visible frames instead of turning one delayed frame into a heading snap.
- **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode. Live signal data continues refreshing in either state.
- **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel (plus LIVE while the ridden subject has a stream) does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode, and which never turns to the LIVE page. Live signal data continues refreshing in either state.
- **Photoreal horizon blend:** Cesium's sky atmosphere remains enabled behind the hidden base globe, but its light intensity, saturation, and brightness are reduced from the library defaults so the distant Google Photorealistic 3D Tiles boundary blends into the sky instead of producing a bright cyan horizon seam.
- **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter.
- Voice control UI (`#gev-voice-control`) shows status states OFF / CONNECTING / LISTENING / EXECUTING / ERROR.
+2 -2
View File
@@ -83,6 +83,6 @@ 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. A multipart
Their input counts are 4,352 datacenter features and 706 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.
different measurements from feature counts.
+11
View File
@@ -343,6 +343,17 @@ correction turns them to, paints the mask in a custom shader per colour
clipping plane through the model's origin. The checks `draw.models.bytes`
and `draw.models.fleet` cover them.
An articulated model's joints are its item's `nodes`: transforms of the
model's named glTF nodes, each a column-major 4×4 matrix in the node's
parent frame that replaces the node's own (the ISS's solar arrays,
radiators, dishes and arms). They change live; a node whose name leaves the
map goes back to its authored pose, and names the model lacks are ignored.
A renderer that poses nodes lists `modelNodes`; one without it draws the
model as authored. The Cesium port lists it, and writes each node's matrix
once the model is ready, and again only when its numbers change. The check
`draw.models.nodes` moves the harness model's node off the screen's centre
and back.
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
+79 -2
View File
@@ -1,11 +1,13 @@
# Bundled 3D Models
Every 3D model shipped in this directory is one of the project's procedural
Every 3D model shipped in this directory but two 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.
like the source code. The exceptions are the two space stations: NASA's model
of the ISS, described in [its own section](#the-iss-model-issglb) below, and
the project's own Tiangong model, [after it](#the-tiangong-model-tiangongglb).
| Path | What it holds |
|---|---|
@@ -37,3 +39,78 @@ How the layers use them:
`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.
## The ISS model (`iss.glb`)
Two models sit outside the fleet set. The first is `iss.glb`, the International
Space Station drawn by the satellites layer up close. It is not procedural and not
covered by the MIT license. It is NASA's own model of the station, which is
not subject to copyright in the United States
([NASA Images and Media Usage Guidelines](https://www.nasa.gov/nasa-brand-center/images-and-media));
its use does not imply endorsement by NASA. It loads only when the camera
nears the station.
- **Original work:** “International Space Station (ISS) (D) (IGOAL)”, NASA
Johnson Space Center, Integrated Graphics, Operations and Analysis
Laboratory, on
[NASA 3D Resources](https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/).
- **Reduction:** from the 96 MB original (2.7 M triangles) to 3 MB (314 k
triangles): handrails left out; geometry simplified within 15 cm
(structure) or 40 cm (small details) of the original surface, normals
rebuilt; normal maps dropped; textures resized to 512 px WebP;
Draco-compressed.
- **Frame:** every part is baked into one frame in meters (glTF +Y zenith,
+X port, +Z forward), and the scene root moves the bounding-box centre to
the origin.
- **Corrections:** NASA's file is a mirror image of the station (port and
starboard swapped), which is undone; 15 materials NASA marks as blended
are made opaque, because blended they draw see-through.
- **Marks on the textures:** the station's textures carry the marks it flies
with: the NASA insignia and the ESA, Columbus, JAXA and Nanoracks marks on
the partners' modules. They are kept as flown, to show the station as it
is; their presence implies no endorsement by NASA or by any partner.
- **Moving parts:** parts that move stay separate nodes at the joints NASA
names (two alpha joints, eight array beta joints, two radiator joints,
Canadarm2's seven joints, two joints on each Dextre arm, three on the
Japanese arm). The two Ku-band dishes and three of the four power-module
radiators, welded into the truss in NASA's file, are cut out by position.
## The Tiangong model (`tiangong.glb`)
The second model outside the fleet set is `tiangong.glb`, China's Tiangong
station in its T configuration (Tianhe, Wentian, Mengtian, a Shenzhou forward
and nadir, a Tianzhou aft), drawn by the satellites layer up close. It is an
original model made for God's Eye View and, unlike the ISS model, it is the
project's own work under the repository's [MIT license](../../LICENSE): no
third-party geometry, texture or image is in it. It loads only when the camera
nears the station.
- **Built:** in Blender 5.3 from primitives only (cylinders, cones, spheres,
tori, boxes), every texture generated procedurally by the build script,
[`scripts/build-tiangong-model.py`](../../scripts/build-tiangong-model.py)
(`blender -b --python scripts/build-tiangong-model.py -- <out_dir>`).
26,460 triangles, 12 materials, 15 WebP textures (`EXT_texture_webp`),
Draco-compressed, 382 KB.
- **Dimensions, as published:** Wang, Zhang & Wang 2023, "Design and
Application Prospect of China's Tiangong Space Station", *Space: Science &
Technology*, [doi:10.34133/space.0035](https://doi.org/10.34133/space.0035)
(CC BY 4.0), and [eoPortal's Tiangong page](https://www.eoportal.org/satellite-missions/tiangong):
Tianhe 16.6 m × 4.2 m with its port layout; Wentian and Mengtian 17.9 m ×
4.2 m, one each side of the node; lab wings 27 × ~4 m, two per lab,
two-axis; Tianhe wings 12.6 m per wing (the paper's figure; eoPortal gives
a 60 m total span), one-axis; the Tianhe arm ~10 m and the Wentian arm
~5 m, seven joints each; Shenzhou 9.25 × 2.8 m (17 m span), Tianzhou
10.6 × 3.35 m (14.9 m span) and their docking ports.
- **Approximate (the author's estimates):** the node sphere, small-cylinder
and resource-section diameters, section lengths and cones, hatch and port
tubes; wing widths, root offsets, masts and drive housings; the airlocks,
radiators, high-gain antenna and node antennas; both arms entirely (bases,
booms, joint spacing, rest pose); the ships' module proportions and arrays.
- **Frame:** meters, glTF +X port, +Y zenith, +Z forward (the ISS file's);
the scene root `tiangong` is translated so the station's bounding-box
centre (without the ships) is at the origin.
- **Moving parts:** joints are nodes with identity rest transforms and the
pivot, axis, kind and range in their `extras` (also in
`src/layers/satellites/tiangongJoints.js`): two Tianhe wing drives, four
lab wing alpha + beta pairs, the antenna gimbal, seven joints per arm, two
drives per ship, six dock markers.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
+31 -1
View File
@@ -148,6 +148,7 @@
"server/providers/cctv/groundHeights.js",
"server/providers/cctv/catalog.js",
"server/providers/cctv/lithuania.js",
"server/providers/cctv/catalogPair.js",
"src/data/cctvLithuania.test.mjs",
"server/providers/cctv/taiwan.js",
"src/data/cctvTaiwan.test.mjs",
@@ -1662,5 +1663,34 @@
"src/layers/firms/selection.test.mjs",
"src/layers/vessels/selection.test.mjs",
"src/layers/bikeshare/selection.test.mjs",
"src/layers/satellites/interaction.test.mjs"
"src/layers/satellites/interaction.test.mjs",
"server/providers/space/issTelemetry.test.mjs",
"src/data/liveStreams.test.mjs",
"src/data/youtubeLivePlayer.test.mjs",
"src/data/youtubeApi.test.mjs",
"src/layers/installations/labelBoxClick.test.mjs",
"src/layers/satellites/cockpitSubject.test.mjs",
"src/layers/satellites/issArticulation.test.mjs",
"src/layers/satellites/issCommand.test.mjs",
"src/layers/satellites/issModel.test.mjs",
"src/layers/satellites/issMounts.test.mjs",
"src/layers/satellites/issTelemetry.test.mjs",
"src/layers/satellites/offCesium.test.mjs",
"src/layers/satellites/stationModel.test.mjs",
"src/layers/satellites/stationModels.test.mjs",
"src/layers/satellites/stationPanel.test.mjs",
"src/layers/satellites/stationResume.test.mjs",
"src/layers/satellites/tiangongArticulation.test.mjs",
"src/layers/satellites/tiangongModel.test.mjs",
"src/layers/satellites/tiangongMounts.test.mjs",
"src/layers/satellites/tiangongStation.test.mjs",
"src/render/cesium/draw.test.mjs",
"src/ui/cockpitBriefing.test.mjs",
"src/ui/cockpitOrbitalFocus.test.mjs",
"src/ui/cockpitOrbitalView.test.mjs",
"src/ui/liveControls.test.mjs",
"src/ui/livePanel.test.mjs",
"src/ui/stationPanel.test.mjs",
"src/ui/styles/live.css",
"src/ui/styles/station.css"
]
+2
View File
@@ -649,6 +649,8 @@ const ZH_HANT_CORRECTIONS = [
['箇中', '個中'],
// 周 as a week: the time-lapse speed in weeks per second.
[' 周/秒', ' 週/秒'],
// 后 as "behind" after a module name (问天, 梦天), not 天后 (empress).
['天后側', '天後側'],
];
let s2tw;
+75 -7
View File
@@ -315,7 +315,13 @@
"src/search/gridReference.js",
"src/search/coordinateParser.js",
"src/search/placeSuggestions.js",
"src/search/bip39Words.js"
"src/search/bip39Words.js",
"src/ui/stores/station.js",
"src/ui/views/panels/StationPanel.vue",
"src/ui/stores/live.js",
"src/ui/views/panels/LivePanel.vue",
"src/ui/views/panels/CockpitLivePage.vue",
"src/ui/liveScreen.js"
],
"external": ["vue", "pinia", "vue-i18n"]
},
@@ -565,6 +571,7 @@
"server/providers/cctv/groundHeights.js",
"server/providers/cctv/catalog.js",
"server/providers/cctv/lithuania.js",
"server/providers/cctv/catalogPair.js",
"server/providers/cctv/taiwan.js",
"server/providers/cctv/quebec.js",
"server/providers/cctv/ottawa.js",
@@ -583,7 +590,9 @@
"src/data/cctvFootprint.js",
"src/sources/cctvTypes.js",
"src/sources/httpBody.js",
"src/i18n/marker.js"
"src/i18n/marker.js",
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js"
],
"external": []
},
@@ -1291,7 +1300,9 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1694,7 +1705,15 @@
"src/data/trackingClickGesture.js",
"src/ui/stores/sceneSharing.js",
"src/maps/attribution.js",
"src/data/dataCredits.js"
"src/data/dataCredits.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/ui/stores/station.js",
"src/ui/stores/live.js",
"src/data/liveStreams.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js"
],
"external": [
"cesium",
@@ -2859,7 +2878,21 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/layers/satellites/issModel.js",
"src/layers/satellites/issTelemetry.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/layers/satellites/issArticulation.js",
"src/layers/satellites/issCommand.js",
"src/layers/satellites/stationPanel.js",
"src/layers/satellites/issStation.js",
"src/layers/satellites/stationModels.js",
"src/layers/satellites/stationModel.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
],
"external": ["cesium", "satellite.js", "kdbush"]
},
@@ -5541,7 +5574,27 @@
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/data/locate.js",
"src/render/cesium/cardPreviews.js"
"src/render/cesium/cardPreviews.js",
"src/layers/satellites/issModel.js",
"src/layers/satellites/issTelemetry.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/layers/satellites/issArticulation.js",
"src/layers/satellites/issCommand.js",
"src/ui/stores/live.js",
"src/ui/stores/station.js",
"src/data/liveStreams.js",
"src/layers/satellites/stationPanel.js",
"src/layers/satellites/issStation.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js",
"src/layers/satellites/stationModels.js",
"src/layers/satellites/stationModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
],
"external": [
"hls.js",
@@ -6382,7 +6435,22 @@
"src/data/placementProvider.js",
"src/data/courseFromFixes.js",
"src/time/frameWait.js",
"src/maps/attribution.js"
"src/maps/attribution.js",
"src/layers/satellites/issModel.js",
"src/layers/satellites/issTelemetry.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/layers/satellites/issArticulation.js",
"src/layers/satellites/issCommand.js",
"src/data/youtubeApi.js",
"src/layers/satellites/stationPanel.js",
"src/layers/satellites/issStation.js",
"src/layers/satellites/stationModels.js",
"src/layers/satellites/stationModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js"
],
"external": [
"hls.js",
+37
View File
@@ -1790,6 +1790,43 @@ async function main() {
gizmoStates.map((s, i) => `${GIZMO_PARTS[i]}=${s}`).join(' '),
);
// Frame the actual gizmo for the drag fixture. Default autofocus can leave
// its shaft below the 10px interaction threshold; that distant view is not
// the drag-usability scenario this regression exercises. The gizmo is drawn
// through the renderer ports, so its arrow is read from the layer's drawn
// state (plain {x,y,z} points), not from viewer.entities.
const dragFraming = await page.evaluate(async () => {
const viewer = window.__godsEyeView.viewer;
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
const arrow = () =>
mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east']?.positions;
if (!arrow()?.length) return null;
const Cartesian3 = viewer.camera.positionWC.constructor;
const measure = () => {
const pts = arrow();
if (!pts?.length) return { shaftPx: null, rangeM: null };
const a = viewer.scene.cartesianToCanvasCoordinates(pts[0]);
const b = viewer.scene.cartesianToCanvasCoordinates(pts[pts.length - 1]);
return {
shaftPx: a && b ? Math.hypot(b.x - a.x, b.y - a.y) : null,
rangeM: Cartesian3.distance(viewer.camera.positionWC, pts[0]),
};
};
const before = measure();
const target = Cartesian3.clone(arrow()[0]);
viewer.camera.cancelFlight();
viewer.camera.lookAt(target, new Cartesian3(0, -200, 180));
viewer.camera.lookAtTransform(viewer.camera.transform.constructor.IDENTITY);
viewer.scene.requestRender();
const frames = await window.__qaRenderFrames(3, 10000);
return { before, after: measure(), frames };
});
record(
'drag fixture frames the east arrow above the 10px grab threshold',
dragFraming?.after?.shaftPx >= 10,
JSON.stringify(dragFraming),
);
// Synthetic CDP drag on the EAST arrow — the owner's field-test
// regression. Sample effective elevation after every mouse move: it must
// stay frozen until release, with no transient sampleHeight calls.
+148
View File
@@ -2050,6 +2050,151 @@ try {
JSON.stringify(narrowViewActions),
);
// A fresh profile has not seen the Stories announcement: Cockpit keeps
// it unread and off the phone row until it closes.
const storiesPopupDisplay = () => {
const popup = document.getElementById('hPop');
return popup ? getComputedStyle(popup).display : null;
};
const storiesPopupInCockpit = await page.evaluate(storiesPopupDisplay);
check('the unread Stories announcement waits while Cockpit is open',
storiesPopupInCockpit === 'none', String(storiesPopupInCockpit));
// Windows too short for the centred row keep it above Reset/Exit.
for (const [width, height] of [[360, 370], [320, 360], [568, 188], [667, 190]]) {
await page.setViewport({ width, height, deviceScaleFactor: 1 });
const glyphHits = await page.evaluate(async () => {
const manager = window.__godsEyeView.styleManager;
manager._setCockpitDisclosure('display', false);
manager._setCockpitDisclosure('radio', false);
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
return [...document.querySelectorAll(
'#cockpit-utility-controls .cockpit-utility-glyph',
)].map((glyph) => {
const box = glyph.getBoundingClientRect();
const target = document.elementFromPoint(
box.left + box.width / 2,
box.top + box.height / 2,
);
return target && glyph.contains(target) ? 'ok' : target?.closest('[id]')?.id || null;
});
});
check(
`${width}×${height} Cockpit Display/Radio glyph centres reach their own launchers`,
glyphHits.length === 2 && glyphHits.every((hit) => hit === 'ok'),
JSON.stringify(glyphHits),
);
}
// The phone row's place in each room: centred on Reset/Exit, on screen,
// tappable, and clear of what that room has space to clear.
for (const [width, height, room] of [
[360, 740, 'portrait'],
[720, 360, 'landscape'],
[667, 240, 'short'],
[390, 844, 'portrait'],
]) {
await page.setViewport({ width, height, deviceScaleFactor: 1 });
const phoneRow = await page.evaluate(async () => {
const manager = window.__godsEyeView.styleManager;
manager._setCockpitDisclosure('display', false);
manager._setCockpitDisclosure('radio', false);
await new Promise(requestAnimationFrame);
manager.cockpitView.syncSignalLayout();
await new Promise(requestAnimationFrame);
const rect = (element) => element?.getBoundingClientRect().toJSON() || null;
const hud = (selector) => document.querySelector(`#cockpit-hud ${selector}`);
const route = document.getElementById('cockpit-route-direction');
// A live flight may have no route, which hides the DEST cue. Show it while
// measuring so the clearance check always has a cue to clear.
const wasHidden = route.hidden;
try {
route.hidden = false;
const controls = [...document.querySelectorAll(
'#cockpit-utility-controls .cockpit-utility-control',
)];
const launchers = controls.map(rect);
const rowLeft = Math.min(...launchers.map((launcher) => launcher.left));
const rowRight = Math.max(...launchers.map((launcher) => launcher.right));
// Taps beside the row reach what is under it.
const besideHits = [];
if (launchers.length) {
const middle = launchers[0].top + launchers[0].height / 2;
for (const x of [rowLeft - 8, rowRight + 8]) {
const target = document.elementFromPoint(x, middle);
besideHits.push(Boolean(target?.closest('#cockpit-utility-controls')));
}
}
return {
launchers,
rowLeft,
rowRight,
besideHits,
hits: controls.map((control) => {
const glyph = control.querySelector('.cockpit-utility-glyph');
const box = glyph?.getBoundingClientRect();
const target = box && document.elementFromPoint(
box.left + box.width / 2,
box.top + box.height / 2,
);
return Boolean(target && glyph.contains(target));
}),
speed: rect(hud('.cockpit-speed')),
altitude: rect(hud('.cockpit-altitude')),
route: rect(route),
chevron: rect(route.querySelector('.cockpit-route-chevron')),
reticle: rect(hud('.cockpit-reticle')),
rollArc: rect(hud('.cockpit-roll-arc')),
vision: rect(hud('.cockpit-vision-controls')),
switcher: rect(document.getElementById('view-switcher')),
viewport: { width: innerWidth, height: innerHeight },
};
} finally {
route.hidden = wasHidden;
}
});
const obstacles = {
portrait: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'rollArc', 'vision'],
// The row covers the roll arc's lower tick ends; ticks and labels stay readable.
landscape: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'vision'],
// No free band between the instruments: only the vision controls.
short: ['vision'],
}[room];
const overlaps = (a, b) => Boolean(a && b)
&& a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
const { rowLeft, rowRight } = phoneRow;
const switcherCentre = (phoneRow.switcher?.left + phoneRow.switcher?.right) / 2;
const [first, second] = phoneRow.launchers;
check(
`${width}×${height} Cockpit Display/Radio row is centred in one line, on screen, tappable and clear of ${obstacles.join(', ')}`,
phoneRow.launchers.length === 2
&& phoneRow.launchers.every((launcher) => launcher.width > 0)
&& phoneRow.speed?.width > 0
&& phoneRow.altitude?.width > 0
&& (room === 'short' || (phoneRow.route?.width > 0 && phoneRow.chevron?.width > 0))
&& phoneRow.hits.every(Boolean)
&& phoneRow.besideHits.every((inside) => !inside)
&& Math.abs((first?.top + first?.bottom) / 2 - (second?.top + second?.bottom) / 2) <= 1
&& phoneRow.launchers.every((launcher) => obstacles.every(
(name) => !overlaps(launcher, phoneRow[name]),
))
&& Math.abs((rowLeft + rowRight) / 2 - switcherCentre) <= 2
&& rowLeft >= 0
&& rowRight <= phoneRow.viewport.width
&& phoneRow.launchers.every((launcher) => (
launcher.top >= 0 && launcher.bottom <= phoneRow.viewport.height
)),
JSON.stringify(phoneRow),
);
}
// A Stories tap that Cockpit refuses leaves the announcement unread.
await page.evaluate(() => document.getElementById('hStories').click());
await page.waitForFunction(
() => document.querySelector('#toast.visible')?.textContent === 'Exit cockpit to open Stories',
);
const resetResult = await page.evaluate(() => {
// Both the UI and compatibility facade delegate to this navigation owner.
const manager = window.__godsEyeView.styleManager._locationNavigation;
@@ -2121,6 +2266,9 @@ try {
&& resetState.visionRestored,
JSON.stringify(resetState),
);
const storiesPopupAfterReset = await page.evaluate(storiesPopupDisplay);
check('the Stories announcement returns once Cockpit closes',
storiesPopupAfterReset !== null && storiesPopupAfterReset !== 'none', String(storiesPopupAfterReset));
check('runtime console remains clean', consoleErrors.length === 0 && localHttpErrors.length === 0,
[...localHttpErrors, ...consoleErrors].slice(0, 6).join(' | '));
} finally {
+36 -13
View File
@@ -21,8 +21,13 @@ import { PROXY_SIGNALS } from '../../src/localRequestGate.mjs';
import { createHlsPuller } from './cctv/stream.js';
import { isMlitRiverAdjustmentImage } from './cctv/worldCameras.js';
import { ottawaAuthorizedFrameUrl } from './cctv/ottawa.js';
import { googleServerApiKey } from './places/google-key.js';
import {
GOOGLE_DEFAULT_PER_MIN,
googleServerApiKey,
} from './places/google-key.js';
import { clientNetworkKey, makeCostRateLimiter } from './common/rate-limit.js';
export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream };
/**
* Vite plugin: CCTV camera proxy with source registry, frame/media serving,
* fallback chain (upstream -> Street View -> synthetic SVG), and health tracking.
@@ -198,17 +203,31 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
};
};
let streetViewBudget; // undefined = not built yet; null = the explicit 0 opt-out
/**
* Fetch a Google Street View static image as a fallback frame. Server-side
* call, never reaches the browser — prefers GOOGLE_MAPS_SERVER_API_KEY
* (#33: a key scoped to Street View Static/Places, restricted by server IP
* rather than HTTP referrer) and falls back to the browser-exposed
* GOOGLE_MAPS_API_KEY for setups that haven't split the two yet.
* Each IP (or IPv6 /64) has its own GEV_RATELIMIT_GOOGLE_PER_MIN window,
* separate from Places. Setting it to 0 disables the limit.
*/
const streetViewFallback = async ({ lat, lon, heading, fov, pitch }) => {
const streetViewFallback = async (
client,
{ lat, lon, heading, fov, pitch },
) => {
const streetViewKey = googleServerApiKey();
if (!streetViewKey || !Number.isFinite(lat) || !Number.isFinite(lon))
return null;
// Built on first use, after the standalone env has loaded.
if (streetViewBudget === undefined)
streetViewBudget = makeCostRateLimiter(
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
GOOGLE_DEFAULT_PER_MIN,
);
if (streetViewBudget && !streetViewBudget(client)) return null;
try {
const sv = new URL('https://maps.googleapis.com/maps/api/streetview');
sv.searchParams.set('size', '960x540');
@@ -264,6 +283,8 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
// keyless gate keeps the routes reachable behind a reverse proxy; the
// key-bearing Street View fallback below has its own check.
if (admitSameSiteKeyless(req, res)) return;
// Read before any await: a socket the client has closed has no address.
const client = clientNetworkKey(req);
const sources = await getCctvSources();
const sourceById = new Map(
sources.map((source) => [source.id, source]),
@@ -635,8 +656,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
const source = sourceById.get(cameraId);
const label = url.searchParams.get('label') || source?.name || cameraId;
const city = url.searchParams.get('city') || source?.city || '';
const lat = Number(url.searchParams.get('lat') || source?.lat);
const lon = Number(url.searchParams.get('lon') || source?.lon);
// The query sets only the view, the pose the browser draws.
const heading = Number(
url.searchParams.get('heading') || source?.headingDeg,
);
@@ -731,18 +751,21 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
// request (whose client this server cannot see) gets the placeholder,
// as if no key were configured. Any forwarding header counts, even an
// empty one.
// It also answers only for catalog cameras, at the catalog position;
// the query never sets the location.
const forwarded = PROXY_SIGNALS.some(
(name) => req.headers?.[name] !== undefined,
);
const sv = forwarded
? null
: await streetViewFallback({
lat,
lon,
heading,
fov,
pitch,
});
const sv =
forwarded || !source
? null
: await streetViewFallback(client, {
lat: source.lat,
lon: source.lon,
heading,
fov,
pitch,
});
if (sv?.ok) {
setHealth(cameraId, {
status: 'degraded',
+53
View File
@@ -0,0 +1,53 @@
import { readResponseTextCapped } from '../common/http.js';
/**
* Read catalogs that are only useful together, because the pack joins them.
*
* The requests share one deadline and refuse redirects. Whichever fails first
* (before its headers, on its status, or while its capped body is read or
* parsed) aborts the others at once, so a stalled feed is not waited on until
* the deadline. Every response body is released, including one that arrives
* after another feed has already failed.
*
* @param {Array<{url: string, label: string}>} feeds `label` names the feed
* in the error ("locations download failed: 503").
* @param {{accept: string, maxBytes: number, timeoutMs: number,
* parse?: (text: string) => unknown}} options
* @returns {Promise<unknown[]>} The parsed bodies (texts without `parse`), in
* feed order.
*/
export async function readCatalogsTogether(
feeds,
{ accept, maxBytes, timeoutMs, parse = (text) => text },
) {
const sibling = new AbortController();
const signal = AbortSignal.any([
sibling.signal,
AbortSignal.timeout(timeoutMs),
]);
return Promise.all(
feeds.map(async ({ url, label }) => {
let response;
try {
response = await fetch(url, {
headers: { Accept: accept },
redirect: 'manual',
signal,
});
signal.throwIfAborted();
if (!response.ok) {
throw new Error(
response.status >= 300 && response.status < 400
? `${label} catalog redirected; redirects are not followed`
: `${label} download failed: ${response.status}`,
);
}
return parse(await readResponseTextCapped(response, maxBytes, signal));
} catch (error) {
sibling.abort();
await response?.body?.cancel().catch(() => {});
throw error;
}
}),
);
}
+13 -38
View File
@@ -4,7 +4,7 @@ import {
fallbackHeadingFromId,
prioritizeSources,
} from './normalize.js';
import { readResponseJsonCapped } from '../common/http.js';
import { readCatalogsTogether } from './catalogPair.js';
const BASE = 'https://eismoinfo.lt/eismoinfo-backend';
export const LITHUANIA_CAMERAS_URL = `${BASE}/camera-info-table`;
@@ -81,46 +81,21 @@ export function lithuaniaCameraToSource(row, feature) {
};
}
async function readCatalog(url, sibling) {
const signal = AbortSignal.any([
AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
sibling.signal,
]);
try {
const response = await fetch(url, {
headers: { Accept: 'application/json' },
redirect: 'manual',
signal,
});
if (!response.ok) {
await response.body?.cancel().catch(() => {});
throw new Error(
response.status >= 300 && response.status < 400
? 'catalog redirected; redirects are not followed'
: `Catalog HTTP ${response.status}`,
);
}
return await readResponseJsonCapped(
response,
LITHUANIA_MAX_CATALOG_BYTES,
signal,
);
} catch (error) {
// The join needs both catalogs; release the other request at once
// rather than leaving its body open until the timeout.
sibling.abort();
throw error;
}
}
/** Two bounded requests per shared catalog refresh, no API key required. */
export async function loadLithuaniaSources() {
try {
const sibling = new AbortController();
const [rows, layers] = await Promise.all([
readCatalog(LITHUANIA_CAMERAS_URL, sibling),
readCatalog(LITHUANIA_LOCATIONS_URL, sibling),
]);
const [rows, layers] = await readCatalogsTogether(
[
{ url: LITHUANIA_CAMERAS_URL, label: 'cameras' },
{ url: LITHUANIA_LOCATIONS_URL, label: 'locations' },
],
{
accept: 'application/json',
maxBytes: LITHUANIA_MAX_CATALOG_BYTES,
timeoutMs: CCTV_SOURCE_FETCH_TIMEOUT_MS,
parse: JSON.parse,
},
);
if (!Array.isArray(rows) || !Array.isArray(layers)) return [];
const features = layers.find((layer) => layer?.layer === 'VKR')?.features;
if (!Array.isArray(features)) return [];
+92
View File
@@ -127,3 +127,95 @@ for (const status of [429, 500, 503]) {
assert.doesNotMatch(lines[0], /secret-key-value/);
});
}
for (const failure of ['transport', 'invalid-json']) {
test(`Ontario ${failure} failures cannot log reflected keys or request URLs`, async (t) => {
const lines = captureConsole(t);
const key = 'synthetic secret&/=%value';
t.mock.method(globalThis, 'fetch', async (url) => {
if (failure === 'transport')
throw new Error(`request failed: ${url} ${key}`);
return new Response(`not JSON: ${url} ${key}`);
});
assert.deepEqual(
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: key }),
[],
);
assert.equal(lines.length, 1);
assert.match(lines[0], /Ontario 511 camera download error/);
assert.equal(lines[0].includes(key), false);
assert.equal(lines[0].includes('synthetic'), false);
assert.equal(lines[0].includes('https://'), false);
});
}
test('Ontario encodes reserved key characters and refuses credential-bearing redirects', async (t) => {
const lines = captureConsole(t);
const key = 'synthetic &/=% value';
let request;
t.mock.method(globalThis, 'fetch', async (url, init) => {
request = { url: new URL(url), init };
return Response.json([ROW]);
});
const cameras = await loadOntarioSourcesFromOpenData(
{},
{ ONTARIO_511_API_KEY: key },
);
assert.equal(request.url.searchParams.get('key'), key);
assert.equal(request.init.redirect, 'error');
assert.equal(cameras.length, 1);
assert.equal(JSON.stringify(cameras).includes('synthetic'), false);
assert.equal(lines.join(' ').includes('synthetic'), false);
});
test('Ontario names a refused redirect and a system code without the request text', async (t) => {
const lines = captureConsole(t);
const key = 'synthetic-secret';
const failures = [
// The shape Node's fetch gives a refused redirect and a DNS failure.
new TypeError('fetch failed', {
cause: new Error('unexpected redirect'),
}),
new TypeError('fetch failed', {
cause: Object.assign(new Error(`getaddrinfo ENOTFOUND ${key}`), {
code: 'ENOTFOUND',
}),
}),
];
t.mock.method(globalThis, 'fetch', async () => {
throw failures.shift();
});
for (let i = 0; i < 2; i++) {
assert.deepEqual(
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: key }),
[],
);
}
assert.deepEqual(lines, [
'[CCTV] Ontario 511 camera download error (TypeError, redirect refused)',
'[CCTV] Ontario 511 camera download error (TypeError ENOTFOUND)',
]);
});
test('Ontario releases the body of an error response', async (t) => {
captureConsole(t);
let cancelled = false;
t.mock.method(
globalThis,
'fetch',
async () =>
new Response(
new ReadableStream({
cancel() {
cancelled = true;
},
}),
{ status: 503 },
),
);
assert.deepEqual(
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: 'k' }),
[],
);
assert.equal(cancelled, true);
});
+34 -70
View File
@@ -43,6 +43,7 @@ import {
TARKTEE_IMAGE_ORIGIN,
DEFAULT_TARKTEE_MAX_SOURCES,
TARKTEE_MAX_CATALOG_BYTES,
TARKTEE_FETCH_TIMEOUT_MS,
TARKTEE_ANCHORS,
DEFAULT_WARENDORF_SOURCE_FILE,
WARENDORF_IMAGE_ORIGINS,
@@ -82,7 +83,6 @@ import {
HK_ANCHORS,
HK_MAX_CATALOG_BYTES,
CCTV_SOURCE_FETCH_TIMEOUT_MS,
TARKTEE_FETCH_TIMEOUT_MS,
DELDOT_CCTV_URL,
DEFAULT_DELDOT_MAX_SOURCES,
DELDOT_ANCHORS,
@@ -172,6 +172,7 @@ import {
pinnedCameraUrl,
} from './normalize.js';
import { directionToHeading } from '../../../src/data/directionText.js';
import { readCatalogsTogether } from './catalogPair.js';
import {
readResponseBytesCapped,
readResponseJsonCapped,
@@ -561,6 +562,22 @@ export function _resetOntarioKeyWarningForTest() {
ontarioKeyMissingLogged = false;
}
/**
* What failed in an Ontario download, without upstream text: the error class,
* plus the system code (`ENOTFOUND`) or a refused redirect when there is one.
* @param {unknown} error
* @returns {string}
*/
function ontarioFailureKind(error) {
const name = /^[A-Za-z]{1,40}$/.test(error?.name) ? error.name : 'Error';
if (error?.cause?.message === 'unexpected redirect')
return `${name}, redirect refused`;
const code = error?.cause?.code;
return typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,40}$/.test(code)
? `${name} ${code}`
: name;
}
/**
* Fetch Ontario 511 CCTV cameras. The camera list comes from the 511 API,
* which now requires a free developer key (511on.ca/developers/doc, "Requires a
@@ -593,6 +610,7 @@ export async function loadOntarioSourcesFromOpenData(
url.searchParams.set('key', key);
const resp = await fetch(url, {
headers: { Accept: 'application/json' },
redirect: 'error',
signal: AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
});
if (!resp.ok) {
@@ -604,6 +622,7 @@ export async function loadOntarioSourcesFromOpenData(
console.warn(
`[CCTV] Ontario 511 camera download failed: ${resp.status}${keyHint}`,
);
await resp.body?.cancel().catch(() => {});
return [];
}
const rows = await resp.json();
@@ -658,7 +677,7 @@ export async function loadOntarioSourcesFromOpenData(
url: view.url,
snapshotUrl: view.url,
sourceKind: 'ontario-511-open-data',
license: 'Open Government Licence - Ontario',
license: 'Open Government Licence – Ontario',
});
}
@@ -677,9 +696,10 @@ export async function loadOntarioSourcesFromOpenData(
);
return prioritized;
} catch (error) {
// Transport and JSON errors may reflect the credential-bearing request,
// so only the error class and a system code are logged, never the text.
console.warn(
'[CCTV] Ontario 511 camera download error:',
error?.message || error,
`[CCTV] Ontario 511 camera download error (${ontarioFailureKind(error)})`,
);
return [];
}
@@ -1279,73 +1299,17 @@ export function parseTarkteeDatexImages(xml) {
*/
export async function loadTarkteeSourcesFromDatex() {
try {
const responses = await Promise.allSettled([
fetch(TARKTEE_LOCATIONS_URL, {
headers: { Accept: 'application/xml,text/xml,*/*' },
redirect: 'manual',
signal: AbortSignal.timeout(TARKTEE_FETCH_TIMEOUT_MS),
}),
fetch(TARKTEE_IMAGES_URL, {
headers: { Accept: 'application/xml,text/xml,*/*' },
redirect: 'manual',
signal: AbortSignal.timeout(TARKTEE_FETCH_TIMEOUT_MS),
}),
]);
const [locResp, imgResp] = responses.map((result) =>
result.status === 'fulfilled' ? result.value : undefined,
const [locXml, imgXml] = await readCatalogsTogether(
[
{ url: TARKTEE_LOCATIONS_URL, label: 'locations' },
{ url: TARKTEE_IMAGES_URL, label: 'images' },
],
{
accept: 'application/xml,text/xml,*/*',
maxBytes: TARKTEE_MAX_CATALOG_BYTES,
timeoutMs: TARKTEE_FETCH_TIMEOUT_MS,
},
);
// Both responses are fetched in parallel; if either is rejected or overflows
// its byte cap, both bodies must be released so neither transport leaks.
const discardBoth = async () => {
await Promise.allSettled([
locResp?.body?.cancel(),
imgResp?.body?.cancel(),
]);
return [];
};
const rejected = responses.find((result) => result.status === 'rejected');
if (rejected) {
await discardBoth();
throw rejected.reason;
}
if (
(locResp.status >= 300 && locResp.status < 400) ||
(imgResp.status >= 300 && imgResp.status < 400)
) {
console.warn(
'[CCTV] Tarktee DATEX catalog redirected; redirects are not followed',
);
return discardBoth();
}
if (!locResp.ok) {
console.warn('[CCTV] Tarktee locations download failed:', locResp.status);
return discardBoth();
}
if (!imgResp.ok) {
console.warn('[CCTV] Tarktee images download failed:', imgResp.status);
return discardBoth();
}
let locXml;
let imgXml;
const readAbort = new AbortController();
try {
[locXml, imgXml] = await Promise.all([
readResponseTextCapped(
locResp,
TARKTEE_MAX_CATALOG_BYTES,
readAbort.signal,
),
readResponseTextCapped(
imgResp,
TARKTEE_MAX_CATALOG_BYTES,
readAbort.signal,
),
]);
} catch (error) {
readAbort.abort();
await discardBoth();
throw error;
}
const locations = parseTarkteeDatexLocations(locXml);
const images = parseTarkteeDatexImages(imgXml);
if (!locations.size || !images.size) {
+2
View File
@@ -1,6 +1,7 @@
import path from 'node:path';
import { openSkyProxy } from './aircraft/opensky.js';
import { celestrakProxy, rocketLaunchesProxy } from './space.js';
import { issTelemetryProxy } from './space/issTelemetry.js';
import { tomtomProxy } from './traffic.js';
import { firmsProxy } from './firms.js';
import { terrainHeightsProxy } from './terrain.js';
@@ -58,6 +59,7 @@ function localProviderPlugins({
return [
openSkyProxy(),
celestrakProxy(),
issTelemetryProxy(),
tomtomProxy(),
firmsProxy(),
rocketLaunchesProxy(),
+8
View File
@@ -1,5 +1,13 @@
import { resolveGoogleServerKey } from '../../../scripts/google-server-key.mjs';
/**
* Default GEV_RATELIMIT_GOOGLE_PER_MIN for the Places and Geocoding window
* and the separate CCTV Street View window, in requests per minute per IP.
* The Pinokio build sets the same default in pinokio/_ENVIRONMENT.
* `.env.example` suggests 60 for hosts other than localhost.
*/
export const GOOGLE_DEFAULT_PER_MIN = 120;
/**
* Optional Google place context is an empty capability when no key is present,
* not a server outage. Returning 200 keeps a deliberately keyless session out
+29 -25
View File
@@ -1,4 +1,5 @@
import {
GOOGLE_DEFAULT_PER_MIN,
googleServerApiKey,
keylessGooglePlacesResponse,
keylessGoogleGeocodeResponse,
@@ -15,17 +16,7 @@ import {
// undefined = not built yet; null = the explicit 0 opt-out; fn = active limiter
let _googleRateLimiter;
/**
* Requests/min/IP applied when GEV_RATELIMIT_GOOGLE_PER_MIN is unset. This is
* the value the Pinokio build already ships (pinokio/_ENVIRONMENT), so the
* packaged app keeps behaving exactly as it does today and only an
* unconfigured server changes — from unlimited to what the product already
* runs with. Places calls are user-driven (a search, a nearby lookup, an
* installation probe) rather than polled, so this sits far above what the app
* generates and bites only a caller enumerating the endpoint. `.env.example`
* suggests a tighter 60 when the host is not localhost; that still applies.
*/
export const GOOGLE_DEFAULT_PER_MIN = 120;
export { GOOGLE_DEFAULT_PER_MIN };
/** Google cost endpoints (nearby-places, text-search, geocoding). Null only when set to 0. */
function googleRateLimiter() {
@@ -71,6 +62,8 @@ const GEOCODE_UPSTREAM_TIMEOUT_MS = 10_000;
const GEOCODE_MAX_RESPONSE_BYTES = 256 * 1024;
const GEOCODE_ANSWER_STATUSES = new Set(['OK', 'ZERO_RESULTS']);
/** Validate a free-text geocoder query before consuming request quota. */
export function validateGeocodeAddress(searchParams) {
const address = String(searchParams.get('address') || '').trim();
@@ -114,6 +107,10 @@ export function googlePlacesContextProxy({
// Gate first, like the OpenAI routes: a cross-site caller learns nothing
// about this endpoint's method surface.
if (admitSameSite(req, res)) return;
// Default to no-store. The browser caches only the 200 answer below.
// A cached refusal (bad key, API off, quota) would outlive the key fix
// by five minutes.
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
@@ -129,7 +126,6 @@ export function googlePlacesContextProxy({
if (keyless) {
res.statusCode = keyless.statusCode;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(keyless.payload));
return;
}
@@ -194,18 +190,21 @@ export function googlePlacesContextProxy({
}),
},
);
const data = await response.json().catch(() => ({}));
const places = projectNearbyPlaces(data, latitude, longitude);
const data = await response.json().catch(() => null);
// A 200 we could not read is an upstream failure, not an empty answer.
if (response.ok && !data)
throw new Error('Google Places request failed');
const places = projectNearbyPlaces(data || {}, latitude, longitude);
res.statusCode = response.ok ? 200 : response.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'private, max-age=300');
if (response.ok) res.setHeader('Cache-Control', 'private, max-age=300');
res.end(
JSON.stringify({
places,
error: response.ok
? null
: data.error?.message || 'Google Places request failed',
: data?.error?.message || 'Google Places request failed',
}),
);
} catch (error) {
@@ -222,11 +221,12 @@ export function googlePlacesContextProxy({
// Text Search: resolve a named landmark/POI to a real coordinate, biased to
// the view. Geocoding scatters obscure monument/POI names across the city;
// a view-biased Text Search lands on the actual feature. Same key, field
// mask, throttle, and `places: []` error contract as nearby-places above.
// a view-biased Text Search lands on the actual feature. Same key, throttle,
// cache rule, and `places: []` error contract as nearby-places above.
middlewares.use('/api/google/text-search', async (req, res) => {
// Paid like nearby-places, so gated the same way, first.
if (admitSameSite(req, res)) return;
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
@@ -242,7 +242,6 @@ export function googlePlacesContextProxy({
if (keyless) {
res.statusCode = keyless.statusCode;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(keyless.payload));
return;
}
@@ -315,18 +314,20 @@ export function googlePlacesContextProxy({
}),
},
);
const data = await response.json().catch(() => ({}));
const places = projectTextSearchPlaces(data, latitude, longitude);
const data = await response.json().catch(() => null);
if (response.ok && !data)
throw new Error('Google Places request failed');
const places = projectTextSearchPlaces(data || {}, latitude, longitude);
res.statusCode = response.ok ? 200 : response.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'private, max-age=300');
if (response.ok) res.setHeader('Cache-Control', 'private, max-age=300');
res.end(
JSON.stringify({
places,
error: response.ok
? null
: data.error?.message || 'Google Places request failed',
: data?.error?.message || 'Google Places request failed',
}),
);
} catch (error) {
@@ -366,6 +367,7 @@ export function googlePlacesContextProxy({
// Gate first, like the Places routes above: a cross-site caller learns
// nothing about this endpoint's method surface.
if (admitSameSite(req, res)) return;
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
refuse(405, 'Method not allowed');
return;
@@ -379,7 +381,6 @@ export function googlePlacesContextProxy({
if (keyless) {
res.statusCode = keyless.statusCode;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(keyless.payload));
return;
}
@@ -446,7 +447,10 @@ export function googlePlacesContextProxy({
res.statusCode = response.ok ? 200 : response.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'private, max-age=300');
// Geocoding reports a denied key or spent quota as HTTP 200 with a
// status of its own; only an answer is worth keeping.
if (response.ok && GEOCODE_ANSWER_STATUSES.has(data.status))
res.setHeader('Cache-Control', 'private, max-age=300');
res.end(JSON.stringify(data));
} catch {
// Fixed public text: a transport, URL or runtime message would
+468
View File
@@ -0,0 +1,468 @@
import { createRequire } from 'node:module';
import { clientNetworkKey, makeRateLimiter } from '../common/rate-limit.js';
import { admitSameSiteKeyless } from '../common/same-site.js';
/**
* NASA's public ISS telemetry (the ISSLive feed), relayed as a small snapshot.
*
* The feed is a push stream served by Lightstreamer for NASA. This module
* holds ONE connection to it for the whole server and gives browsers the
* latest value of each joint item at `/api/iss-telemetry`, so many viewers
* cost the public server one subscriber.
*
* Off by default: the feed publishes no terms of use, so nothing here
* contacts it unless the operator sets `ISS_TELEMETRY_ENABLED=1`. Without the
* flag the route answers `{ configured: false }` and the browser stops asking.
* With it, the connection opens on the first request and closes again once
* nobody has asked for a while.
*/
/** The route browsers poll. */
export const ISS_TELEMETRY_ROUTE = '/api/iss-telemetry';
const FEED_URL = 'wss://push.lightstreamer.com/lightstreamer';
/** Lightstreamer's text protocol (TLCP), spoken directly over the socket. */
const FEED_PROTOCOL = 'TLCP-2.4.0.lightstreamer.com';
const FEED_ADAPTER_SET = 'ISSLIVE';
/** The client id Lightstreamer assigns to custom TLCP clients. */
const FEED_CLIENT_ID = 'mgQkwtwdysogQz2BJ4Ji%20kOj2Bg';
/** The station clock; it ticks only while the ground has signal. */
const SIGNAL_ITEM = 'TIME_000001';
/** `Status.Class` of an item received with signal. */
const SIGNAL_CLASS = '24';
/**
* The items relayed: the joints the ISS model can turn, plus the station
* clock that says whether the feed has signal.
*/
export const ISS_TELEMETRY_ITEMS = Object.freeze([
// Alpha joints (SARJ): port, starboard.
'S0000004',
'S0000003',
// Array beta joints (BGA): 2A, 4A, 2B, 4B, 1A, 3A, 1B, 3B.
'P4000007',
'P4000008',
'P6000008',
'P6000007',
'S4000007',
'S4000008',
'S6000008',
'S6000007',
// Radiator joints (TRRJ): port, starboard.
'S0000002',
'S0000001',
// Ku-band dish: elevation, cross-elevation, transmitting.
'Z1000014',
'Z1000015',
'Z1000013',
// Canadarm2: shoulder roll, yaw, pitch; elbow; wrist pitch, yaw, roll.
'CSASSRMS004',
'CSASSRMS005',
'CSASSRMS006',
'CSASSRMS007',
'CSASSRMS008',
'CSASSRMS009',
'CSASSRMS010',
SIGNAL_ITEM,
]);
const FEED_FIELDS = Object.freeze(['TimeStamp', 'Value', 'Status.Class']);
/** No station clock tick for this long means the signal is gone. */
const SIGNAL_STALE_MS = 20_000;
/** No frame at all for this long (the server probes every 5 s) recycles the socket. */
const SILENCE_MS = 30_000;
/** Nobody asking for this long closes the connection. */
const IDLE_MS = 120_000;
/** Waits between connection attempts, the last one repeating. */
const RETRY_LADDER_MS = Object.freeze([5_000, 15_000, 60_000, 300_000]);
/**
* A session that has run this long has proved itself: its updates bring the
* retry ladder back to its first step. One that ends sooner (a snapshot and
* then `END`, over and over) keeps climbing the ladder.
*/
const STABLE_SESSION_MS = 60_000;
/** The opening handshake with the feed gives up after this. */
const HANDSHAKE_TIMEOUT_MS = 10_000;
/** A frame larger than this is not telemetry; it is dropped unread. */
const MAX_FRAME_BYTES = 64 * 1024;
const TICK_MS = 5_000;
/**
* Whether the operator switched the relay on. Only "1" does.
* @param {Record<string, string|undefined>} [env]
* @returns {boolean}
*/
export function issTelemetryEnabled(env = process.env) {
return String(env.ISS_TELEMETRY_ENABLED || '').trim() === '1';
}
/**
* The feed's time stamp as epoch milliseconds. The feed counts hours from the
* start of the day before January 1st (day of year × 24 + hours of the day),
* with no year; the year is taken from `nowMs`, stepping back one when that
* would put the stamp in the future (a value last sent in December, read in
* January).
* @param {number} hours
* @param {number} nowMs
* @returns {number|null}
*/
export function issTelemetryTimeMs(hours, nowMs) {
if (!Number.isFinite(hours) || hours < 0) return null;
const year = new Date(nowMs).getUTCFullYear();
const at = Date.UTC(year, 0, 0) + hours * 3_600_000;
// A day of slack for clock differences.
return at > nowMs + 86_400_000
? Date.UTC(year - 1, 0, 0) + hours * 3_600_000
: at;
}
/**
* Decode one TLCP update line, `U,<subscription>,<item>,<fields>`, against
* the item's previous field values. Fields are `|`-separated and
* percent-encoded: an empty field is unchanged, `#` is null, `$` is the empty
* string and `^n` stands for n unchanged fields.
* @param {string} line
* @param {(item: number) => Array<string|null>|undefined} previousOf
* @param {number} fieldCount
* @returns {{item: number, fields: Array<string|null>}|null} Null for a line
* that is not a well-formed update.
*/
export function parseTlcpUpdate(line, previousOf, fieldCount) {
if (!line.startsWith('U,')) return null;
const second = line.indexOf(',', 2);
const third = second < 0 ? -1 : line.indexOf(',', second + 1);
if (third < 0) return null;
const item = Number(line.slice(second + 1, third));
if (!Number.isInteger(item) || item < 1) return null;
const previous = previousOf(item) ?? [];
const fields = [];
for (const raw of line.slice(third + 1).split('|')) {
if (fields.length >= fieldCount) return null;
if (raw === '') fields.push(previous[fields.length] ?? null);
else if (raw === '#') fields.push(null);
else if (raw === '$') fields.push('');
else if (raw[0] === '^') {
const run = Number(raw.slice(1));
if (!Number.isInteger(run) || run < 1 || fields.length + run > fieldCount)
return null;
for (let i = 0; i < run; i++)
fields.push(previous[fields.length] ?? null);
} else {
try {
fields.push(decodeURIComponent(raw));
} catch {
return null;
}
}
}
return fields.length === fieldCount ? { item, fields } : null;
}
/**
* The relay: the connection's lifecycle and the snapshot it serves. It owns
* no timers; the caller drives `tick()` every few seconds.
* @param {{createSocket: () => object|null, now?: () => number}} options
* `createSocket` opens the feed and returns a `ws`-style socket (`on`,
* `send`, `terminate`), or null when no socket can be made.
*/
export function createIssTelemetryRelay({ createSocket, now = Date.now }) {
/** @type {Map<string, {value: number, at: number|null}>} */
const values = new Map();
/** Per item index, the raw field values the next update is decoded against. */
const fields = new Map();
let socket = null;
/** Bumped on every connect and dispose, so a dead socket's events are ignored. */
let generation = 0;
let lastDemandAt = null;
let lastFrameAt = null;
let signalAt = null;
let signalClass = null;
let failures = 0;
let retryAt = 0;
let unavailable = false;
/** When the live socket was opened, or null without one. */
let connectedAt = null;
function drop() {
generation += 1;
const old = socket;
socket = null;
connectedAt = null;
fields.clear();
// A replacement session must rebuild both its joint snapshot and signal
// credit; a new clock tick cannot make the old session's angles live.
values.clear();
signalAt = null;
signalClass = null;
try {
old?.terminate?.();
} catch {
// A socket that will not terminate is abandoned; the generation guard
// keeps its events out.
}
}
function fail() {
drop();
const wait =
RETRY_LADDER_MS[Math.min(failures, RETRY_LADDER_MS.length - 1)];
failures += 1;
retryAt = now() + wait;
}
function onLine(line) {
if (line.startsWith('CONOK,')) {
socket?.send(
`control\r\nLS_reqId=1&LS_op=add&LS_subId=1&LS_mode=MERGE&LS_group=${encodeURIComponent(
ISS_TELEMETRY_ITEMS.join(' '),
)}&LS_schema=${encodeURIComponent(FEED_FIELDS.join(' '))}&LS_snapshot=true`,
);
return;
}
// The session was refused, ended, or asks to be re-bound: start over.
if (/^(CONERR|END|LOOP|REQERR),/.test(line)) {
fail();
return;
}
const update = parseTlcpUpdate(
line,
(item) => fields.get(item),
FEED_FIELDS.length,
);
if (!update) return;
const name = ISS_TELEMETRY_ITEMS[update.item - 1];
if (!name) return;
fields.set(update.item, update.fields);
if (connectedAt !== null && now() - connectedAt >= STABLE_SESSION_MS)
failures = 0;
const [stamp, raw, statusClass] = update.fields;
const at = now();
if (name === SIGNAL_ITEM) {
signalAt = at;
signalClass = statusClass;
return;
}
const value = raw === null || raw === '' ? Number.NaN : Number(raw);
if (!Number.isFinite(value)) return;
values.set(name, {
value,
at:
stamp === null || stamp === ''
? null
: issTelemetryTimeMs(Number(stamp), at),
});
}
function connect() {
let opened;
try {
opened = createSocket();
} catch {
opened = null;
}
if (!opened) {
unavailable = true;
return;
}
unavailable = false;
generation += 1;
const mine = generation;
socket = opened;
connectedAt = now();
lastFrameAt = now();
opened.on('open', () => {
if (mine !== generation) return;
opened.send(
`create_session\r\nLS_adapter_set=${FEED_ADAPTER_SET}&LS_cid=${FEED_CLIENT_ID}&LS_send_sync=false&LS_cause=api`,
);
});
opened.on('message', (data) => {
if (mine !== generation) return;
// Nothing the feed sends may take the server down.
try {
if (data?.length > MAX_FRAME_BYTES) return;
lastFrameAt = now();
for (const line of String(data).split('\r\n')) {
if (mine !== generation) return;
if (line) onLine(line);
}
} catch {
fail();
}
});
const lost = () => {
if (mine === generation) fail();
};
opened.on('error', lost);
opened.on('close', lost);
}
/** Whether anyone asked recently enough to keep the connection. */
function wanted() {
return lastDemandAt !== null && now() - lastDemandAt < IDLE_MS;
}
/**
* Housekeeping, every few seconds: close when idle, recycle a silent
* socket, retry a failed one.
* @returns {boolean} False once there is nothing left to watch.
*/
function tick() {
if (!wanted()) {
dispose();
return false;
}
if (socket && now() - lastFrameAt > SILENCE_MS) fail();
if (!socket && !unavailable && now() >= retryAt) connect();
return true;
}
/** Record that a browser asked, opening the connection if it is closed. */
function demand() {
lastDemandAt = now();
if (!socket && !unavailable && now() >= retryAt) connect();
}
function status() {
if (unavailable) return 'unavailable';
if (!socket) return 'reconnecting';
if (signalAt === null) return 'connecting';
return signalClass === SIGNAL_CLASS && now() - signalAt < SIGNAL_STALE_MS
? 'live'
: 'no-signal';
}
/** The body served to browsers: each item's `[value, epoch ms it was true at]`. */
function snapshot() {
const items = {};
for (const [name, { value, at }] of values) items[name] = [value, at];
return { configured: true, status: status(), generatedAt: now(), items };
}
/** Close the connection and forget what it said. */
function dispose() {
drop();
values.clear();
lastDemandAt = null;
signalAt = null;
signalClass = null;
failures = 0;
retryAt = 0;
unavailable = false;
}
return { demand, tick, snapshot, dispose };
}
let webSocketImpl;
/**
* Load `ws` once, lazily: the vessel feed's socket library, so a missing
* optional dependency turns this relay off instead of breaking the server.
* @returns {Function|null}
*/
function loadWebSocket() {
if (webSocketImpl !== undefined) return webSocketImpl;
try {
webSocketImpl = createRequire(import.meta.url)('ws');
} catch {
webSocketImpl = null;
console.warn(
'[ISS telemetry] `ws` is unavailable; the telemetry relay is off.',
);
}
return webSocketImpl;
}
function json(res, status, body) {
res.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
});
res.end(JSON.stringify(body));
}
/**
* The Vite plugin that mounts the relay's route.
* @param {{env?: Record<string, string|undefined>, createSocket?: () => object|null,
* now?: () => number}} [options] Test seams; the defaults read the process
* environment at request time and open the real feed.
*/
export function issTelemetryProxy({
env,
createSocket = () => {
const WebSocket = loadWebSocket();
// `ws` buffers a whole frame before handing it over, up to 100 MiB by
// default: the frame cap applies on the socket, not only after it.
return WebSocket
? new WebSocket(FEED_URL, FEED_PROTOCOL, {
maxPayload: MAX_FRAME_BYTES,
handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
})
: null;
},
now = Date.now,
} = {}) {
const relay = createIssTelemetryRelay({ createSocket, now });
// A browser polls every few seconds; this leaves room for several tabs.
const allow = makeRateLimiter({ windowMs: 60_000, max: 60, globalMax: 1200 });
let timer = null;
function stop() {
if (timer) clearInterval(timer);
timer = null;
relay.dispose();
}
function watch() {
if (timer) return;
timer = setInterval(() => {
if (relay.tick()) return;
clearInterval(timer);
timer = null;
}, TICK_MS);
timer.unref?.();
}
function handle(req, res) {
if (admitSameSiteKeyless(req, res)) return;
// The route is the one path: anything under it is not found, as JSON.
const path = String(req.url ?? '/').split('?')[0];
if (path !== '/' && path !== '') {
json(res, 404, { error: 'Not Found' });
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
json(res, 405, { error: 'Method Not Allowed' });
return;
}
// Read per request: the environment is loaded after this module is.
if (!issTelemetryEnabled(env ?? process.env)) {
json(res, 200, { configured: false });
return;
}
// IPv6 clients fold to their /64, so one host cannot spread across it.
if (!allow(clientNetworkKey(req))) {
json(res, 429, { error: 'Too Many Requests' });
return;
}
relay.demand();
watch();
json(res, 200, relay.snapshot());
}
function install(server) {
server.middlewares.use(ISS_TELEMETRY_ROUTE, handle);
// Vite restarts the server in-process while this module's state lives on.
server.httpServer?.on('close', stop);
}
return {
name: 'iss-telemetry-proxy',
configureServer: install,
configurePreviewServer: install,
// Middleware mode has no httpServer to hang 'close' on.
closeBundle: stop,
};
}
@@ -0,0 +1,430 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
ISS_TELEMETRY_ITEMS,
ISS_TELEMETRY_ROUTE,
createIssTelemetryRelay,
issTelemetryEnabled,
issTelemetryProxy,
issTelemetryTimeMs,
parseTlcpUpdate,
} from './issTelemetry.js';
/** A `ws`-shaped socket the test drives by hand. */
function fakeSocket() {
const handlers = {};
return {
sent: [],
terminated: false,
on(event, handler) {
handlers[event] = handler;
},
send(text) {
this.sent.push(text);
},
terminate() {
this.terminated = true;
},
emit(event, payload) {
handlers[event]?.(payload);
},
};
}
const index = (name) => ISS_TELEMETRY_ITEMS.indexOf(name) + 1;
/** A relay on a hand-moved clock, with every socket it opened. */
function relayAt(startMs) {
const clock = { ms: startMs };
const sockets = [];
const relay = createIssTelemetryRelay({
createSocket: () => {
const socket = fakeSocket();
sockets.push(socket);
return socket;
},
now: () => clock.ms,
});
return { relay, sockets, clock };
}
const NOV_13 = Date.UTC(2026, 10, 13, 11, 0, 0);
/** The feed's stamp for a moment: day of year × 24 + hours of that day. */
const stampOf = (ms) =>
(ms - Date.UTC(new Date(ms).getUTCFullYear(), 0, 0)) / 3_600_000;
test('only ISS_TELEMETRY_ENABLED=1 switches the relay on', () => {
assert.equal(issTelemetryEnabled({}), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '0' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: 'true' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: ' 1 ' }), true);
});
test("the feed's stamp is hours from the day before January 1st", () => {
// 13 November 2026 is day 317: 317 × 24 + 11 hours.
assert.equal(issTelemetryTimeMs(317 * 24 + 11, NOV_13), NOV_13);
assert.equal(
issTelemetryTimeMs(stampOf(NOV_13 - 5000), NOV_13),
NOV_13 - 5000,
);
// A value last sent on 30 December, read on 2 January, belongs to last year.
const january = Date.UTC(2027, 0, 2, 0, 0, 0);
assert.equal(
issTelemetryTimeMs(364 * 24, january),
Date.UTC(2026, 11, 30, 0, 0, 0),
);
assert.equal(issTelemetryTimeMs(Number.NaN, NOV_13), null);
assert.equal(issTelemetryTimeMs(-1, NOV_13), null);
});
test('an update line decodes against the previous field values', () => {
const previous = new Map([[3, ['7000.5', '10.25', '24']]]);
const of = (item) => previous.get(item);
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.6|11.5|24', of, 3), {
item: 3,
fields: ['7000.6', '11.5', '24'],
});
// Empty = unchanged, ^n = n unchanged, # = null, $ = empty string.
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.7||', of, 3).fields, [
'7000.7',
'10.25',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.8|^2', of, 3).fields, [
'7000.8',
'10.25',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,#|$|24', of, 3).fields, [
null,
'',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,a%7Cb|1|24', of, 3).fields[0], 'a|b');
// Not updates, or malformed ones.
for (const line of [
'PROBE',
'SUBOK,1,23,3',
'U,1',
'U,1,x,1|2|3',
'U,1,0,1|2|3',
'U,1,3,1|2',
'U,1,3,1|2|3|4',
'U,1,3,^9',
'U,1,3,%E0%A4%A|1|24',
])
assert.equal(parseTlcpUpdate(line, of, 3), null, line);
});
test('the relay opens on the first request, subscribes, and reports live values', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
assert.equal(sockets.length, 0, 'nothing is contacted before a request');
relay.demand();
assert.equal(sockets.length, 1);
assert.equal(relay.snapshot().status, 'connecting');
const socket = sockets[0];
socket.emit('open');
assert.match(socket.sent[0], /^create_session\r\nLS_adapter_set=ISSLIVE&/);
socket.emit(
'message',
'CONOK,S1,50000,5000,*\r\nSERVNAME,x\r\nCLIENTIP,192.0.2.1',
);
assert.match(
socket.sent[1],
/^control\r\n.*LS_mode=MERGE.*LS_schema=TimeStamp%20Value%20Status\.Class/,
);
assert.ok(socket.sent[1].includes('S0000004%20S0000003'));
const stamp = stampOf(NOV_13 - 2000);
socket.emit(
'message',
`U,1,${index('S0000004')},${stamp}|346.12|24\r\nU,1,${index('TIME_000001')},${stamp}|123|24`,
);
let body = relay.snapshot();
assert.equal(body.configured, true);
assert.equal(body.status, 'live');
assert.deepEqual(body.items.S0000004, [346.12, NOV_13 - 2000]);
assert.equal(body.items.TIME_000001, undefined, 'the clock is not a joint');
assert.equal(JSON.stringify(body).includes('192.0.2.1'), false);
// A later update with an unchanged stamp field keeps the old stamp.
clock.ms += 1000;
socket.emit('message', `U,1,${index('S0000004')},|346.5|`);
body = relay.snapshot();
assert.deepEqual(body.items.S0000004, [346.5, NOV_13 - 2000]);
});
test('no station clock tick for 20 s, or a clock without signal, is no-signal', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
const clockLine = (cls) =>
`U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|${cls}`;
socket.emit('message', clockLine('24'));
assert.equal(relay.snapshot().status, 'live');
clock.ms += 19_000;
socket.emit('message', 'PROBE');
assert.equal(relay.snapshot().status, 'live');
clock.ms += 2_000;
assert.equal(relay.snapshot().status, 'no-signal');
socket.emit('message', clockLine('1'));
assert.equal(relay.snapshot().status, 'no-signal');
socket.emit('message', clockLine('24'));
assert.equal(relay.snapshot().status, 'live');
});
test('a lost or silent connection is retried on a ladder, and stale events are ignored', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const first = sockets[0];
first.emit('open');
first.emit('close');
assert.equal(first.terminated, true);
assert.equal(relay.snapshot().status, 'reconnecting');
// Not before 5 s.
clock.ms += 4_000;
relay.demand();
relay.tick();
assert.equal(sockets.length, 1);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, 2);
// The dead socket's late events change nothing.
first.emit('message', `U,1,${index('S0000004')},1|999|24`);
assert.equal(relay.snapshot().items.S0000004, undefined);
// A second failure waits 15 s.
sockets[1].emit('error', new Error('x'));
clock.ms += 14_000;
relay.demand();
assert.equal(sockets.length, 2);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, 3);
// A socket that goes silent for 30 s is recycled by the tick.
const third = sockets[2];
third.emit('open');
third.emit('message', 'CONOK,S1,50000,5000,*');
clock.ms += 29_000;
relay.demand();
relay.tick();
assert.equal(third.terminated, false);
clock.ms += 2_000;
relay.demand();
relay.tick();
assert.equal(third.terminated, true);
});
test("a reconnect cannot mark the previous socket's joint samples live", () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const first = sockets[0];
first.emit('open');
first.emit('message', 'CONOK,S1,50000,5000,*');
const stamp = stampOf(clock.ms);
first.emit(
'message',
`U,1,${index('S0000004')},${stamp}|17|24\r\n` +
`U,1,${index('TIME_000001')},${stamp}|1|24`,
);
assert.equal(relay.snapshot().status, 'live');
assert.deepEqual(relay.snapshot().items.S0000004, [17, clock.ms]);
first.emit('close');
assert.equal(relay.snapshot().status, 'reconnecting');
clock.ms += 5_000;
relay.demand();
assert.equal(sockets.length, 2);
assert.equal(relay.snapshot().status, 'connecting');
assert.deepEqual(relay.snapshot().items, {});
const second = sockets[1];
second.emit('open');
second.emit('message', 'CONOK,S2,50000,5000,*');
// The clock can return before any new joint snapshot is delivered.
second.emit(
'message',
`U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|24`,
);
assert.equal(relay.snapshot().status, 'live');
assert.deepEqual(
relay.snapshot().items,
{},
'the new clock must not revive old joint angles',
);
second.emit('message', `U,1,${index('S0000004')},${stampOf(clock.ms)}|23|24`);
assert.deepEqual(relay.snapshot().items.S0000004, [23, clock.ms]);
});
test('a refused or ended session starts over', () => {
for (const line of ['CONERR,2,x', 'END,31,x', 'LOOP,0', 'REQERR,1,17,x']) {
const { relay, sockets } = relayAt(NOV_13);
relay.demand();
sockets[0].emit('open');
sockets[0].emit('message', line);
assert.equal(sockets[0].terminated, true, line);
assert.equal(relay.snapshot().status, 'reconnecting', line);
}
});
test('with nobody asking for two minutes the connection closes and the values go', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit('message', `U,1,${index('S0000003')},${stampOf(clock.ms)}|14|24`);
clock.ms += 119_000;
socket.emit('message', 'PROBE');
assert.equal(relay.tick(), true);
assert.equal(socket.terminated, false);
clock.ms += 2_000;
assert.equal(relay.tick(), false);
assert.equal(socket.terminated, true);
assert.deepEqual(relay.snapshot().items, {});
// The next request opens a fresh connection.
relay.demand();
assert.equal(sockets.length, 2);
});
test('an oversized or malformed frame is dropped without taking the relay down', () => {
const { relay, sockets } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit('message', { length: 10_000_000 });
socket.emit('message', `U,1,${index('S0000004')},1|not-a-number|24`);
socket.emit('message', 'U,1,999,1|2|24');
assert.deepEqual(relay.snapshot().items, {});
assert.equal(socket.terminated, false);
});
test('without a socket library the relay says unavailable', () => {
const relay = createIssTelemetryRelay({ createSocket: () => null });
relay.demand();
assert.equal(relay.snapshot().status, 'unavailable');
});
/** Mount the plugin on a fake Connect stack and return a request function. */
function install(plugin, preview = false) {
const routes = new Map();
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: { use: (route, handler) => routes.set(route, handler) },
});
return (method = 'GET', headers = {}, url = '/') => {
const res = {
headers: {},
writeHead(status, headers) {
Object.assign(this, { status, headers });
},
setHeader(name, value) {
this.headers[name] = value;
},
end(body) {
this.body = body;
this.status ??= this.statusCode;
},
};
routes.get(ISS_TELEMETRY_ROUTE)({ url, method, headers, socket: {} }, res);
return res;
};
}
test('the route is off by default and never opens the feed', () => {
let opened = 0;
const plugin = issTelemetryProxy({
env: {},
createSocket: () => {
opened += 1;
return fakeSocket();
},
});
assert.equal(typeof plugin.configurePreviewServer, 'function');
for (const preview of [false, true]) {
const res = install(plugin, preview)();
assert.equal(res.status, 200);
assert.deepEqual(JSON.parse(res.body), { configured: false });
assert.equal(res.headers['Cache-Control'], 'no-store');
}
assert.equal(opened, 0);
});
test('switched on, the route opens the feed once and serves the snapshot', () => {
const sockets = [];
const plugin = issTelemetryProxy({
env: { ISS_TELEMETRY_ENABLED: '1' },
createSocket: () => {
const socket = fakeSocket();
sockets.push(socket);
return socket;
},
now: () => NOV_13,
});
const request = install(plugin);
try {
const first = JSON.parse(request().body);
assert.equal(first.configured, true);
assert.equal(first.status, 'connecting');
request();
assert.equal(sockets.length, 1, 'one connection for every request');
assert.equal(request('POST').status, 405);
const unknown = request('GET', {}, '/anything');
assert.equal(unknown.status, 404);
assert.deepEqual(JSON.parse(unknown.body), { error: 'Not Found' });
assert.equal(request('GET', {}, '/?t=1').status, 200, 'a query is fine');
assert.equal(
request('GET', { 'sec-fetch-site': 'cross-site' }).status,
403,
);
// Sixty requests a minute from one client, then 429.
let limited = 0;
for (let i = 0; i < 70; i++) if (request().status === 429) limited += 1;
assert.ok(limited > 0);
} finally {
plugin.closeBundle();
}
assert.equal(sockets[0].terminated, true);
});
test('a session that keeps ending soon after its snapshot climbs the retry ladder', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
/** The current socket opens, sends a snapshot update, then ends. */
const shortSession = () => {
const socket = sockets.at(-1);
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit(
'message',
`U,1,${index('S0000004')},${stampOf(clock.ms)}|17|24`,
);
socket.emit('message', 'END,41,session closed');
};
// Each wait is the next step: 5 s, 15 s, 60 s, then 5 minutes.
for (const wait of [5_000, 15_000, 60_000, 300_000, 300_000]) {
shortSession();
const before = sockets.length;
clock.ms += wait - 1_000;
relay.demand();
assert.equal(sockets.length, before, `not before ${wait / 1000} s`);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, before + 1, `again after ${wait / 1000} s`);
}
// A session that runs a minute before its updates brings the ladder down.
const socket = sockets.at(-1);
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
clock.ms += 60_000;
relay.demand();
socket.emit('message', `U,1,${index('S0000004')},${stampOf(clock.ms)}|17|24`);
socket.emit('message', 'END,41,session closed');
const before = sockets.length;
clock.ms += 5_000;
relay.demand();
assert.equal(sockets.length, before + 1, 'back to 5 s');
});
+1
View File
@@ -126,6 +126,7 @@ export function createApplicationCatalog({
});
const satellites = createApplicationSatellites({
source: sources.satellites,
...(resolveAsset ? { resolveAsset } : {}),
});
const catalog = createLayerCatalog(
[
+4
View File
@@ -1,12 +1,16 @@
import {
clearOverlaySource,
getOverlayPaintRect,
getWorldOverlayDiagnostics,
hitTestWorldOverlay,
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
export const overlayHost = Object.freeze({
clearSource: clearOverlaySource,
getDiagnostics: getWorldOverlayDiagnostics,
hitTest: hitTestWorldOverlay,
paintRect: getOverlayPaintRect,
setEntries: setOverlayEntries,
setVisible: setOverlaySourceVisible,
});
+6 -1
View File
@@ -8,9 +8,14 @@ import * as render from '../../renderGovernor.js';
import * as layerState from '../../data/layerState.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationSatellites({ source }) {
export function createApplicationSatellites({
source,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
return createSatellitesLayer({
source,
resolveAsset,
services: {
picking,
focus,
+18
View File
@@ -1157,6 +1157,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-controls[\s\S]*?bottom:\s*152px;/,
);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode\.mobile-shell[^{]*?\.cockpit-utility-controls \{[^}]*?top:[^;]*?var\(--cockpit-visor-top\)/,
);
assert.match(
mobileCockpit[1],
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
);
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
@@ -1175,6 +1184,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
);
});
test('the unread Stories announcement waits until Cockpit closes', () => {
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
assert.match(
storiesView,
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
);
});
test('cockpit route direction uses self-contained vector artwork, not a font ligature', () => {
const match = html.match(/<div id="cockpit-route-direction"[\s\S]*?<\/div>/);
assert.ok(match, 'cockpit route-direction markup is missing');
+1
View File
@@ -335,6 +335,7 @@ test('the Google places route throttles by default and keeps its places[] contra
const overLimit = await request(handler, { url, method: 'GET' });
assert.equal(overLimit.status, 429);
assert.equal(overLimit.headers['retry-after'], '5');
assert.equal(overLimit.headers['cache-control'], 'no-store');
// Every error response on this route carries places[]; the client reads it
// unconditionally, so a throttled reply must not be the one shape that omits it.
assert.deepEqual(JSON.parse(overLimit.body).places, []);
+1 -53
View File
@@ -5,6 +5,7 @@ import {
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { loadYouTubeApi } from './youtubeApi.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
import { h, render as renderVue } from 'vue';
import BhoteKoshiMediaCards from '../ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
@@ -101,59 +102,6 @@ let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
let _cardSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
/** A trimmed clip follows provider time, never time spent loading its iframe. */
export function createTrimmedYouTubePlayback({
+155 -54
View File
@@ -12,6 +12,14 @@ import {
parseTarkteeDatexLocations,
} from '../../server/providers/cctv/sources.js';
/**
* Disarm the 30 s deadline, so a loader that only stops at that deadline
* fails at the test timeout instead of passing late.
*/
function withoutDeadline(t) {
t.mock.method(AbortSignal, 'timeout', () => new AbortController().signal);
}
/** Silence the loaders' progress and failure logging. */
function quiet(t) {
t.mock.method(console, 'log', () => {});
@@ -97,6 +105,29 @@ test('Tarktee DATEX image parser rejects non-official hosts', () => {
assert.equal(images.size, 0);
});
test('Tarktee DATEX requests wait 30 s, past the slow answers measured live', async (t) => {
const timeouts = [];
const timeout = AbortSignal.timeout;
t.mock.method(AbortSignal, 'timeout', (ms) => {
timeouts.push(ms);
return timeout.call(AbortSignal, ms);
});
t.mock.method(console, 'log', () => {});
t.mock.method(
globalThis,
'fetch',
async (url) =>
new Response(
String(url).includes('roadCameraLocations')
? SAMPLE_LOCATIONS_XML
: SAMPLE_IMAGES_XML,
),
);
const cameras = await loadTarkteeSourcesFromDatex();
assert.deepEqual(timeouts, [30_000]);
assert.equal(cameras.length, 1);
});
test('Tarktee loader deduplicates cameras sharing an image number before the cap', async (t) => {
quiet(t);
const dupLocationsXml = `<?xml version="1.0" encoding="UTF-8"?>
@@ -168,46 +199,6 @@ test('Tarktee loader refuses a redirect and cancels both response bodies', async
assert.equal(cancelled.images, true, 'sibling 200 body is also cancelled');
});
test('Tarktee loader cancels fulfilled bodies when either fetch rejects', async (t) => {
for (const failedUrl of [TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL]) {
for (const delayedSibling of [false, true]) {
await t.test(
`${failedUrl}, delayed sibling: ${delayedSibling}`,
async (t) => {
quiet(t);
let cancelled = false;
const response = new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('<xml/>'));
},
cancel() {
cancelled = true;
},
}),
);
t.mock.method(globalThis, 'fetch', async (url) => {
if (String(url) === failedUrl) throw new TypeError('fetch failed');
if (delayedSibling) await new Promise(setImmediate);
return response;
});
try {
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.equal(
cancelled,
true,
'fulfilled sibling body is cancelled',
);
} finally {
await response.body.cancel();
}
},
);
}
}
});
test('Tarktee loader cancels the sibling body when one feed fails or overflows the byte cap', async (t) => {
quiet(t);
let siblingCancelled = false;
@@ -264,25 +255,135 @@ test('Tarktee loader cancels the sibling body when one feed fails or overflows t
);
});
test('Tarktee DATEX requests wait 30 s, past the slow answers measured live', async (t) => {
const timeouts = [];
const timeout = AbortSignal.timeout;
t.mock.method(AbortSignal, 'timeout', (ms) => {
timeouts.push(ms);
return timeout.call(AbortSignal, ms);
});
t.mock.method(console, 'log', () => {});
for (const failingUrl of [TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL]) {
for (const lateSibling of [false, true]) {
test(
`Tarktee cancels a ${lateSibling ? 'late' : 'received'} sibling when ${failingUrl} rejects before headers`,
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(t);
let cancelled = false;
let siblingSignal;
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
t.mock.method(globalThis, 'fetch', async (url, init) => {
if (String(url) === failingUrl)
throw new Error('headers unavailable');
siblingSignal = init.signal;
// A late transport answers once the sibling is aborted, or on release.
if (lateSibling)
await Promise.race([
gate,
new Promise((resolve) =>
init.signal.addEventListener('abort', resolve, { once: true }),
),
]);
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('<xml/>'));
},
cancel() {
cancelled = true;
},
}),
);
});
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
// Also exercise a response arriving after abort, as a queued transport
// completion can race the rejection owner even when fetch honors abort.
if (lateSibling) {
release();
await new Promise((resolve) => setImmediate(resolve));
}
assert.equal(cancelled, true, 'every obtained body must be cancelled');
assert.equal(
siblingSignal.aborted,
true,
'a pending transport is aborted immediately',
);
},
);
}
test(
`Tarktee aborts a pending sibling when ${failingUrl} rejects`,
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(t);
let aborted = false;
t.mock.method(globalThis, 'fetch', async (url, init) => {
if (String(url) === failingUrl) throw new Error('headers unavailable');
return new Promise((resolve, reject) => {
init.signal.addEventListener(
'abort',
() => {
aborted = true;
reject(init.signal.reason);
},
{ once: true },
);
});
});
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.equal(aborted, true, 'do not wait for the 30-second deadline');
},
);
}
test('Tarktee cancels both lengthless streams when one exceeds the byte cap', async (t) => {
quiet(t);
const cancelled = [];
t.mock.method(
globalThis,
'fetch',
async (url) =>
new Response(
String(url).includes('roadCameraLocations')
? SAMPLE_LOCATIONS_XML
: SAMPLE_IMAGES_XML,
new ReadableStream({
start(controller) {
const oversized = String(url) === TARKTEE_LOCATIONS_URL;
controller.enqueue(
new Uint8Array(oversized ? TARKTEE_MAX_CATALOG_BYTES + 1 : 1),
);
},
cancel() {
cancelled.push(String(url));
},
}),
),
);
const cameras = await loadTarkteeSourcesFromDatex();
assert.deepEqual(timeouts, [30_000, 30_000]);
assert.equal(cameras.length, 1);
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.deepEqual(
cancelled.sort(),
[TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL].sort(),
);
});
test(
'Tarktee aborts pending headers as soon as its sibling returns an HTTP error',
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(t);
let aborted = false;
t.mock.method(globalThis, 'fetch', async (url, init) => {
if (String(url) === TARKTEE_LOCATIONS_URL)
return new Response('unavailable', { status: 503 });
return new Promise((resolve, reject) => {
init.signal.addEventListener(
'abort',
() => {
aborted = true;
reject(init.signal.reason);
},
{ once: true },
);
});
});
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.equal(aborted, true);
},
);
+112
View File
@@ -0,0 +1,112 @@
// A body-phase failure of one Tarktee DATEX feed must abort the sibling that is
// still waiting for headers instead of leaving it until the 30 s deadline.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import {
TARKTEE_IMAGES_URL,
TARKTEE_LOCATIONS_URL,
TARKTEE_MAX_CATALOG_BYTES,
} from '../../server/providers/cctv/constants.js';
import { loadTarkteeSourcesFromDatex } from '../../server/providers/cctv/sources.js';
/** The sibling sends its headers this late; the loader must not wait for it. */
const SIBLING_HEADER_DELAY_MS = 2000;
/** Generous bound for "at once" on a loaded CI machine. */
const FAIL_FAST_MS = 1000;
function startServer(handlers) {
const server = http.createServer((req, res) => handlers[req.url](req, res));
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => resolve(server));
});
}
/** Send the two DATEX URLs to the local server through the real fetch. */
function routeFetchTo(t, port) {
const realFetch = globalThis.fetch;
t.mock.method(globalThis, 'fetch', (url, init) => {
const path =
String(url) === TARKTEE_LOCATIONS_URL
? '/loc'
: String(url) === TARKTEE_IMAGES_URL
? '/img'
: null;
assert.ok(path, `unexpected url ${url}`);
return realFetch(`http://127.0.0.1:${port}${path}`, init);
});
}
/** The sibling answers late and reports whether it was cut off before headers. */
function slowSibling() {
const arrived = Promise.withResolvers();
const closed = Promise.withResolvers();
return {
arrived: arrived.promise,
closed: closed.promise,
handler(req, res) {
arrived.resolve();
const timer = setTimeout(() => {
res.writeHead(200, { 'content-type': 'application/xml' });
res.end('<d2LogicalModel/>');
}, SIBLING_HEADER_DELAY_MS);
res.on('close', () => {
clearTimeout(timer);
closed.resolve({ beforeHeaders: !res.headersSent });
});
},
};
}
const failingBodies = {
'declares a body over the byte cap': (req, res) => {
res.writeHead(200, {
'content-type': 'application/xml',
'content-length': String(TARKTEE_MAX_CATALOG_BYTES + 1),
});
res.write('<d2LogicalModel>');
},
'resets the connection mid-body': (req, res) => {
res.writeHead(200, { 'content-type': 'application/xml' });
res.write('<d2LogicalModel><payloadPublication>');
setTimeout(() => res.socket.destroy(), 20);
},
};
for (const [label, failingFeed] of Object.entries(failingBodies)) {
for (const [failing, pending] of [
['/loc', '/img'],
['/img', '/loc'],
]) {
test(`Tarktee aborts ${pending} pending headers when ${failing} ${label}`, { timeout: 10_000 }, async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
const sibling = slowSibling();
const server = await startServer({
[failing]: (req, res) =>
sibling.arrived.then(() => failingFeed(req, res)),
[pending]: sibling.handler,
});
t.after(() => {
server.closeAllConnections();
server.close();
});
routeFetchTo(t, server.address().port);
const started = Date.now();
const cameras = await loadTarkteeSourcesFromDatex();
const elapsed = Date.now() - started;
assert.deepEqual(cameras, []);
assert.ok(
elapsed < FAIL_FAST_MS,
`loader waited ${elapsed} ms for the sibling's headers instead of aborting it`,
);
assert.deepEqual(
await sibling.closed,
{ beforeHeaders: true },
`${pending} was not aborted`,
);
});
}
}
@@ -0,0 +1,138 @@
// An explicit pick of the camera that a settled move just re-opened must end
// the opening pick. That pick goes through setActiveCamera's UNCHANGED path
// (same camera, already activated); if that path keeps the provisional flag,
// the next settled move (a pan, or the landing of NEAREST's own flight)
// switches the camera away from the one the user chose.
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import cctvLayer, {
_setCctvCoverageStateForTest,
_setCctvOverlayHostForTest,
reopenNearestCamera,
} from './cctv.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
const BASE = {
headingDeg: 41,
pitchDeg: -5,
fovDeg: 56,
rangeM: 210,
mountHeightM: 100,
groundElevationM: 0,
city: 'London',
};
function record(id, lat, lon) {
return {
camera: { ...BASE, id, name: `Camera ${id}`, lat, lon },
coverageEntities: [],
projection: null,
activationDone: true,
groundResolved: {},
groundSamples: {},
groundPrior: 0,
frustumGeometry: null,
frustumPositions: null,
probeClampRangeM: null,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 100),
};
}
function viewerAt(lat, lon) {
const viewer = {
isDestroyed: () => false,
eye: { lat, lon, height: 300 },
scene: {
canvas: { clientWidth: 1200, clientHeight: 800 },
cartesianToCanvasCoordinates: () => undefined,
primitives: { add: (p) => p, remove: () => true },
requestRender() {},
},
};
// The layer reads the eye and flies through the renderer's camera port.
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...viewer.eye }),
on: () => () => {},
followed: null,
flyToBounds() {},
},
}).draw;
return viewer;
}
function moveViewer(viewer, lat, lon) {
viewer.eye = { lat, lon, height: 300 };
}
function withReopenedLayer(fn) {
_setCctvOverlayHostForTest({
setEntries() {},
setVisible() {},
clearSource() {},
});
// Activation builds the projection canvas and frame image.
const originalDocument = globalThis.document;
const originalImage = globalThis.Image;
globalThis.document = { createElement: () => ({ getContext: () => null }) };
globalThis.Image = class {};
try {
const trafalgar = record('a-trafalgar', 51.508, -0.128);
const cambridge = record('b-cambridge', 51.513, -0.129);
// enable() assigned the opening camera without activating it.
trafalgar.activationDone = false;
const viewer = viewerAt(51.5081, -0.1281);
_setCctvCoverageStateForTest({
viewer,
records: [trafalgar, cambridge],
activeCameraId: 'a-trafalgar',
enabled: true,
openingCameraProvisional: true,
});
// A settled move next to Cambridge Circus re-opens there, still as the
// opening pick.
moveViewer(viewer, 51.5131, -0.1291);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
fn(viewer);
} finally {
globalThis.document = originalDocument;
globalThis.Image = originalImage;
_setCctvOverlayHostForTest();
_setCctvCoverageStateForTest({ enabled: false });
}
}
for (const [name, pick] of [
['NEAREST (focusNearest)', () => cctvLayer.focusNearest({ focus: false })],
['selectCamera', () => cctvLayer.selectCamera('b-cambridge')],
[
'setParams({ selectedCameraId })',
() => cctvLayer.setParams({ selectedCameraId: 'b-cambridge' }),
],
[
'focusNearestToPoint',
() => cctvLayer.focusNearestToPoint(51.513, -0.129, { focus: false }),
],
]) {
test(`an explicit ${name} pick of the re-opened camera ends the opening pick`, () => {
withReopenedLayer((viewer) => {
pick();
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
// A later settled move (a pan, or the landing of the pick's own flight)
// leaves the explicit choice alone.
moveViewer(viewer, 51.5081, -0.1281);
assert.equal(reopenNearestCamera(), false);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
});
});
}
test('without a pick, the next settled move still follows the view', () => {
withReopenedLayer((viewer) => {
moveViewer(viewer, 51.5081, -0.1281);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'a-trafalgar');
});
});
+20 -17
View File
@@ -140,25 +140,28 @@ for (const [label, flag] of [
});
}
test('a failed catalog cancels the sibling request instead of waiting for the timeout', async (t) => {
t.mock.method(console, 'warn', () => {});
let siblingSignal;
t.mock.method(globalThis, 'fetch', async (url, options) => {
if (url === LITHUANIA_CAMERAS_URL) {
return new Response('', { status: 503 });
}
siblingSignal = options.signal;
// Never settles on its own; only an abort ends it.
return new Promise((_, reject) => {
options.signal.addEventListener('abort', () =>
reject(options.signal.reason),
);
for (const [failure, camerasResponse] of [
['failed', () => new Response('', { status: 503 })],
['malformed', () => new Response('<html>error page</html>')],
]) {
test(`a ${failure} catalog cancels the sibling request instead of waiting for the timeout`, async (t) => {
t.mock.method(console, 'warn', () => {});
let siblingSignal;
t.mock.method(globalThis, 'fetch', async (url, options) => {
if (url === LITHUANIA_CAMERAS_URL) return camerasResponse();
siblingSignal = options.signal;
// Never settles on its own; only an abort ends it.
return new Promise((_, reject) => {
options.signal.addEventListener('abort', () =>
reject(options.signal.reason),
);
});
});
assert.deepEqual(await loadLithuaniaSources(), []);
assert.equal(siblingSignal?.aborted, true);
assert.notEqual(siblingSignal.reason?.name, 'TimeoutError');
});
assert.deepEqual(await loadLithuaniaSources(), []);
assert.equal(siblingSignal?.aborted, true);
assert.notEqual(siblingSignal.reason?.name, 'TimeoutError');
});
}
test('a redirected catalog is reported as not followed', async (t) => {
const warnings = [];
+103 -2
View File
@@ -111,6 +111,7 @@ function mount(t, respond) {
austin: process.env.CCTV_FORCE_AUSTIN,
serverKey: process.env.GOOGLE_MAPS_SERVER_API_KEY,
browserKey: process.env.GOOGLE_MAPS_API_KEY,
rateLimit: process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
};
process.env.CCTV_SOURCES_JSON = JSON.stringify([
STILL,
@@ -125,6 +126,8 @@ function mount(t, respond) {
// than a network call this file does not model.
delete process.env.GOOGLE_MAPS_SERVER_API_KEY;
delete process.env.GOOGLE_MAPS_API_KEY;
// The default Google budget, whatever the shell sets.
delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN;
const nativeFetch = globalThis.fetch;
const requests = [];
globalThis.fetch = async (url, init = {}) => {
@@ -139,6 +142,7 @@ function mount(t, respond) {
['CCTV_FORCE_AUSTIN', before.austin],
['GOOGLE_MAPS_SERVER_API_KEY', before.serverKey],
['GOOGLE_MAPS_API_KEY', before.browserKey],
['GEV_RATELIMIT_GOOGLE_PER_MIN', before.rateLimit],
]) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
@@ -155,9 +159,9 @@ function mount(t, respond) {
});
assert.ok(handler, 'the CCTV provider must mount a middleware');
const call = async (path, headers = {}) => {
const call = async (path, headers = {}, socket) => {
const { res, done } = recordingResponse();
await handler({ url: path, headers, method: 'GET', on() {} }, res);
await handler({ url: path, headers, method: 'GET', on() {}, socket }, res);
await done;
return res;
};
@@ -528,3 +532,100 @@ test('a forwarded same-origin request reaches every CCTV route but not the Stree
assert.equal(direct.body, 'street-view');
assert.equal(streetViewCalls(), 1);
});
test('the Street View fallback frames catalog cameras only, from the catalog position', async (t) => {
const app = mount(t, ({ url }) =>
url.startsWith('https://maps.googleapis.com/')
? trackedUpstream({
headers: { 'content-type': 'image/jpeg' },
body: 'street-view',
}).response
: upstreamResponse({ status: 503 }),
);
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
const streetView = () =>
app.requests.filter(({ url }) =>
url.startsWith('https://maps.googleapis.com/'),
);
const unknown = await app.call('/frame/not-a-camera?lat=48.85&lon=2.29');
assert.equal(unknown.headers['X-CCTV-Source'], 'synthetic');
assert.deepEqual(streetView(), [], 'no Google call for an unknown id');
const steered = await app.call(
`/frame/${STILL.id}?lat=48.85&lon=2.29&heading=90&fov=74&pitch=-17`,
);
assert.equal(steered.headers['X-CCTV-Source'], 'streetview');
const sv = new URL(streetView()[0].url).searchParams;
assert.equal(sv.get('location'), `${STILL.lat},${STILL.lon}`);
assert.equal(sv.get('heading'), '90');
assert.equal(sv.get('fov'), '74');
assert.equal(sv.get('pitch'), '-17');
});
test('the Street View fallback spends a per-IP Google budget, and only with a key', async (t) => {
const app = mount(t, ({ url }) =>
url.startsWith('https://maps.googleapis.com/')
? trackedUpstream({
headers: { 'content-type': 'image/jpeg' },
body: 'street-view',
}).response
: upstreamResponse({ status: 503 }),
);
// Read when the first keyed fallback builds the limiter, so after mount().
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '2';
const streetViewCalls = () =>
app.requests.filter(({ url }) =>
url.startsWith('https://maps.googleapis.com/'),
).length;
const first = { remoteAddress: '203.0.113.7' };
const frameSource = async (socket) =>
(await app.call(`/frame/${STILL.id}`, {}, socket)).headers['X-CCTV-Source'];
// Without a key nothing is spent.
for (let i = 0; i < 3; i++)
assert.equal(await frameSource(first), 'synthetic');
assert.equal(streetViewCalls(), 0);
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
// Neither an unknown id nor a forwarded request spends the window.
assert.equal(
(await app.call('/frame/not-a-camera', {}, first)).headers['X-CCTV-Source'],
'synthetic',
);
assert.equal(
(
await app.call(
`/frame/${STILL.id}`,
{ 'x-forwarded-for': '203.0.113.9' },
first,
)
).headers['X-CCTV-Source'],
'synthetic',
);
assert.deepEqual(
[
await frameSource(first),
await frameSource(first),
await frameSource(first),
],
['streetview', 'streetview', 'synthetic'],
);
assert.equal(streetViewCalls(), 2, 'no Google call over the budget');
// Another address has a budget of its own.
assert.equal(
await frameSource({ remoteAddress: '203.0.113.8' }),
'streetview',
);
assert.equal(streetViewCalls(), 3);
// Addresses within one IPv6 /64 share a budget.
const v6 = (remoteAddress) => frameSource({ remoteAddress });
assert.deepEqual(
[await v6('2001:db8::1'), await v6('2001:db8::2'), await v6('2001:db8::3')],
['streetview', 'streetview', 'synthetic'],
);
assert.equal(await v6('2001:db8:0:1::1'), 'streetview', 'another /64');
assert.equal(streetViewCalls(), 6);
});
@@ -0,0 +1,87 @@
// Real sockets: a client that closes its connection while the camera upstream
// is still pending must not get a Street View call outside its own budget.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { cctvProxy } from '../../server/providers/cctv.js';
const CAM = {
id: 'still-fixture',
name: 'Still fixture',
lat: 30.27,
lon: -97.74,
feedType: 'image',
url: 'https://cams.upstream.invalid/still.jpg',
};
test('a client that disconnects mid-fetch stays inside its own Street View budget', async (t) => {
const saved = { ...process.env };
process.env.CCTV_SOURCES_JSON = JSON.stringify([CAM]);
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
process.env.CCTV_FORCE_AUSTIN = '0';
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
delete process.env.GOOGLE_MAPS_API_KEY;
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '1';
const nativeFetch = globalThis.fetch;
let streetViewCalls = 0;
globalThis.fetch = async (url) => {
if (String(url).startsWith('https://maps.googleapis.com/')) {
streetViewCalls += 1;
return new Response('street-view', {
headers: { 'content-type': 'image/jpeg' },
});
}
await new Promise((r) => setTimeout(r, 400));
return new Response(null, { status: 503 });
};
let handler;
cctvProxy().configureServer({
middlewares: { use: (_r, fn) => (handler = fn) },
});
const server = http.createServer((req, res) => {
req.url = req.url.replace(/^\/api\/cctv/, '');
handler(req, res, () => res.end());
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => {
server.close();
globalThis.fetch = nativeFetch;
for (const k of Object.keys(process.env))
if (!(k in saved)) delete process.env[k];
Object.assign(process.env, saved);
});
const { port } = server.address();
const get = (abortAfterMs) =>
new Promise((resolve) => {
const req = http.get(
{
host: '127.0.0.1',
port,
path: `/api/cctv/frame/${CAM.id}`,
headers: { host: `localhost:${port}` },
agent: false,
},
(res) => {
res.resume();
res.on('end', () => resolve(res.headers['x-cctv-source']));
},
);
req.on('error', () => resolve('aborted'));
if (abortAfterMs)
setTimeout(() => {
req.destroy();
resolve('aborted');
}, abortAfterMs);
});
assert.equal(await get(), 'streetview');
assert.equal(await get(), 'synthetic', 'the cap of one is spent');
assert.equal(streetViewCalls, 1);
await get(50);
await new Promise((r) => setTimeout(r, 800));
assert.equal(
streetViewCalls,
1,
'an aborted request spent the key outside its own budget',
);
});
+27 -3
View File
@@ -166,6 +166,30 @@ export const DATA_CREDITS = [
'(<a href="https://celestrak.org" target="_blank" rel="noopener">celestrak.org</a>), ' +
'Dr. T.S. Kelso',
},
{
key: 'nasa-iss-model',
html:
'ISS model: ' +
'<a href="https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/" target="_blank" rel="noopener">NASA 3D Resources</a> (JSC IGOAL)',
},
{
key: 'tiangong-model',
html:
"Tiangong model: made for God's Eye View; dimensions from " +
'<a href="https://doi.org/10.34133/space.0035" target="_blank" rel="noopener">Wang, Zhang &amp; Wang 2023</a> ' +
'(CC BY 4.0) and eoPortal',
},
{
key: 'nasa-iss-telemetry',
html: 'ISS joint telemetry (where switched on): NASA ISSLive, via Lightstreamer',
},
{
key: 'nasa-iss-live',
html:
'ISS live video (LIVE section): NASA, via YouTube ' +
'(<a href="https://www.youtube.com/watch?v=ROboUHfPUrU" target="_blank" rel="noopener">exterior cameras</a>, ' +
'<a href="https://www.youtube.com/watch?v=M3HKLzjvKPc" target="_blank" rel="noopener">live video and audio</a>)',
},
{
key: 'ucs-satellite-database',
html:
@@ -303,9 +327,9 @@ export const DATA_CREDITS = [
key: 'ontario-511-cctv',
html:
'CCTV cameras &amp; frames (Ontario): ' +
'<a href="https://511on.ca/" target="_blank" rel="noopener">Ontario 511</a> ' +
'(<a href="https://www.ontario.ca/page/open-government-licence-ontario" target="_blank" rel="noopener">Open Government Licence - Ontario</a>) ' +
'· provided as is, without warranty; actual road conditions may differ',
'<a href="https://511on.ca/" target="_blank" rel="noopener">Ontario 511</a>. ' +
'Contains information licensed under the <a href="https://www.ontario.ca/page/open-government-licence-ontario" target="_blank" rel="noopener">Open Government Licence – Ontario</a>. ' +
'Provided as is, without warranty; actual road conditions may differ.',
},
{
key: 'fintraffic-cctv',
+12
View File
@@ -173,6 +173,18 @@ test('the NYC camera credit carries NYC DOT’s requested disclaimer', () => {
assert.match(credit.html, /observe posted signage/);
});
test('the Ontario 511 camera credit carries the licence attribution statement', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'ontario-511-cctv');
assert.ok(credit, 'Ontario 511 camera frames must be credited');
assert.ok(
credit.html.includes(
'Contains information licensed under the <a href="https://www.ontario.ca/page/open-government-licence-ontario"',
),
);
assert.match(credit.html, />Open Government Licence – Ontario<\/a>/);
assert.match(credit.html, /Provided as is, without warranty/);
});
test("the Houston camera credit names TranStar's terms and the permission they require", () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'houston-cctv');
assert.ok(credit, 'Houston TranStar camera frames must be credited');
+1 -1
View File
@@ -32,7 +32,7 @@ export function createInfrastructureLayers(services) {
name: 'Dams',
color: '#0088ff', // Blue
icon: '▰',
source: 'USACE',
source: 'OpenStreetMap / OpenInfraMap',
osmDerived: true,
labels: true,
labelMax: 900,
+79 -2
View File
@@ -6,6 +6,7 @@ import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { parseGeojsonLines } from '../sources/infrastructureData.js';
function services() {
const records = new Map();
@@ -34,6 +35,20 @@ function services() {
};
}
// Added from the OSM API, not the OpenInfraMap extract: [id, name, OSM
// object, version]. Both must stay polygons: the Dams layer skips
// LineStrings.
const OSM_API_DAMS = [
[262532166, 'Acaray', 'way/262532166', 7],
[-5671745, 'Represa Yacyretá-Apipé', 'relation/5671745', 2],
];
const DAMS = parseGeojsonLines(
readFileSync(
new URL('./local_data/dams/dams.geojsonl', import.meta.url),
'utf8',
),
);
test('package exports import without an application, DOM, fetch, or timers', () => {
const result = spawnSync(
process.execPath,
@@ -66,7 +81,11 @@ test('infrastructure factory preserves identity and creates independent state wi
first.map(({ id, name, source }) => ({ id, name, source })),
[
{ id: 'local-datacenters', name: 'Datacenters', source: 'Local' },
{ id: 'local-dams', name: 'Dams', source: 'USACE' },
{
id: 'local-dams',
name: 'Dams',
source: 'OpenStreetMap / OpenInfraMap',
},
],
);
first.forEach((layer, index) => {
@@ -84,7 +103,7 @@ test('infrastructure factory preserves identity and creates independent state wi
test('dataset URLs still name the complete bundled sources', () => {
for (const [file, count] of [
['datacenters', 4352],
['dams', 704],
['dams', 706],
]) {
const lines = readFileSync(
new URL(`./local_data/${file}/${file}.geojsonl`, import.meta.url),
@@ -96,6 +115,64 @@ test('dataset URLs still name the complete bundled sources', () => {
}
});
test('Acaray and Yacyretá appear once each with OSM provenance', () => {
for (const [id, name, object, version] of OSM_API_DAMS) {
const matches = DAMS.filter((feature) => feature.id === id);
assert.equal(matches.length, 1);
const { properties } = matches[0];
assert.equal(properties.name, name);
assert.equal(properties.osm_id, id);
assert.equal(properties.source_version, version);
assert.equal(
properties.source_url,
`https://www.openstreetmap.org/${object}`,
);
assert.equal(properties.retrieved_at, '2026-10-15');
}
});
test('Acaray and Yacyretá each get a stem, a selection context and an analyst record', async (t) => {
const added = DAMS.filter((feature) =>
OSM_API_DAMS.some(([id]) => id === feature.id),
);
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
text: async () =>
added.map((feature) => JSON.stringify(feature)).join('\n'),
}));
const host = services();
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
name: 'Dams',
osmDerived: true,
color: '#0088ff',
url: '/dams.geojsonl',
},
host,
);
const viewer = {
scene: { screenSpaceCameraController: { enableInputs: true } },
};
const fake = bindFakeGroundRenderer(viewer);
fakeInput(viewer);
t.after(() => layer.destroy(viewer));
await layer.enable(viewer);
const names = OSM_API_DAMS.map(([, name]) => name).sort();
assert.equal(fake.set('stems').items.size, 2, 'both dams get a stem');
assert.deepEqual(
[...host.records.values()].map((record) => record.label).sort(),
names,
);
assert.deepEqual(
layer
.getAnalystRecords()
.map((record) => record.name)
.sort(),
names,
);
});
test('two viewers use their supplied contexts and dispose independently', async (t) => {
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
+83
View File
@@ -0,0 +1,83 @@
import { msg } from '../i18n/marker.js';
/**
* Live streams the app can show for a selected object: a fixed list, each
* entry a broadcast on a platform's own player (YouTube today), attached to
* the subjects it shows by key. Any layer can name its selected subject's
* keys (`getLiveSubjectKeys`), and the LIVE section in Context offers the
* streams that match; the satellites layer names the ISS as `station:iss`
* whichever of the station's catalog entries is selected.
*
* These are broadcasts in the platform's embedded player, not camera feeds:
* the CCTV layer is for those. A stream's id changes when its broadcaster
* restarts it, so each entry is one line to update.
*/
/** Where YouTube's embedded player is served from: the privacy-enhanced host. */
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
/** @typedef {{id: string, platform: 'youtube', videoId: string, title: string,
* owner: string, ownerUrl: string, subjects: readonly string[],
* note: string}} LiveStream */
/** @type {readonly LiveStream[]} */
export const LIVE_STREAMS = Object.freeze([
Object.freeze({
id: 'iss-exterior',
platform: 'youtube',
videoId: 'ROboUHfPUrU',
title: msg('Exterior cameras'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
Object.freeze({
id: 'iss-crew',
platform: 'youtube',
videoId: 'M3HKLzjvKPc',
title: msg('Live video and space-to-ground audio'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
]);
/**
* The streams attached to any of `subjectKeys`, in list order.
* @param {Iterable<string>|null|undefined} subjectKeys
* @param {readonly LiveStream[]} [streams]
* @returns {LiveStream[]}
*/
export function liveStreamsFor(subjectKeys, streams = LIVE_STREAMS) {
const keys = new Set(subjectKeys ?? []);
if (!keys.size) return [];
return streams.filter((stream) =>
stream.subjects.some((subject) => keys.has(subject)),
);
}
/** The video's own page, for the "Open on YouTube" link. */
export function youtubeWatchUrl(videoId) {
return `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`;
}
/**
* The parameters the live player is created with: starts on creation (the
* player is built only when the viewer presses Play), muted so the browser
* lets it start once the player API has loaded, inline on phones, no related
* videos, and the page's origin so the player API may be spoken to.
* @param {string} origin The page's origin.
* @returns {Record<string, string|number>}
*/
export function youtubeLivePlayerVars(origin) {
return {
autoplay: 1,
mute: 1,
playsinline: 1,
rel: 0,
enablejsapi: 1,
...(origin ? { origin } : {}),
};
}
+80
View File
@@ -0,0 +1,80 @@
// src/data/liveStreams.test.mjs — the fixed list of live streams and how a
// selected object's keys pick from it.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LIVE_STREAMS,
YOUTUBE_EMBED_HOST,
liveStreamsFor,
youtubeLivePlayerVars,
youtubeWatchUrl,
} from './liveStreams.js';
test('every listed stream is a complete YouTube entry with a distinct id', () => {
assert.ok(LIVE_STREAMS.length >= 2, 'the ISS has two streams');
const ids = new Set(LIVE_STREAMS.map((stream) => stream.id));
assert.equal(ids.size, LIVE_STREAMS.length);
for (const stream of LIVE_STREAMS) {
assert.equal(stream.platform, 'youtube');
assert.match(stream.videoId, /^[\w-]{11}$/, `${stream.id} video id`);
assert.ok(stream.title.length > 0);
assert.ok(stream.owner.length > 0);
assert.match(stream.ownerUrl, /^https:\/\/www\.youtube\.com\//);
assert.ok(stream.subjects.length > 0, `${stream.id} names a subject`);
assert.ok(Object.isFrozen(stream), 'entries cannot be edited at run time');
}
});
test('the ISS streams attach to the station key, in list order', () => {
const found = liveStreamsFor(['station:iss']);
assert.deepEqual(
found.map((stream) => stream.id),
['iss-exterior', 'iss-crew'],
);
});
test('a key no stream names, or no keys at all, finds nothing', () => {
assert.deepEqual(liveStreamsFor(['satellites:25544']), []);
assert.deepEqual(liveStreamsFor([]), []);
assert.deepEqual(liveStreamsFor(null), []);
assert.deepEqual(liveStreamsFor(undefined), []);
});
test('a subject known by several keys gets the union, each stream once', () => {
const streams = [
{ id: 'a', subjects: ['x'] },
{ id: 'b', subjects: ['y', 'x'] },
{ id: 'c', subjects: ['z'] },
];
assert.deepEqual(
liveStreamsFor(new Set(['x', 'y']), streams).map((s) => s.id),
['a', 'b'],
);
});
test('the watch link is the video page on YouTube proper', () => {
assert.equal(
youtubeWatchUrl('ROboUHfPUrU'),
'https://www.youtube.com/watch?v=ROboUHfPUrU',
);
assert.equal(
youtubeWatchUrl('a b&c'),
'https://www.youtube.com/watch?v=a%20b%26c',
);
});
test('the player is created on the privacy-enhanced host, muted, with the API on', () => {
assert.equal(YOUTUBE_EMBED_HOST, 'https://www.youtube-nocookie.com');
const vars = youtubeLivePlayerVars('http://localhost:5190');
assert.equal(vars.autoplay, 1);
assert.equal(vars.mute, 1);
assert.equal(vars.playsinline, 1);
assert.equal(vars.rel, 0);
assert.equal(vars.enablejsapi, 1);
assert.equal(vars.origin, 'http://localhost:5190');
assert.equal(
'origin' in youtubeLivePlayerVars(undefined),
false,
'no origin is passed when the page has none',
);
});
+14 -1
View File
@@ -4,7 +4,7 @@ Extracted from local decoded OpenInfraMap/PostGIS layers.
Filters: `waterway=dam`, `man_made=dam`, or `building=dam`.
Feature count: 704
Feature count: 706
Runtime output: `dams.geojsonl`
@@ -15,3 +15,16 @@ this derived database.
The public-release snapshot removes contact-oriented fields and note values
that contain email or phone identifiers. The runtime layer does not display or
depend on those fields.
## OSM API additions
Two dams come from the public OpenStreetMap API rather than the extract:
- Acaray: [way 262532166](https://www.openstreetmap.org/way/262532166), its closed outline of nine nodes.
- Represa Yacyretá-Apipé: [relation 5671745](https://www.openstreetmap.org/relation/5671745), its eight outer ways joined into one closed outline.
Both are under the same ODbL 1.0; the relation keeps the extract's negative ID (-5671745).
Keep both as polygons: the Dams layer skips LineStrings.
The layer puts a polygon's marker at the centre of its bounding sphere. The Yacyretá outline is L-shaped, so its
marker sits about 1.6 km from the outline, over the reservoir.
+2
View File
@@ -702,3 +702,5 @@
{"id":1415605139,"type":"Feature","geometry":{"type":"LineString","coordinates":[[169.362055788,-45.423612051],[169.360158461,-45.423276272],[169.358642426,-45.4229907],[169.357633077,-45.422794061],[169.356944755,-45.42275366],[169.356044036,-45.422764473]]},"properties":{"id":2377429,"line":"","tags":{"power":"minor_line","voltage":"11000","operator":"Aurora Energy","waterway":"dam","operator:wikidata":"Q4822522"},"type":"minor_line","osm_id":1415605139,"tunnel":false,"disused":"","voltage":"11000","circuits":null,"location":"","frequency":"","construction":"","source_layer":"osm_power_line"}}
{"id":405007988,"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[51.592068922,43.199413946],[51.59684602,43.199885177],[51.59724064,43.197759191],[51.593578084,43.197397847],[51.59272137,43.197675623],[51.592397577,43.197643772],[51.592068922,43.199413946]]]},"properties":{"id":33090,"name":"","tags":{"man_made":"wastewater_plant","waterway":"dam"},"type":"wastewater_plant","osm_id":405007988,"source_layer":"osm_wastewater_plant"}}
{"id":-19953989,"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[14.292237283,46.169084857],[14.292230326,46.169090389],[14.292224878,46.169096341],[14.292219346,46.169103549],[14.292216999,46.169113188],[14.292215322,46.169122744],[14.29221658,46.169131796],[14.292221273,46.169138334],[14.292231918,46.169148225],[14.29223963,46.169150823]],[[14.292171736,46.168911268],[14.292167462,46.168929289],[14.29216654,46.168975893],[14.292183555,46.169023083],[14.292186321,46.169030124],[14.292204593,46.169025933],[14.292237283,46.169084857]],[[14.293466824,46.169211843],[14.293464394,46.169201869],[14.293090644,46.16923657],[14.293067678,46.169224248],[14.293022583,46.169223662],[14.292636178,46.169247718],[14.292563842,46.169209496],[14.292558394,46.169207988],[14.292478766,46.169186446],[14.292457643,46.169185021],[14.292426882,46.169183429],[14.29241347,46.169186446],[14.292388492,46.169203545],[14.292448842,46.169220477],[14.292470384,46.169226428],[14.292521681,46.169242772],[14.292532661,46.169225673],[14.292546659,46.169229529],[14.29256468,46.169234558],[14.292535679,46.169293483],[14.292533499,46.169297925],[14.292576582,46.169300859],[14.292619162,46.169286191],[14.293023422,46.169262554],[14.293072791,46.169259536],[14.293092321,46.169248388],[14.293466824,46.169211843]],[[14.292535679,46.169293483],[14.29249905,46.169285185],[14.292510198,46.169267248],[14.292313977,46.169211927],[14.292318755,46.169203042],[14.29232546,46.169190721],[14.292333256,46.169176472],[14.292290089,46.169164653],[14.292276175,46.169192062],[14.292257986,46.169227769],[14.29231163,46.169241767],[14.292303919,46.169254842],[14.292294196,46.169271439],[14.292207024,46.169244868],[14.292170647,46.169314522],[14.29248589,46.169394736],[14.292518496,46.169328436],[14.292526123,46.169312845],[14.292533499,46.169297925],[14.292535679,46.169293483]],[[14.292426882,46.169183429],[14.292448172,46.169103549],[14.292476838,46.169107153],[14.292457643,46.169185021],[14.292426882,46.169183429]],[[14.292237283,46.169084857],[14.292246922,46.169084941],[14.292247257,46.169081086],[14.292319845,46.169084857],[14.292448172,46.169103549],[14.292476838,46.169107153],[14.292575074,46.169109333],[14.292575493,46.169095838],[14.292480777,46.169093156],[14.292326383,46.169069099],[14.292247341,46.169065747],[14.292242228,46.169055269],[14.292266117,46.169050324],[14.292263099,46.169041858],[14.292231835,46.169048899],[14.292217418,46.169022161],[14.292267374,46.16901336],[14.292264943,46.169006235],[14.292183555,46.169023083],[14.292186321,46.169030124],[14.292204593,46.169025933],[14.292237283,46.169084857]]]},"properties":{"name":"HE Podlubnik - Centrala","tags":{"name":"HE Podlubnik - Centrala","type":"site","power":"plant","alt_name":"HE Škofja Loka","operator":"Elektro Gorenjska","waterway":"dam","start_date":"1969","plant:method":"run-of-the-river","plant:source":"hydro","plant:output:electricity":"330KW"},"osm_id":-19953989,"output":"330KW","source":"hydro","construction":"","source_layer":"power_plant_relation_by_geom_type"}}
{"type":"Feature","id":-5671745,"geometry":{"type":"Polygon","coordinates":[[[-56.7356385,-27.4830326],[-56.7356372,-27.4836817],[-56.7356918,-27.4837745],[-56.7356509,-27.4838875],[-56.7355326,-27.4837665],[-56.7354735,-27.4836131],[-56.7353507,-27.4835526],[-56.7353552,-27.4830522],[-56.7354053,-27.483032],[-56.7354041,-27.4829378],[-56.7350345,-27.4826704],[-56.7321442,-27.4826598],[-56.7319588,-27.4828659],[-56.7018972,-27.4827418],[-56.7018797,-27.4821358],[-56.706089,-27.4821869],[-56.7060921,-27.4821089],[-56.7063455,-27.482095],[-56.7063734,-27.4821649],[-56.7090948,-27.482163],[-56.7091818,-27.4821095],[-56.7093995,-27.4820799],[-56.7094201,-27.4821854],[-56.7106196,-27.4821876],[-56.7109955,-27.4820628],[-56.7121754,-27.4820408],[-56.7121751,-27.4817168],[-56.712209,-27.4817165],[-56.7122144,-27.4803221],[-56.7121755,-27.4803209],[-56.7121781,-27.4793322],[-56.7122425,-27.4793286],[-56.7122439,-27.4791204],[-56.7121688,-27.479118],[-56.7121795,-27.4788039],[-56.7122371,-27.4788007],[-56.7122492,-27.4788015],[-56.7122948,-27.4790038],[-56.7123002,-27.4793441],[-56.7123005,-27.4796668],[-56.7124411,-27.4796679],[-56.7125759,-27.4796689],[-56.7125765,-27.47935],[-56.7125805,-27.4792477],[-56.7125939,-27.4790371],[-56.7126422,-27.4788016],[-56.7126649,-27.4788009],[-56.7127186,-27.4788051],[-56.7127213,-27.4791216],[-56.7126462,-27.4791276],[-56.7126516,-27.4793274],[-56.7127079,-27.4793263],[-56.7127072,-27.4803126],[-56.7126744,-27.4803132],[-56.712673,-27.4817118],[-56.7127239,-27.481713],[-56.7127247,-27.4820404],[-56.7132439,-27.4820594],[-56.7135349,-27.4821853],[-56.716431,-27.4821918],[-56.7166924,-27.4821402],[-56.7169096,-27.482192],[-56.7354167,-27.4822992],[-56.7432767,-27.4822775],[-56.7432829,-27.4821624],[-56.7433092,-27.4820925],[-56.7433441,-27.4820092],[-56.743387,-27.4819117],[-56.7433977,-27.481826],[-56.7434058,-27.481362],[-56.743385,-27.4806888],[-56.7435047,-27.4806879],[-56.7435053,-27.480804],[-56.7517581,-27.4808023],[-56.7519858,-27.4807842],[-56.7522074,-27.4807224],[-56.7529074,-27.4805122],[-56.7530675,-27.4804512],[-56.753188,-27.4804018],[-56.7536873,-27.4801667],[-56.7539035,-27.480035],[-56.7540186,-27.4799455],[-56.7546428,-27.4793125],[-56.7548624,-27.4789803],[-56.755134,-27.4784449],[-56.7553243,-27.4776504],[-56.7553385,-27.4775558],[-56.7553453,-27.4773839],[-56.7553663,-27.453364],[-56.756278,-27.4533505],[-56.7566902,-27.4545407],[-56.7565699,-27.4671653],[-56.7566153,-27.4769172],[-56.7565098,-27.4782975],[-56.7561882,-27.4791614],[-56.7557343,-27.4797995],[-56.7548315,-27.4808659],[-56.7541622,-27.4813087],[-56.753515,-27.4815729],[-56.7529038,-27.4817915],[-56.7522708,-27.4819086],[-56.7486914,-27.4820093],[-56.7480953,-27.4820155],[-56.7478466,-27.4820264],[-56.747675,-27.4820455],[-56.7475127,-27.4820919],[-56.7469953,-27.4823096],[-56.7450435,-27.4829093],[-56.7443696,-27.4830283],[-56.7436163,-27.4830891],[-56.7434021,-27.483068],[-56.7396907,-27.4830592],[-56.7396861,-27.4833826],[-56.7394399,-27.4833826],[-56.739439,-27.4830604],[-56.7356385,-27.4830326]]]},"properties":{"name":"Represa Yacyretá-Apipé","tags":{"name":"Represa Yacyretá-Apipé","type":"multipolygon","waterway":"dam"},"osm_id":-5671745,"source_layer":"osm_relation","source_url":"https://www.openstreetmap.org/relation/5671745","source_version":2,"retrieved_at":"2026-10-15"}}
{"type":"Feature","id":262532166,"geometry":{"type":"Polygon","coordinates":[[[-54.6285064,-25.4587626],[-54.628456,-25.4586556],[-54.6286513,-25.458535],[-54.6287352,-25.4587382],[-54.6292971,-25.459876],[-54.6290649,-25.4599721],[-54.6285037,-25.4588762],[-54.6285459,-25.4588065],[-54.6285064,-25.4587626]]]},"properties":{"name":"Acaray","tags":{"name":"Acaray","waterway":"dam","wikidata":"Q3433454"},"osm_id":262532166,"source_layer":"osm_way","source_url":"https://www.openstreetmap.org/way/262532166","source_version":7,"retrieved_at":"2026-10-15"}}
+68
View File
@@ -0,0 +1,68 @@
/**
* YouTube's IFrame Player API, loaded once per document: the only in-page
* way to learn a player's state (playing, ended) and errors (video gone,
* embedding refused), which the live-stream player needs to tell an offline
* stream from one still loading. The page's script-src allows
* `https://www.youtube.com`.
*/
const youtubeApis = new WeakMap();
/**
* Load the API, or return the one already there.
* @param {Document} documentRef
* @param {object} globalRef The window: `YT`, `onYouTubeIframeAPIReady`,
* timers.
* @returns {Promise<object>} The `YT` namespace.
*/
export function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
+84
View File
@@ -0,0 +1,84 @@
// src/data/youtubeApi.test.mjs — YouTube's IFrame API loader, with the page
// faked: one load per document, and a load that fails is not kept, so the
// LIVE section's Try again loads the API afresh.
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadYouTubeApi } from './youtubeApi.js';
/** A document whose head records the scripts put in it. */
function fakePage() {
const scripts = [];
const timers = [];
const documentRef = {
createElement(tag) {
const listeners = {};
return {
tag,
removed: false,
addEventListener(name, listener) {
listeners[name] = listener;
},
fire(name) {
listeners[name]?.();
},
remove() {
this.removed = true;
},
};
},
head: {
append(node) {
scripts.push(node);
},
},
};
const globalRef = {
setTimeout(callback, delay) {
timers.push({ callback, delay, cleared: false });
return timers.length;
},
clearTimeout(id) {
if (timers[id - 1]) timers[id - 1].cleared = true;
},
};
return { documentRef, globalRef, scripts, timers };
}
class Player {}
test('the API loads once per document, and a loaded one is reused', async () => {
const { documentRef, globalRef, scripts } = fakePage();
const first = loadYouTubeApi(documentRef, globalRef);
assert.equal(loadYouTubeApi(documentRef, globalRef), first);
assert.equal(scripts.length, 1);
assert.equal(scripts[0].src, 'https://www.youtube.com/iframe_api');
globalRef.YT = { Player };
globalRef.onYouTubeIframeAPIReady();
assert.equal(await first, globalRef.YT);
assert.equal(await loadYouTubeApi(documentRef, globalRef), globalRef.YT);
assert.equal(scripts.length, 1);
});
test('a script that fails to load is removed, and the next call loads afresh', async () => {
const { documentRef, globalRef, scripts } = fakePage();
const failed = loadYouTubeApi(documentRef, globalRef);
scripts[0].fire('error');
await assert.rejects(failed, /YouTube API unavailable/);
assert.equal(scripts[0].removed, true);
const again = loadYouTubeApi(documentRef, globalRef);
assert.notEqual(again, failed);
assert.equal(scripts.length, 2);
globalRef.YT = { Player };
globalRef.onYouTubeIframeAPIReady();
assert.equal(await again, globalRef.YT);
});
test('a load slower than 5 s fails, and the next call loads afresh', async () => {
const { documentRef, globalRef, scripts, timers } = fakePage();
const slow = loadYouTubeApi(documentRef, globalRef);
assert.equal(timers[0].delay, 5000);
timers[0].callback();
await assert.rejects(slow, /YouTube API timed out/);
loadYouTubeApi(documentRef, globalRef);
assert.equal(scripts.length, 2);
});
+124
View File
@@ -0,0 +1,124 @@
import { loadYouTubeApi } from './youtubeApi.js';
import { YOUTUBE_EMBED_HOST, youtubeLivePlayerVars } from './liveStreams.js';
/**
* One live stream in YouTube's embedded player, with its state read back
* through the player API: `loading` until the video plays, `playing`, and
* `offline` once the player says the video has ended, cannot be found or
* never starts. The player cannot say "this broadcast is off air" in so
* many words: a live stream that is off air is reported as a video that
* cannot play, or that never reaches playing, so both read as offline here.
* An API that does not load (blocked, or slower than its 5 s) is offline too,
* reason `api`: Try again loads it afresh. Embedding refused by the video's
* owner is `unavailable`, which no retry will change.
*/
/** A stream that has not started playing this long after its player was ready is offline. */
export const LIVE_START_TIMEOUT_MS = 25_000;
/** YouTube's player states. */
const ENDED = 0;
const PLAYING = 1;
/** Error codes: embedding not allowed on this page. */
const EMBED_REFUSED = new Set([101, 150]);
/**
* @param {{host: HTMLElement, videoId: string, documentRef?: Document,
* globalRef?: object, loadApi?: typeof loadYouTubeApi,
* onChange: (state: {state: 'loading'|'playing'|'offline'|'unavailable',
* reason: string|null}) => void}} options `host` is emptied and given the
* player's iframe.
* @returns {{destroy: () => void}}
*/
export function createYouTubeLivePlayer({
host,
videoId,
documentRef = globalThis.document,
globalRef = globalThis,
loadApi = loadYouTubeApi,
onChange,
}) {
let destroyed = false;
let player = null;
let timer = null;
let current = null;
const set = (state, reason = null) => {
if (destroyed || current === state) return;
current = state;
onChange({ state, reason });
};
const clearTimer = () => {
if (timer !== null) globalRef.clearTimeout(timer);
timer = null;
};
const armTimer = () => {
clearTimer();
timer = globalRef.setTimeout(() => {
timer = null;
if (current === 'loading') set('offline', 'timeout');
}, LIVE_START_TIMEOUT_MS);
};
set('loading');
host.replaceChildren();
const mount = documentRef.createElement('div');
host.append(mount);
loadApi(documentRef, globalRef).then(
(YT) => {
if (destroyed) return;
try {
player = new YT.Player(mount, {
host: YOUTUBE_EMBED_HOST,
videoId,
playerVars: youtubeLivePlayerVars(globalRef.location?.origin),
events: {
onReady: () => {
if (!destroyed) armTimer();
},
onStateChange: (event) => {
if (destroyed) return;
if (event?.data === PLAYING) {
clearTimer();
set('playing');
} else if (event?.data === ENDED) {
clearTimer();
set('offline', 'ended');
}
},
onError: (event) => {
if (destroyed) return;
clearTimer();
const code = Number(event?.data);
if (EMBED_REFUSED.has(code)) set('unavailable', `error-${code}`);
else set('offline', `error-${code}`);
},
},
});
// The API may never call onReady for a video it cannot load.
armTimer();
} catch {
set('offline', 'player');
}
},
() => {
if (!destroyed) set('offline', 'api');
},
);
return {
destroy() {
if (destroyed) return;
destroyed = true;
clearTimer();
try {
player?.destroy?.();
} catch {
// A player half-created has nothing to destroy.
}
player = null;
host.replaceChildren();
},
};
}
+188
View File
@@ -0,0 +1,188 @@
// src/data/youtubeLivePlayer.test.mjs — one live stream in YouTube's player,
// with the player API faked: its states and errors read back as the LIVE
// section's loading / playing / offline / unavailable.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LIVE_START_TIMEOUT_MS,
createYouTubeLivePlayer,
} from './youtubeLivePlayer.js';
import { YOUTUBE_EMBED_HOST } from './liveStreams.js';
/** A stand-in for the panel's host element: counts what is put in it. */
function fakeHost() {
return {
children: [],
replaceChildren() {
this.children = [];
},
append(...nodes) {
this.children.push(...nodes);
},
};
}
/**
* The player as YouTube's API builds it: records its options and lets the
* test fire its events.
*/
function fakeApi() {
const players = [];
class Player {
constructor(mount, options) {
this.mount = mount;
this.options = options;
this.destroyed = 0;
players.push(this);
}
fire(name, data) {
this.options.events[name]?.({ data, target: this });
}
destroy() {
this.destroyed += 1;
}
}
return { YT: { Player }, players };
}
function fixture({ apiFails = false } = {}) {
const api = fakeApi();
const timers = [];
const globalRef = {
location: { origin: 'http://localhost:5190' },
setTimeout(callback, delay) {
const id = timers.length + 1;
timers.push({ id, callback, delay, cleared: false });
return id;
},
clearTimeout(id) {
const timer = timers.find((entry) => entry.id === id);
if (timer) timer.cleared = true;
},
};
const documentRef = { createElement: (tag) => ({ tag }) };
const states = [];
const host = fakeHost();
const player = createYouTubeLivePlayer({
host,
videoId: 'ROboUHfPUrU',
documentRef,
globalRef,
loadApi: () =>
apiFails ? Promise.reject(new Error('blocked')) : Promise.resolve(api.YT),
onChange: (state) => states.push(state),
});
// Let the API promise settle and the player be built.
const settle = () => new Promise((resolve) => setImmediate(resolve));
const pending = () => timers.filter((timer) => !timer.cleared);
return { api, timers, pending, states, host, player, settle };
}
test('the player is built on the privacy host with the live parameters, once the API loads', async () => {
const { api, states, host, settle } = fixture();
assert.deepEqual(states, [{ state: 'loading', reason: null }]);
assert.equal(host.children.length, 1, 'a mount for the iframe is placed');
await settle();
assert.equal(api.players.length, 1);
const { options } = api.players[0];
assert.equal(options.host, YOUTUBE_EMBED_HOST);
assert.equal(options.videoId, 'ROboUHfPUrU');
assert.equal(options.playerVars.enablejsapi, 1);
assert.equal(options.playerVars.mute, 1);
assert.equal(options.playerVars.origin, 'http://localhost:5190');
});
test('playing clears the start timer; the same state is not reported twice', async () => {
const { api, pending, states, settle } = fixture();
await settle();
const [player] = api.players;
player.fire('onReady');
assert.equal(pending().length, 1, 'one start timer is running');
assert.equal(pending()[0].delay, LIVE_START_TIMEOUT_MS);
player.fire('onStateChange', 1);
player.fire('onStateChange', 1);
assert.equal(pending().length, 0, 'the timer went when playback began');
assert.deepEqual(states.at(-1), { state: 'playing', reason: null });
assert.equal(states.length, 2);
});
test('a video that ends, or errors for any other reason, reads as offline', async () => {
const ended = fixture();
await ended.settle();
ended.api.players[0].fire('onStateChange', 0);
assert.deepEqual(ended.states.at(-1), { state: 'offline', reason: 'ended' });
const errored = fixture();
await errored.settle();
errored.api.players[0].fire('onError', 100);
assert.deepEqual(errored.states.at(-1), {
state: 'offline',
reason: 'error-100',
});
assert.equal(errored.pending().length, 0, 'the start timer is cleared');
});
test('embedding refused by the owner is unavailable, which no retry would change', async () => {
for (const code of [101, 150]) {
const { api, states, settle } = fixture();
await settle();
api.players[0].fire('onError', code);
assert.deepEqual(states.at(-1), {
state: 'unavailable',
reason: `error-${code}`,
});
}
});
test('a stream that never starts playing is offline when the start timer runs out', async () => {
const { api, pending, states, settle } = fixture();
await settle();
api.players[0].fire('onReady');
const [timer] = pending();
timer.callback();
assert.deepEqual(states.at(-1), { state: 'offline', reason: 'timeout' });
// Buffering states before the timer do not count as playing.
assert.equal(
states.some((entry) => entry.state === 'playing'),
false,
);
});
test('a timer that fires after playback began changes nothing', async () => {
const { api, timers, states, settle } = fixture();
await settle();
api.players[0].fire('onReady');
api.players[0].fire('onStateChange', 1);
for (const timer of timers) timer.callback();
assert.deepEqual(states.at(-1), { state: 'playing', reason: null });
});
test('an API that does not load reads as offline, which Try again can change', async () => {
const { states, settle } = fixture({ apiFails: true });
await settle();
assert.deepEqual(states.at(-1), { state: 'offline', reason: 'api' });
});
test('destroy empties the host, destroys the player and silences later events', async () => {
const { api, host, pending, player, states, settle } = fixture();
await settle();
const built = api.players[0];
built.fire('onReady');
player.destroy();
player.destroy();
assert.equal(built.destroyed, 1);
assert.equal(host.children.length, 0);
assert.equal(pending().length, 0);
const before = states.length;
built.fire('onStateChange', 1);
built.fire('onError', 150);
assert.equal(states.length, before, 'nothing is reported after destroy');
});
test('destroy before the API loads builds no player', async () => {
const { api, player, states, settle } = fixture();
player.destroy();
await settle();
assert.equal(api.players.length, 0);
assert.deepEqual(states, [{ state: 'loading', reason: null }]);
});
+29
View File
@@ -144,3 +144,32 @@ export function followOffsetFitting(sphere, at, view = {}) {
2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x);
return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range);
}
/**
* The heading, pitch and roll that turn the east-north-up frame at `origin`
* onto `axes`: three unit vectors in the Earth-fixed frame that are a
* body's own x, y and z axes there (a right-handed set). The inverse of the
* renderer's placing of a model by `{heading, pitch, roll}` at a position
* (Cesium's `headingPitchRollToFixedFrame`): heading turns about down,
* pitch about the turned east axis, roll about the body's own x. Radians.
* @param {{x: number, y: number, z: number}} origin
* @param {{x: {x: number, y: number, z: number},
* y: {x: number, y: number, z: number},
* z: {x: number, y: number, z: number}}} axes
* @returns {{heading: number, pitch: number, roll: number}}
*/
export function headingPitchRollOfAxes(origin, axes) {
const enu = eastNorthUp(origin);
// M = ENUᵀ · [x y z]: the body's axes on the local east, north, up.
const m00 = dot(enu.x, axes.x);
const m10 = dot(enu.y, axes.x);
const m20 = dot(enu.z, axes.x);
const m21 = dot(enu.z, axes.y);
const m22 = dot(enu.z, axes.z);
// M = Rz(-heading) · Ry(-pitch) · Rx(roll).
return {
heading: -Math.atan2(m10, m00),
pitch: Math.asin(Math.max(-1, Math.min(1, m20))),
roll: Math.atan2(m21, m22),
};
}
+30
View File
@@ -134,6 +134,7 @@ test('a bad or keyless geocode request never reaches Google', async () => {
]) {
const response = await invokeRoute(routes.get(path), { url });
assert.equal(response.statusCode, 400);
assert.equal(response.headers['cache-control'], 'no-store');
assert.deepEqual(response.body.results, []);
assert.equal(response.body.status, 'REQUEST_DENIED');
}
@@ -144,6 +145,7 @@ test('a bad or keyless geocode request never reaches Google', async () => {
url: '/?address=Austin&lat=30&lon=-97',
});
assert.equal(rejected.statusCode, 405);
assert.equal(rejected.headers['cache-control'], 'no-store');
}
// Keyless is an empty capability, not an outage: a 200 the browser adapters
@@ -167,6 +169,33 @@ test('a bad or keyless geocode request never reaches Google', async () => {
assert.deepEqual(upstream, []);
});
test('only a Geocoding answer is kept by the browser', async () => {
// Google can report a denied key or exhausted quota with HTTP 200.
for (const [httpStatus, status, cacheControl] of [
[200, 'OK', 'private, max-age=300'],
[200, 'ZERO_RESULTS', 'private, max-age=300'],
[200, 'REQUEST_DENIED', 'no-store'],
[200, 'OVER_QUERY_LIMIT', 'no-store'],
[200, 'OVER_DAILY_LIMIT', 'no-store'],
[200, 'UNKNOWN_ERROR', 'no-store'],
[503, 'ZERO_RESULTS', 'no-store'],
]) {
const routes = installRoutes({
fetchImpl: async () =>
Response.json({ status, results: [] }, { status: httpStatus }),
});
for (const path of ['/api/google/geocode', '/api/google/reverse-geocode']) {
const label = `${path} ${httpStatus} ${status}`;
const response = await invokeRoute(routes.get(path), {
url: '/?address=Austin&lat=30&lon=-97',
});
assert.equal(response.statusCode, httpStatus, label);
assert.equal(response.body.status, status, label);
assert.equal(response.headers['cache-control'], cacheControl, label);
}
}
});
test('an upstream failure reaches the browser as fixed public text', async () => {
const routes = installRoutes({
fetchImpl: async () => {
@@ -178,6 +207,7 @@ test('an upstream failure reaches the browser as fixed public text', async () =>
url: '/?address=Austin&lat=30&lon=-97',
});
assert.equal(response.statusCode, 502);
assert.equal(response.headers['cache-control'], 'no-store');
assert.deepEqual(response.body, {
status: 'UNKNOWN_ERROR',
results: [],
+107 -1
View File
@@ -4743,5 +4743,111 @@
"Finding it…": "جارٍ البحث عنه…",
"No reading at this time": "لا توجد قراءة في هذا الوقت",
"Last reading · {age}": "آخر قراءة · {age}",
"Find it": "اعثر عليه"
"Find it": "اعثر عليه",
"Underneath": "تحت",
"Open on YouTube": "فتح على YouTube",
"Video plays from YouTube, which sees your IP address.": "يُشغَّل الفيديو من YouTube، الذي يرى عنوان IP الخاص بك.",
"Automatic": "تلقائي",
"Manual": "يدوي",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "الألواح والمشعّات تتبع الشمس، والأطباق تتجه نحو أقمار الترحيل، والأذرع تتحرك للتوضيح فقط. محسوبة، وليست قياسات حية.",
"Overhead": "فوق المحطة",
"Ahead": "أمام",
"Behind": "خلف",
"Port side": "الجانب الأيسر",
"Starboard side": "الجانب الأيمن",
"Night (shadow)": "ليل (ظل)",
"Sun position": "موضع الشمس",
"Follow the Sun": "اتبع الشمس",
"Fast orbit (40 s)": "مدار سريع (40 ث)",
"Solar arrays": "الألواح الشمسية",
"Demonstration: the real arrays stay extended.": "للتوضيح: الألواح الحقيقية تبقى مفرودة.",
"Retract": "طيّ",
"Extend": "فرد",
"Radiators": "المشعّات",
"Demonstration: the real radiators can fold but stay extended.": "للتوضيح: المشعّات الحقيقية قابلة للطي لكنها تبقى مفرودة.",
"Dishes": "الأطباق",
"Relay satellites": "أقمار الترحيل",
"Up": "أعلى",
"Forward": "أمام",
"Sideways": "جانبًا",
"Shoulder roll": "دوران الكتف",
"Shoulder yaw": "انعراج الكتف",
"Shoulder pitch": "ميل الكتف",
"Elbow": "المرفق",
"Wrist pitch": "ميل المعصم",
"Wrist yaw": "انعراج المعصم",
"Wrist roll": "دوران المعصم",
"Canadarm2 (degrees)": "Canadarm2 (درجات)",
"Resume sway": "استئناف الحركة التلقائية",
"Zoom to the ISS": "تقريب إلى المحطة الدولية",
"Now: in sunlight": "الآن: في ضوء الشمس",
"Now: in the Earth's shadow": "الآن: في ظل الأرض",
"{label} · STATION VIEW": "{label} · منظر المحطة",
"STATION VIEW · {name}": "منظر المحطة · {name}",
"Previous station view": "منظر المحطة السابق",
"Next station view": "منظر المحطة التالي",
"OBSERVATION MODULE · ISS": "وحدة رصد · محطة الفضاء الدولية",
"European Space Agency (ESA)": "وكالة الفضاء الأوروبية (ESA)",
"7 WINDOWS": "7 نوافذ",
"LAUNCHED 8 FEB 2010 · STS-130": "أُطلقت 8 فبراير 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "ترانكويليتي · المنفذ المواجه للأرض",
"LABORATORY MODULE · ISS": "وحدة مختبر · محطة الفضاء الدولية",
"Japan Aerospace Exploration Agency (JAXA)": "وكالة استكشاف الفضاء اليابانية (JAXA)",
"2 WINDOWS": "نافذتان",
"LAUNCHED 31 MAY 2008 · STS-124": "أُطلقت 31 مايو 2008 · STS-124",
"HARMONY · PORT SIDE": "هارموني · الجانب الأيسر",
"Return to the default view": "العودة إلى العرض الافتراضي",
"ON AIR": "على الهواء",
"Starting…": "جارٍ البدء…",
"Stream is offline": "البث غير متاح حاليًا",
"LIVE VIDEO": "فيديو مباشر",
"STREAM ATTACHED TO THE SUBJECT": "بث مرتبط بالعنصر",
"Live video": "الفيديو المباشر",
"Show Live Video": "عرض الفيديو المباشر",
"This stream cannot play here": "لا يمكن تشغيل هذا البث هنا",
"Expand Live section": "توسيع قسم البث المباشر",
"Collapse Live section": "طيّ قسم البث المباشر",
"Expand Live": "توسيع البث المباشر",
"Collapse Live": "طيّ البث المباشر",
"Live streams for the selected object": "البث المباشر للعنصر المحدد",
"Stream": "البث",
"Previous stream": "البث السابق",
"Next stream": "البث التالي",
"Try again": "حاول مرة أخرى",
"Exterior cameras": "الكاميرات الخارجية",
"Live video and space-to-ground audio": "فيديو مباشر وصوت الاتصال بين الفضاء والأرض",
"NASA video, via YouTube": "فيديو ناسا، عبر يوتيوب",
"Controls for the selected space station": "عناصر التحكم في المحطة الفضائية المحددة",
"Expand Station section": "توسيع قسم المحطة",
"Collapse Station section": "طيّ قسم المحطة",
"Expand Station": "توسيع المحطة",
"Collapse Station": "طيّ المحطة",
"Manual · telemetry paused": "يدوي · القياسات متوقفة مؤقتًا",
"Telemetry · updated {ago} ago": "القياسات · آخر تحديث قبل {ago}",
"No signal since {time} · computed values": "لا إشارة منذ {time} · قيم محسوبة",
"No signal · computed values": "لا إشارة · قيم محسوبة",
"Telemetry unavailable · last update {ago} ago · computed values": "القياسات غير متاحة · آخر تحديث قبل {ago} · قيم محسوبة",
"Telemetry unavailable · computed values": "القياسات غير متاحة · قيم محسوبة",
"Telemetry not enabled on this server · computed values": "القياسات غير مفعّلة على هذا الخادم · قيم محسوبة",
"No public telemetry · computed values": "لا توجد قياسات عامة · قيم محسوبة",
"Zoom to Tiangong": "تقريب إلى تيانغونغ",
"Tianhe arm (degrees)": "ذراع تيانهه (درجات)",
"Tianhe wings (degrees)": "أجنحة تيانخه (درجات)",
"Lab wings (degrees)": "أجنحة المختبرين (درجات)",
"Port wing": "الجناح الأيسر",
"Starboard wing": "الجناح الأيمن",
"Wentian forward · alpha": "ونتيان الأمامي · ألفا",
"Wentian forward · beta": "ونتيان الأمامي · بيتا",
"Wentian aft · alpha": "ونتيان الخلفي · ألفا",
"Wentian aft · beta": "ونتيان الخلفي · بيتا",
"Mengtian forward · alpha": "منغتيان الأمامي · ألفا",
"Mengtian forward · beta": "منغتيان الأمامي · بيتا",
"Mengtian aft · alpha": "منغتيان الخلفي · ألفا",
"Mengtian aft · beta": "منغتيان الخلفي · بيتا",
"Wentian arm (degrees)": "ذراع ونتيان (درجات)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "الألواح تتبع الشمس، والهوائي يتجه نحو أقمار التتابع، والأذرع تتمايل للتوضيح. محسوب: الصين لا تنشر قياسات حية.",
"Telemetry reads while the model is on screen": "تُقرأ القياسات أثناء ظهور النموذج على الشاشة",
"Connecting to telemetry…": "جارٍ الاتصال بالقياسات…",
"{seconds} s": "{seconds} ث",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
}
+107 -1
View File
@@ -4319,5 +4319,111 @@
"Finding it…": "Wird gesucht…",
"No reading at this time": "Zu dieser Zeit kein Messwert",
"Last reading · {age}": "Letzter Stand · {age}",
"Find it": "Finden"
"Find it": "Finden",
"Underneath": "Darunter",
"Open on YouTube": "Auf YouTube öffnen",
"Video plays from YouTube, which sees your IP address.": "Das Video wird von YouTube abgespielt, das Ihre IP-Adresse sieht.",
"Automatic": "Automatisch",
"Manual": "Manuell",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Solarflügel und Radiatoren folgen der Sonne, die Antennen richten sich auf Relaissatelliten aus und die Arme bewegen sich zur Veranschaulichung. Berechnet, keine Live-Telemetrie.",
"Overhead": "Über der Station",
"Ahead": "Voraus",
"Behind": "Dahinter",
"Port side": "Backbord",
"Starboard side": "Steuerbord",
"Night (shadow)": "Nacht (Schatten)",
"Sun position": "Sonnenstand",
"Follow the Sun": "Der Sonne folgen",
"Fast orbit (40 s)": "Schneller Umlauf (40 s)",
"Solar arrays": "Solarflügel",
"Demonstration: the real arrays stay extended.": "Demonstration: Die echten Solarflügel bleiben ausgefahren.",
"Retract": "Einfahren",
"Extend": "Ausfahren",
"Radiators": "Radiatoren",
"Demonstration: the real radiators can fold but stay extended.": "Demonstration: Die echten Radiatoren lassen sich falten, bleiben aber ausgefahren.",
"Dishes": "Antennen",
"Relay satellites": "Relaissatelliten",
"Up": "Nach oben",
"Forward": "Nach vorn",
"Sideways": "Zur Seite",
"Shoulder roll": "Schulter-Rollen",
"Shoulder yaw": "Schulter-Gieren",
"Shoulder pitch": "Schulter-Nicken",
"Elbow": "Ellbogen",
"Wrist pitch": "Handgelenk-Nicken",
"Wrist yaw": "Handgelenk-Gieren",
"Wrist roll": "Handgelenk-Rollen",
"Canadarm2 (degrees)": "Canadarm2 (Grad)",
"Resume sway": "Bewegung fortsetzen",
"Zoom to the ISS": "Auf die ISS zoomen",
"Now: in sunlight": "Jetzt: im Sonnenlicht",
"Now: in the Earth's shadow": "Jetzt: im Erdschatten",
"STATION VIEW · {name}": "STATIONSANSICHT · {name}",
"Previous station view": "Vorherige Stationsansicht",
"Next station view": "Nächste Stationsansicht",
"OBSERVATION MODULE · ISS": "BEOBACHTUNGSMODUL · ISS",
"European Space Agency (ESA)": "Europäische Weltraumorganisation (ESA)",
"7 WINDOWS": "7 FENSTER",
"LAUNCHED 8 FEB 2010 · STS-130": "GESTARTET 8. FEB. 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · ERDZUGEWANDTER PORT",
"LABORATORY MODULE · ISS": "LABORMODUL · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Japanische Raumfahrtagentur (JAXA)",
"2 WINDOWS": "2 FENSTER",
"LAUNCHED 31 MAY 2008 · STS-124": "GESTARTET 31. MAI 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · BACKBORDSEITE",
"Return to the default view": "Zur Standardansicht zurückkehren",
"{label} · STATION VIEW": "{label} · STATIONSANSICHT",
"ON AIR": "ON AIR",
"Starting…": "Startet…",
"Stream is offline": "Der Stream ist offline",
"LIVE VIDEO": "LIVE-VIDEO",
"STREAM ATTACHED TO THE SUBJECT": "STREAM ZUM OBJEKT",
"Live video": "Live-Video",
"Show Live Video": "Live-Video anzeigen",
"This stream cannot play here": "Dieser Stream kann hier nicht abgespielt werden",
"Expand Live section": "Live-Bereich ausklappen",
"Collapse Live section": "Live-Bereich einklappen",
"Expand Live": "Live ausklappen",
"Collapse Live": "Live einklappen",
"Live streams for the selected object": "Livestreams zum ausgewählten Objekt",
"Stream": "Stream",
"Previous stream": "Vorheriger Stream",
"Next stream": "Nächster Stream",
"Try again": "Erneut versuchen",
"Exterior cameras": "Außenkameras",
"Live video and space-to-ground audio": "Livevideo und Funkverkehr mit dem Boden",
"NASA video, via YouTube": "NASA-Video, über YouTube",
"Controls for the selected space station": "Steuerung der ausgewählten Raumstation",
"Expand Station section": "Stationsbereich ausklappen",
"Collapse Station section": "Stationsbereich einklappen",
"Expand Station": "Station ausklappen",
"Collapse Station": "Station einklappen",
"Manual · telemetry paused": "Manuell · Telemetrie pausiert",
"Telemetry · updated {ago} ago": "Telemetrie · aktualisiert vor {ago}",
"No signal since {time} · computed values": "Kein Signal seit {time} · berechnete Werte",
"No signal · computed values": "Kein Signal · berechnete Werte",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetrie nicht verfügbar · letzte Aktualisierung vor {ago} · berechnete Werte",
"Telemetry unavailable · computed values": "Telemetrie nicht verfügbar · berechnete Werte",
"Telemetry not enabled on this server · computed values": "Telemetrie auf diesem Server nicht aktiviert · berechnete Werte",
"No public telemetry · computed values": "Keine öffentliche Telemetrie · berechnete Werte",
"Zoom to Tiangong": "Auf Tiangong zoomen",
"Tianhe arm (degrees)": "Tianhe-Arm (Grad)",
"Tianhe wings (degrees)": "Tianhe-Flügel (Grad)",
"Lab wings (degrees)": "Labor-Flügel (Grad)",
"Port wing": "Backbordflügel",
"Starboard wing": "Steuerbordflügel",
"Wentian forward · alpha": "Wentian vorn · Alpha",
"Wentian forward · beta": "Wentian vorn · Beta",
"Wentian aft · alpha": "Wentian hinten · Alpha",
"Wentian aft · beta": "Wentian hinten · Beta",
"Mengtian forward · alpha": "Mengtian vorn · Alpha",
"Mengtian forward · beta": "Mengtian vorn · Beta",
"Mengtian aft · alpha": "Mengtian hinten · Alpha",
"Mengtian aft · beta": "Mengtian hinten · Beta",
"Wentian arm (degrees)": "Wentian-Arm (Grad)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Solarflügel folgen der Sonne, die Antenne richtet sich auf Relaissatelliten und die Arme schwenken zur Veranschaulichung. Berechnet: China veröffentlicht keine Live-Telemetrie.",
"Telemetry reads while the model is on screen": "Telemetrie wird gelesen, solange das Modell zu sehen ist",
"Connecting to telemetry…": "Verbindung zur Telemetrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung."
}
+107 -1
View File
@@ -4425,5 +4425,111 @@
"Finding it…": "Buscando…",
"No reading at this time": "Sin lectura a esta hora",
"Last reading · {age}": "Última lectura · {age}",
"Find it": "Encontrar"
"Find it": "Encontrar",
"Underneath": "Abajo",
"Open on YouTube": "Abrir en YouTube",
"Video plays from YouTube, which sees your IP address.": "El vídeo se reproduce desde YouTube, que ve tu dirección IP.",
"Automatic": "Automático",
"Manual": "Manual",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Los paneles y radiadores siguen al Sol, las antenas apuntan a los satélites de retransmisión y los brazos se mueven a modo de ilustración. Calculado, no es telemetría en vivo.",
"Overhead": "Arriba",
"Ahead": "Delante",
"Behind": "Detrás",
"Port side": "Babor",
"Starboard side": "Estribor",
"Night (shadow)": "Noche (sombra)",
"Sun position": "Posición del Sol",
"Follow the Sun": "Seguir al Sol",
"Fast orbit (40 s)": "Órbita rápida (40 s)",
"Solar arrays": "Paneles solares",
"Demonstration: the real arrays stay extended.": "Demostración: los paneles reales permanecen desplegados.",
"Retract": "Recoger",
"Extend": "Desplegar",
"Radiators": "Radiadores",
"Demonstration: the real radiators can fold but stay extended.": "Demostración: los radiadores reales pueden plegarse, pero permanecen desplegados.",
"Dishes": "Antenas",
"Relay satellites": "Satélites de retransmisión",
"Up": "Arriba",
"Forward": "Adelante",
"Sideways": "De lado",
"Shoulder roll": "Alabeo del hombro",
"Shoulder yaw": "Guiñada del hombro",
"Shoulder pitch": "Cabeceo del hombro",
"Elbow": "Codo",
"Wrist pitch": "Cabeceo de la muñeca",
"Wrist yaw": "Guiñada de la muñeca",
"Wrist roll": "Alabeo de la muñeca",
"Canadarm2 (degrees)": "Canadarm2 (grados)",
"Resume sway": "Reanudar movimiento",
"Zoom to the ISS": "Acercar a la ISS",
"Now: in sunlight": "Ahora: a la luz del Sol",
"Now: in the Earth's shadow": "Ahora: a la sombra de la Tierra",
"{label} · STATION VIEW": "{label} · VISTA DE LA ESTACIÓN",
"STATION VIEW · {name}": "VISTA DE LA ESTACIÓN · {name}",
"Previous station view": "Vista anterior de la estación",
"Next station view": "Siguiente vista de la estación",
"OBSERVATION MODULE · ISS": "MÓDULO DE OBSERVACIÓN · ISS",
"European Space Agency (ESA)": "Agencia Espacial Europea (ESA)",
"7 WINDOWS": "7 VENTANAS",
"LAUNCHED 8 FEB 2010 · STS-130": "LANZADO EL 8 FEB 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PUERTO ORIENTADO A LA TIERRA",
"LABORATORY MODULE · ISS": "MÓDULO LABORATORIO · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agencia Japonesa de Exploración Aeroespacial (JAXA)",
"2 WINDOWS": "2 VENTANAS",
"LAUNCHED 31 MAY 2008 · STS-124": "LANZADO EL 31 MAY 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · LADO DE BABOR",
"Return to the default view": "Volver a la vista predeterminada",
"ON AIR": "EN EL AIRE",
"Starting…": "Iniciando…",
"Stream is offline": "La transmisión está fuera de línea",
"LIVE VIDEO": "VÍDEO EN VIVO",
"STREAM ATTACHED TO THE SUBJECT": "TRANSMISIÓN VINCULADA AL OBJETO",
"Live video": "Vídeo en vivo",
"Show Live Video": "Mostrar Vídeo en vivo",
"This stream cannot play here": "Esta transmisión no se puede reproducir aquí",
"Expand Live section": "Expandir la sección En directo",
"Collapse Live section": "Contraer la sección En directo",
"Expand Live": "Expandir En directo",
"Collapse Live": "Contraer En directo",
"Live streams for the selected object": "Transmisiones en directo del objeto seleccionado",
"Stream": "Transmisión",
"Previous stream": "Transmisión anterior",
"Next stream": "Siguiente transmisión",
"Try again": "Reintentar",
"Exterior cameras": "Cámaras exteriores",
"Live video and space-to-ground audio": "Vídeo en directo y audio espacio-tierra",
"NASA video, via YouTube": "Vídeo de la NASA, vía YouTube",
"Controls for the selected space station": "Controles de la estación espacial seleccionada",
"Expand Station section": "Expandir la sección Estación",
"Collapse Station section": "Contraer la sección Estación",
"Expand Station": "Expandir Estación",
"Collapse Station": "Contraer Estación",
"Manual · telemetry paused": "Manual · telemetría en pausa",
"Telemetry · updated {ago} ago": "Telemetría · actualizada hace {ago}",
"No signal since {time} · computed values": "Sin señal desde las {time} · valores calculados",
"No signal · computed values": "Sin señal · valores calculados",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetría no disponible · última actualización hace {ago} · valores calculados",
"Telemetry unavailable · computed values": "Telemetría no disponible · valores calculados",
"Telemetry not enabled on this server · computed values": "Telemetría no activada en este servidor · valores calculados",
"No public telemetry · computed values": "Sin telemetría pública · valores calculados",
"Zoom to Tiangong": "Acercar a Tiangong",
"Tianhe arm (degrees)": "Brazo de Tianhe (grados)",
"Tianhe wings (degrees)": "Alas de Tianhe (grados)",
"Lab wings (degrees)": "Alas de los laboratorios (grados)",
"Port wing": "Ala de babor",
"Starboard wing": "Ala de estribor",
"Wentian forward · alpha": "Wentian delantera · alfa",
"Wentian forward · beta": "Wentian delantera · beta",
"Wentian aft · alpha": "Wentian trasera · alfa",
"Wentian aft · beta": "Wentian trasera · beta",
"Mengtian forward · alpha": "Mengtian delantera · alfa",
"Mengtian forward · beta": "Mengtian delantera · beta",
"Mengtian aft · alpha": "Mengtian trasera · alfa",
"Mengtian aft · beta": "Mengtian trasera · beta",
"Wentian arm (degrees)": "Brazo de Wentian (grados)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Los paneles siguen al Sol, la antena apunta a los satélites de retransmisión y los brazos se mueven a modo de ilustración. Calculado: China no publica telemetría en directo.",
"Telemetry reads while the model is on screen": "La telemetría se lee mientras el modelo está en pantalla",
"Connecting to telemetry…": "Conectando con la telemetría…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración."
}
+107 -1
View File
@@ -4425,5 +4425,111 @@
"Finding it…": "Recherche…",
"No reading at this time": "Aucune donnée à cette heure",
"Last reading · {age}": "Dernière donnée · {age}",
"Find it": "Retrouver"
"Find it": "Retrouver",
"Underneath": "En dessous",
"Open on YouTube": "Ouvrir sur YouTube",
"Video plays from YouTube, which sees your IP address.": "La vidéo est lue depuis YouTube, qui voit votre adresse IP.",
"Automatic": "Automatique",
"Manual": "Manuel",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Les panneaux et les radiateurs suivent le Soleil, les antennes visent les satellites relais et les bras bougent à titre d'illustration. Calculé, pas de télémétrie en direct.",
"Overhead": "Au-dessus",
"Ahead": "Devant",
"Behind": "Derrière",
"Port side": "Bâbord",
"Starboard side": "Tribord",
"Night (shadow)": "Nuit (ombre)",
"Sun position": "Position du Soleil",
"Follow the Sun": "Suivre le Soleil",
"Fast orbit (40 s)": "Orbite rapide (40 s)",
"Solar arrays": "Panneaux solaires",
"Demonstration: the real arrays stay extended.": "Démonstration : les vrais panneaux restent déployés.",
"Retract": "Rétracter",
"Extend": "Déployer",
"Radiators": "Radiateurs",
"Demonstration: the real radiators can fold but stay extended.": "Démonstration : les vrais radiateurs peuvent se replier mais restent déployés.",
"Dishes": "Antennes",
"Relay satellites": "Satellites relais",
"Up": "Vers le haut",
"Forward": "Vers l'avant",
"Sideways": "Sur le côté",
"Shoulder roll": "Roulis d'épaule",
"Shoulder yaw": "Lacet d'épaule",
"Shoulder pitch": "Tangage d'épaule",
"Elbow": "Coude",
"Wrist pitch": "Tangage du poignet",
"Wrist yaw": "Lacet du poignet",
"Wrist roll": "Roulis du poignet",
"Canadarm2 (degrees)": "Canadarm2 (degrés)",
"Resume sway": "Reprendre le mouvement",
"Zoom to the ISS": "Zoomer sur l'ISS",
"Now: in sunlight": "En ce moment : au soleil",
"Now: in the Earth's shadow": "En ce moment : dans l'ombre de la Terre",
"STATION VIEW · {name}": "VUE DE LA STATION · {name}",
"Previous station view": "Vue précédente de la station",
"Next station view": "Vue suivante de la station",
"OBSERVATION MODULE · ISS": "MODULE D'OBSERVATION · ISS",
"European Space Agency (ESA)": "Agence spatiale européenne (ESA)",
"7 WINDOWS": "7 HUBLOTS",
"LAUNCHED 8 FEB 2010 · STS-130": "LANCÉ LE 8 FÉV. 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PORT ORIENTÉ VERS LA TERRE",
"LABORATORY MODULE · ISS": "MODULE LABORATOIRE · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agence japonaise d'exploration aérospatiale (JAXA)",
"2 WINDOWS": "2 HUBLOTS",
"LAUNCHED 31 MAY 2008 · STS-124": "LANCÉ LE 31 MAI 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · CÔTÉ BÂBORD",
"Return to the default view": "Revenir à la vue par défaut",
"{label} · STATION VIEW": "{label} · VUE DE LA STATION",
"ON AIR": "À L’ANTENNE",
"Starting…": "Démarrage…",
"Stream is offline": "Le flux est hors ligne",
"LIVE VIDEO": "VIDÉO EN DIRECT",
"STREAM ATTACHED TO THE SUBJECT": "FLUX ATTACHÉ À L’OBJET",
"Live video": "Vidéo en direct",
"Show Live Video": "Afficher la vidéo en direct",
"This stream cannot play here": "Ce flux ne peut pas être lu ici",
"Expand Live section": "Déplier la section Direct",
"Collapse Live section": "Replier la section Direct",
"Expand Live": "Déplier Direct",
"Collapse Live": "Replier Direct",
"Live streams for the selected object": "Flux en direct de l’objet sélectionné",
"Stream": "Flux",
"Previous stream": "Flux précédent",
"Next stream": "Flux suivant",
"Try again": "Réessayer",
"Exterior cameras": "Caméras extérieures",
"Live video and space-to-ground audio": "Vidéo en direct et audio espace-sol",
"NASA video, via YouTube": "Vidéo de la NASA, via YouTube",
"Controls for the selected space station": "Commandes de la station spatiale sélectionnée",
"Expand Station section": "Déplier la section Station",
"Collapse Station section": "Replier la section Station",
"Expand Station": "Déplier Station",
"Collapse Station": "Replier Station",
"Manual · telemetry paused": "Manuel · télémétrie en pause",
"Telemetry · updated {ago} ago": "Télémétrie · mise à jour il y a {ago}",
"No signal since {time} · computed values": "Pas de signal depuis {time} · valeurs calculées",
"No signal · computed values": "Pas de signal · valeurs calculées",
"Telemetry unavailable · last update {ago} ago · computed values": "Télémétrie indisponible · dernière mise à jour il y a {ago} · valeurs calculées",
"Telemetry unavailable · computed values": "Télémétrie indisponible · valeurs calculées",
"Telemetry not enabled on this server · computed values": "Télémétrie non activée sur ce serveur · valeurs calculées",
"No public telemetry · computed values": "Pas de télémétrie publique · valeurs calculées",
"Zoom to Tiangong": "Zoomer sur Tiangong",
"Tianhe arm (degrees)": "Bras de Tianhe (degrés)",
"Tianhe wings (degrees)": "Ailes de Tianhe (degrés)",
"Lab wings (degrees)": "Ailes des laboratoires (degrés)",
"Port wing": "Aile bâbord",
"Starboard wing": "Aile tribord",
"Wentian forward · alpha": "Wentian avant · alpha",
"Wentian forward · beta": "Wentian avant · bêta",
"Wentian aft · alpha": "Wentian arrière · alpha",
"Wentian aft · beta": "Wentian arrière · bêta",
"Mengtian forward · alpha": "Mengtian avant · alpha",
"Mengtian forward · beta": "Mengtian avant · bêta",
"Mengtian aft · alpha": "Mengtian arrière · alpha",
"Mengtian aft · beta": "Mengtian arrière · bêta",
"Wentian arm (degrees)": "Bras de Wentian (degrés)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Les panneaux suivent le Soleil, l'antenne vise les satellites relais et les bras oscillent à titre d'illustration. Calculé : la Chine ne publie pas de télémétrie en direct.",
"Telemetry reads while the model is on screen": "La télémétrie est lue tant que le modèle est à l'écran",
"Connecting to telemetry…": "Connexion à la télémétrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration."
}
+107 -1
View File
@@ -4425,5 +4425,111 @@
"Finding it…": "מחפש…",
"No reading at this time": "אין קריאה בזמן הזה",
"Last reading · {age}": "קריאה אחרונה · {age}",
"Find it": "מצא"
"Find it": "מצא",
"Underneath": "מתחת",
"Open on YouTube": "פתיחה ב-YouTube",
"Video plays from YouTube, which sees your IP address.": "הווידאו זורם מ-YouTube, שרואה את כתובת ה-IP שלך.",
"Automatic": "אוטומטי",
"Manual": "ידני",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "הלוחות והרדיאטורים עוקבים אחר השמש, הצלחות מכוונות ללווייני ממסר והזרועות נעות להמחשה בלבד. מחושב, לא טלמטריה חיה.",
"Overhead": "מעל",
"Ahead": "מלפנים",
"Behind": "מאחור",
"Port side": "צד שמאל",
"Starboard side": "צד ימין",
"Night (shadow)": "לילה (צל)",
"Sun position": "מיקום השמש",
"Follow the Sun": "מעקב אחר השמש",
"Fast orbit (40 s)": "הקפה מהירה (40 שנ')",
"Solar arrays": "לוחות סולאריים",
"Demonstration: the real arrays stay extended.": "הדגמה: הלוחות האמיתיים נשארים פרושים.",
"Retract": "קיפול",
"Extend": "פריסה",
"Radiators": "רדיאטורים",
"Demonstration: the real radiators can fold but stay extended.": "הדגמה: הרדיאטורים האמיתיים יכולים להתקפל אך נשארים פרושים.",
"Dishes": "צלחות",
"Relay satellites": "לווייני ממסר",
"Up": "למעלה",
"Forward": "קדימה",
"Sideways": "הצידה",
"Shoulder roll": "גלגול כתף",
"Shoulder yaw": "סבסוב כתף",
"Shoulder pitch": "עלרוד כתף",
"Elbow": "מרפק",
"Wrist pitch": "עלרוד שורש כף היד",
"Wrist yaw": "סבסוב שורש כף היד",
"Wrist roll": "גלגול שורש כף היד",
"Canadarm2 (degrees)": "Canadarm2 (מעלות)",
"Resume sway": "חידוש התנועה",
"Zoom to the ISS": "התקרבות לתחנת החלל",
"Now: in sunlight": "כעת: באור השמש",
"Now: in the Earth's shadow": "כעת: בצל כדור הארץ",
"{label} · STATION VIEW": "{label} · תצוגת התחנה",
"STATION VIEW · {name}": "תצוגת התחנה · {name}",
"Previous station view": "תצוגת התחנה הקודמת",
"Next station view": "תצוגת התחנה הבאה",
"OBSERVATION MODULE · ISS": "מודול תצפית · תחנת החלל",
"European Space Agency (ESA)": "סוכנות החלל האירופית (ESA)",
"7 WINDOWS": "7 חלונות",
"LAUNCHED 8 FEB 2010 · STS-130": "שוגר ב-8 בפברואר 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "טרנקוויליטי · פתח הפונה לכדור הארץ",
"LABORATORY MODULE · ISS": "מודול מעבדה · תחנת החלל",
"Japan Aerospace Exploration Agency (JAXA)": "סוכנות חקר החלל היפנית (JAXA)",
"2 WINDOWS": "2 חלונות",
"LAUNCHED 31 MAY 2008 · STS-124": "שוגר ב-31 במאי 2008 · STS-124",
"HARMONY · PORT SIDE": "הרמוני · צד שמאל",
"Return to the default view": "חזרה לתצוגת ברירת המחדל",
"ON AIR": "בשידור",
"Starting…": "מתחיל…",
"Stream is offline": "השידור אינו פעיל",
"LIVE VIDEO": "וידאו חי",
"STREAM ATTACHED TO THE SUBJECT": "שידור המשויך לפריט",
"Live video": "וידאו חי",
"Show Live Video": "הצגת וידאו חי",
"This stream cannot play here": "לא ניתן להפעיל שידור זה כאן",
"Expand Live section": "הרחבת מקטע השידור החי",
"Collapse Live section": "כיווץ מקטע השידור החי",
"Expand Live": "הרחבת שידור חי",
"Collapse Live": "כיווץ שידור חי",
"Live streams for the selected object": "שידורים חיים של הפריט שנבחר",
"Stream": "שידור",
"Previous stream": "השידור הקודם",
"Next stream": "השידור הבא",
"Try again": "ניסיון חוזר",
"Exterior cameras": "מצלמות חיצוניות",
"Live video and space-to-ground audio": "וידאו חי ושמע חלל–קרקע",
"NASA video, via YouTube": "וידאו של נאס״א, דרך יוטיוב",
"Controls for the selected space station": "בקרות לתחנת החלל שנבחרה",
"Expand Station section": "הרחבת מקטע התחנה",
"Collapse Station section": "כיווץ מקטע התחנה",
"Expand Station": "הרחבת התחנה",
"Collapse Station": "כיווץ התחנה",
"Manual · telemetry paused": "ידני · הטלמטריה מושהית",
"Telemetry · updated {ago} ago": "טלמטריה · עודכנה לפני {ago}",
"No signal since {time} · computed values": "אין אות מאז {time} · ערכים מחושבים",
"No signal · computed values": "אין אות · ערכים מחושבים",
"Telemetry unavailable · last update {ago} ago · computed values": "הטלמטריה אינה זמינה · עדכון אחרון לפני {ago} · ערכים מחושבים",
"Telemetry unavailable · computed values": "הטלמטריה אינה זמינה · ערכים מחושבים",
"Telemetry not enabled on this server · computed values": "הטלמטריה אינה מופעלת בשרת זה · ערכים מחושבים",
"No public telemetry · computed values": "אין טלמטריה ציבורית · ערכים מחושבים",
"Zoom to Tiangong": "התקרבות לטיאנגונג",
"Tianhe arm (degrees)": "זרוע טיאנהה (מעלות)",
"Tianhe wings (degrees)": "כנפי טיאנחה (מעלות)",
"Lab wings (degrees)": "כנפי המעבדות (מעלות)",
"Port wing": "כנף שמאל",
"Starboard wing": "כנף ימין",
"Wentian forward · alpha": "ונטיאן קדמי · אלפא",
"Wentian forward · beta": "ונטיאן קדמי · בטא",
"Wentian aft · alpha": "ונטיאן אחורי · אלפא",
"Wentian aft · beta": "ונטיאן אחורי · בטא",
"Mengtian forward · alpha": "מנגטיאן קדמי · אלפא",
"Mengtian forward · beta": "מנגטיאן קדמי · בטא",
"Mengtian aft · alpha": "מנגטיאן אחורי · אלפא",
"Mengtian aft · beta": "מנגטיאן אחורי · בטא",
"Wentian arm (degrees)": "זרוע ונטיאן (מעלות)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "הלוחות עוקבים אחר השמש, האנטנה מכוונת ללווייני ממסר והזרועות נעות לצורכי הדגמה. מחושב: סין אינה מפרסמת טלמטריה חיה.",
"Telemetry reads while the model is on screen": "הטלמטריה נקראת כל עוד הדגם מוצג על המסך",
"Connecting to telemetry…": "מתחבר לטלמטריה…",
"{seconds} s": "{seconds} שנ׳",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
}
+107 -1
View File
@@ -4425,5 +4425,111 @@
"Finding it…": "Ricerca in corso…",
"No reading at this time": "Nessun dato a quest'ora",
"Last reading · {age}": "Ultimo dato · {age}",
"Find it": "Trova"
"Find it": "Trova",
"Underneath": "Sotto",
"Open on YouTube": "Apri su YouTube",
"Video plays from YouTube, which sees your IP address.": "Il video viene riprodotto da YouTube, che vede il tuo indirizzo IP.",
"Automatic": "Automatico",
"Manual": "Manuale",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Pannelli e radiatori seguono il Sole, le antenne puntano ai satelliti di collegamento e i bracci si muovono a scopo illustrativo. Calcolato, non telemetria in diretta.",
"Overhead": "Sopra",
"Ahead": "Davanti",
"Behind": "Dietro",
"Port side": "Babordo",
"Starboard side": "Tribordo",
"Night (shadow)": "Notte (ombra)",
"Sun position": "Posizione del Sole",
"Follow the Sun": "Segui il Sole",
"Fast orbit (40 s)": "Orbita veloce (40 s)",
"Solar arrays": "Pannelli solari",
"Demonstration: the real arrays stay extended.": "Dimostrazione: i pannelli reali restano dispiegati.",
"Retract": "Ritira",
"Extend": "Dispiega",
"Radiators": "Radiatori",
"Demonstration: the real radiators can fold but stay extended.": "Dimostrazione: i radiatori reali possono ripiegarsi ma restano dispiegati.",
"Dishes": "Antenne",
"Relay satellites": "Satelliti di collegamento",
"Up": "In alto",
"Forward": "In avanti",
"Sideways": "Di lato",
"Shoulder roll": "Rollio spalla",
"Shoulder yaw": "Imbardata spalla",
"Shoulder pitch": "Beccheggio spalla",
"Elbow": "Gomito",
"Wrist pitch": "Beccheggio polso",
"Wrist yaw": "Imbardata polso",
"Wrist roll": "Rollio polso",
"Canadarm2 (degrees)": "Canadarm2 (gradi)",
"Resume sway": "Riprendi movimento",
"Zoom to the ISS": "Zoom sulla ISS",
"Now: in sunlight": "Ora: alla luce del Sole",
"Now: in the Earth's shadow": "Ora: nell'ombra della Terra",
"STATION VIEW · {name}": "VISTA DELLA STAZIONE · {name}",
"Previous station view": "Vista precedente della stazione",
"Next station view": "Vista successiva della stazione",
"OBSERVATION MODULE · ISS": "MODULO DI OSSERVAZIONE · ISS",
"European Space Agency (ESA)": "Agenzia Spaziale Europea (ESA)",
"7 WINDOWS": "7 FINESTRINI",
"LAUNCHED 8 FEB 2010 · STS-130": "LANCIATO L’8 FEB 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PORTELLONE RIVOLTO ALLA TERRA",
"LABORATORY MODULE · ISS": "MODULO LABORATORIO · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agenzia Giapponese per l’Esplorazione Aerospaziale (JAXA)",
"2 WINDOWS": "2 FINESTRINI",
"LAUNCHED 31 MAY 2008 · STS-124": "LANCIATO IL 31 MAG 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · LATO DI BABORDO",
"Return to the default view": "Torna alla vista predefinita",
"{label} · STATION VIEW": "{label} · VISTA DELLA STAZIONE",
"ON AIR": "IN ONDA",
"Starting…": "Avvio…",
"Stream is offline": "La diretta è offline",
"LIVE VIDEO": "VIDEO LIVE",
"STREAM ATTACHED TO THE SUBJECT": "DIRETTA COLLEGATA ALL’OGGETTO",
"Live video": "Video live",
"Show Live Video": "Mostra Video live",
"This stream cannot play here": "Questa diretta non può essere riprodotta qui",
"Expand Live section": "Espandi la sezione Live",
"Collapse Live section": "Comprimi la sezione Live",
"Expand Live": "Espandi Live",
"Collapse Live": "Comprimi Live",
"Live streams for the selected object": "Dirette dell’oggetto selezionato",
"Stream": "Diretta",
"Previous stream": "Diretta precedente",
"Next stream": "Diretta successiva",
"Try again": "Riprova",
"Exterior cameras": "Telecamere esterne",
"Live video and space-to-ground audio": "Video in diretta e audio spazio-terra",
"NASA video, via YouTube": "Video NASA, tramite YouTube",
"Controls for the selected space station": "Controlli della stazione spaziale selezionata",
"Expand Station section": "Espandi la sezione Stazione",
"Collapse Station section": "Comprimi la sezione Stazione",
"Expand Station": "Espandi Stazione",
"Collapse Station": "Comprimi Stazione",
"Manual · telemetry paused": "Manuale · telemetria in pausa",
"Telemetry · updated {ago} ago": "Telemetria · aggiornata {ago} fa",
"No signal since {time} · computed values": "Nessun segnale dalle {time} · valori calcolati",
"No signal · computed values": "Nessun segnale · valori calcolati",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetria non disponibile · ultimo aggiornamento {ago} fa · valori calcolati",
"Telemetry unavailable · computed values": "Telemetria non disponibile · valori calcolati",
"Telemetry not enabled on this server · computed values": "Telemetria non attivata su questo server · valori calcolati",
"No public telemetry · computed values": "Nessuna telemetria pubblica · valori calcolati",
"Zoom to Tiangong": "Zoom su Tiangong",
"Tianhe arm (degrees)": "Braccio di Tianhe (gradi)",
"Tianhe wings (degrees)": "Ali di Tianhe (gradi)",
"Lab wings (degrees)": "Ali dei laboratori (gradi)",
"Port wing": "Ala di sinistra",
"Starboard wing": "Ala di dritta",
"Wentian forward · alpha": "Wentian anteriore · alfa",
"Wentian forward · beta": "Wentian anteriore · beta",
"Wentian aft · alpha": "Wentian posteriore · alfa",
"Wentian aft · beta": "Wentian posteriore · beta",
"Mengtian forward · alpha": "Mengtian anteriore · alfa",
"Mengtian forward · beta": "Mengtian anteriore · beta",
"Mengtian aft · alpha": "Mengtian posteriore · alfa",
"Mengtian aft · beta": "Mengtian posteriore · beta",
"Wentian arm (degrees)": "Braccio di Wentian (gradi)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "I pannelli seguono il Sole, l'antenna punta ai satelliti di collegamento e i bracci oscillano a scopo illustrativo. Calcolato: la Cina non pubblica telemetria in tempo reale.",
"Telemetry reads while the model is on screen": "La telemetria viene letta finché il modello è sullo schermo",
"Connecting to telemetry…": "Connessione alla telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo."
}
+107 -1
View File
@@ -4213,5 +4213,111 @@
"Finding it…": "検索中…",
"No reading at this time": "この時刻のデータなし",
"Last reading · {age}": "最終データ・{age}",
"Find it": "探す"
"Find it": "探す",
"Underneath": "真下",
"Open on YouTube": "YouTubeで開く",
"Video plays from YouTube, which sees your IP address.": "動画は YouTube から再生され、YouTube にはあなたの IP アドレスが見えます。",
"Automatic": "自動",
"Manual": "手動",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "太陽電池パネルとラジエーターは太陽を追い、アンテナは中継衛星を向き、アームは説明用にゆっくり動きます。計算による表示で、実際のテレメトリではありません。",
"Overhead": "真上",
"Ahead": "前方",
"Behind": "後方",
"Port side": "左舷",
"Starboard side": "右舷",
"Night (shadow)": "夜(影)",
"Sun position": "太陽の位置",
"Follow the Sun": "太陽を追う",
"Fast orbit (40 s)": "高速周回(40秒)",
"Solar arrays": "太陽電池パネル",
"Demonstration: the real arrays stay extended.": "デモ表示:実際のパネルは展開したままです。",
"Retract": "収納",
"Extend": "展開",
"Radiators": "ラジエーター",
"Demonstration: the real radiators can fold but stay extended.": "デモ表示:実際のラジエーターは折りたためますが、展開したままです。",
"Dishes": "アンテナ",
"Relay satellites": "中継衛星",
"Up": "上",
"Forward": "前",
"Sideways": "横",
"Shoulder roll": "肩ロール",
"Shoulder yaw": "肩ヨー",
"Shoulder pitch": "肩ピッチ",
"Elbow": "肘",
"Wrist pitch": "手首ピッチ",
"Wrist yaw": "手首ヨー",
"Wrist roll": "手首ロール",
"Canadarm2 (degrees)": "Canadarm2(度)",
"Resume sway": "自動の動きに戻す",
"Zoom to the ISS": "ISSにズーム",
"Now: in sunlight": "現在:日なた",
"Now: in the Earth's shadow": "現在:地球の影の中",
"STATION VIEW · {name}": "ステーションビュー · {name}",
"Previous station view": "前のステーションビュー",
"Next station view": "次のステーションビュー",
"OBSERVATION MODULE · ISS": "観測モジュール · ISS",
"European Space Agency (ESA)": "欧州宇宙機関(ESA)",
"7 WINDOWS": "窓 7 枚",
"LAUNCHED 8 FEB 2010 · STS-130": "2010年2月8日打ち上げ · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "トランクウィリティー · 地球側ポート",
"LABORATORY MODULE · ISS": "実験モジュール · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "宇宙航空研究開発機構(JAXA)",
"2 WINDOWS": "窓 2 枚",
"LAUNCHED 31 MAY 2008 · STS-124": "2008年5月31日打ち上げ · STS-124",
"HARMONY · PORT SIDE": "ハーモニー · 左舷側",
"Return to the default view": "既定のビューに戻す",
"{label} · STATION VIEW": "{label} · ステーションビュー",
"ON AIR": "オンエア",
"Starting…": "開始しています…",
"Stream is offline": "ストリームはオフラインです",
"LIVE VIDEO": "ライブ映像",
"STREAM ATTACHED TO THE SUBJECT": "対象に紐づくライブ配信",
"Live video": "ライブ映像",
"Show Live Video": "ライブ映像を表示",
"This stream cannot play here": "このストリームはここでは再生できません",
"Expand Live section": "ライブセクションを展開",
"Collapse Live section": "ライブセクションを折りたたむ",
"Expand Live": "ライブを展開",
"Collapse Live": "ライブを折りたたむ",
"Live streams for the selected object": "選択中のオブジェクトのライブ配信",
"Stream": "ストリーム",
"Previous stream": "前のストリーム",
"Next stream": "次のストリーム",
"Try again": "再試行",
"Exterior cameras": "船外カメラ",
"Live video and space-to-ground audio": "ライブ映像と地上との交信音声",
"NASA video, via YouTube": "NASAの映像、YouTube経由",
"Controls for the selected space station": "選択中の宇宙ステーションの操作",
"Expand Station section": "ステーションセクションを展開",
"Collapse Station section": "ステーションセクションを折りたたむ",
"Expand Station": "ステーションを展開",
"Collapse Station": "ステーションを折りたたむ",
"Manual · telemetry paused": "手動 · テレメトリ一時停止",
"Telemetry · updated {ago} ago": "テレメトリ · {ago}前に更新",
"No signal since {time} · computed values": "{time}から信号なし · 計算値",
"No signal · computed values": "信号なし · 計算値",
"Telemetry unavailable · last update {ago} ago · computed values": "テレメトリ利用不可 · 最終更新は{ago}前 · 計算値",
"Telemetry unavailable · computed values": "テレメトリ利用不可 · 計算値",
"Telemetry not enabled on this server · computed values": "このサーバーではテレメトリが無効 · 計算値",
"No public telemetry · computed values": "公開テレメトリなし · 計算値",
"Zoom to Tiangong": "天宮にズーム",
"Tianhe arm (degrees)": "天和アーム(度)",
"Tianhe wings (degrees)": "天和の翼(度)",
"Lab wings (degrees)": "実験モジュールの翼(度)",
"Port wing": "左舷の翼",
"Starboard wing": "右舷の翼",
"Wentian forward · alpha": "問天 前方 · アルファ",
"Wentian forward · beta": "問天 前方 · ベータ",
"Wentian aft · alpha": "問天 後方 · アルファ",
"Wentian aft · beta": "問天 後方 · ベータ",
"Mengtian forward · alpha": "夢天 前方 · アルファ",
"Mengtian forward · beta": "夢天 前方 · ベータ",
"Mengtian aft · alpha": "夢天 後方 · アルファ",
"Mengtian aft · beta": "夢天 後方 · ベータ",
"Wentian arm (degrees)": "問天アーム(度)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "太陽電池パネルは太陽を追い、アンテナは中継衛星に向き、アームは説明のために揺れます。計算値:中国はライブテレメトリを公開していません。",
"Telemetry reads while the model is on screen": "テレメトリはモデルが画面にある間に読み取られます",
"Connecting to telemetry…": "テレメトリに接続中…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
}
+107 -1
View File
@@ -4425,5 +4425,111 @@
"Finding it…": "A procurar…",
"No reading at this time": "Sem leitura nesta hora",
"Last reading · {age}": "Última leitura · {age}",
"Find it": "Encontrar"
"Find it": "Encontrar",
"Underneath": "Embaixo",
"Open on YouTube": "Abrir no YouTube",
"Video plays from YouTube, which sees your IP address.": "O vídeo é reproduzido a partir do YouTube, que vê o seu endereço IP.",
"Automatic": "Automático",
"Manual": "Manual",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Painéis e radiadores seguem o Sol, as antenas apontam para os satélites de retransmissão e os braços se movem de forma ilustrativa. Calculado, não é telemetria ao vivo.",
"Overhead": "Em cima",
"Ahead": "À frente",
"Behind": "Atrás",
"Port side": "Bombordo",
"Starboard side": "Estibordo",
"Night (shadow)": "Noite (sombra)",
"Sun position": "Posição do Sol",
"Follow the Sun": "Seguir o Sol",
"Fast orbit (40 s)": "Órbita acelerada (40 s)",
"Solar arrays": "Painéis solares",
"Demonstration: the real arrays stay extended.": "Demonstração: os painéis reais ficam abertos.",
"Retract": "Recolher",
"Extend": "Expandir",
"Radiators": "Radiadores",
"Demonstration: the real radiators can fold but stay extended.": "Demonstração: os radiadores reais podem dobrar, mas ficam abertos.",
"Dishes": "Antenas",
"Relay satellites": "Satélites de retransmissão",
"Up": "Para cima",
"Forward": "Para frente",
"Sideways": "Para o lado",
"Shoulder roll": "Ombro (giro)",
"Shoulder yaw": "Ombro (guinada)",
"Shoulder pitch": "Ombro (arfagem)",
"Elbow": "Cotovelo",
"Wrist pitch": "Pulso (arfagem)",
"Wrist yaw": "Pulso (guinada)",
"Wrist roll": "Pulso (giro)",
"Canadarm2 (degrees)": "Canadarm2 (graus)",
"Resume sway": "Retomar movimento",
"Zoom to the ISS": "Aproximar da ISS",
"Now: in sunlight": "Agora: na luz do Sol",
"Now: in the Earth's shadow": "Agora: na sombra da Terra",
"STATION VIEW · {name}": "VISTA DA ESTAÇÃO · {name}",
"Previous station view": "Vista anterior da estação",
"Next station view": "Próxima vista da estação",
"OBSERVATION MODULE · ISS": "MÓDULO DE OBSERVAÇÃO · ISS",
"European Space Agency (ESA)": "Agência Espacial Europeia (ESA)",
"7 WINDOWS": "7 JANELAS",
"LAUNCHED 8 FEB 2010 · STS-130": "LANÇADO EM 8 FEV 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PORTA VOLTADA PARA A TERRA",
"LABORATORY MODULE · ISS": "MÓDULO LABORATÓRIO · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agência de Exploração Aeroespacial do Japão (JAXA)",
"2 WINDOWS": "2 JANELAS",
"LAUNCHED 31 MAY 2008 · STS-124": "LANÇADO EM 31 MAI 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · LADO BOMBORDO",
"Return to the default view": "Voltar à vista padrão",
"{label} · STATION VIEW": "{label} · VISTA DA ESTAÇÃO",
"ON AIR": "NO AR",
"Starting…": "A iniciar…",
"Stream is offline": "A transmissão está offline",
"LIVE VIDEO": "VÍDEO AO VIVO",
"STREAM ATTACHED TO THE SUBJECT": "TRANSMISSÃO VINCULADA AO OBJETO",
"Live video": "Vídeo ao vivo",
"Show Live Video": "Mostrar vídeo ao vivo",
"This stream cannot play here": "Esta transmissão não pode ser reproduzida aqui",
"Expand Live section": "Expandir a secção Ao vivo",
"Collapse Live section": "Recolher a secção Ao vivo",
"Expand Live": "Expandir Ao vivo",
"Collapse Live": "Recolher Ao vivo",
"Live streams for the selected object": "Transmissões ao vivo do objeto selecionado",
"Stream": "Transmissão",
"Previous stream": "Transmissão anterior",
"Next stream": "Próxima transmissão",
"Try again": "Tentar novamente",
"Exterior cameras": "Câmaras exteriores",
"Live video and space-to-ground audio": "Vídeo ao vivo e áudio espaço-terra",
"NASA video, via YouTube": "Vídeo da NASA, via YouTube",
"Controls for the selected space station": "Controlos da estação espacial selecionada",
"Expand Station section": "Expandir a secção Estação",
"Collapse Station section": "Recolher a secção Estação",
"Expand Station": "Expandir Estação",
"Collapse Station": "Recolher Estação",
"Manual · telemetry paused": "Manual · telemetria em pausa",
"Telemetry · updated {ago} ago": "Telemetria · atualizada há {ago}",
"No signal since {time} · computed values": "Sem sinal desde as {time} · valores calculados",
"No signal · computed values": "Sem sinal · valores calculados",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetria indisponível · última atualização há {ago} · valores calculados",
"Telemetry unavailable · computed values": "Telemetria indisponível · valores calculados",
"Telemetry not enabled on this server · computed values": "Telemetria não ativada neste servidor · valores calculados",
"No public telemetry · computed values": "Sem telemetria pública · valores calculados",
"Zoom to Tiangong": "Aproximar de Tiangong",
"Tianhe arm (degrees)": "Braço de Tianhe (graus)",
"Tianhe wings (degrees)": "Asas de Tianhe (graus)",
"Lab wings (degrees)": "Asas dos laboratórios (graus)",
"Port wing": "Asa de bombordo",
"Starboard wing": "Asa de estibordo",
"Wentian forward · alpha": "Wentian dianteira · alfa",
"Wentian forward · beta": "Wentian dianteira · beta",
"Wentian aft · alpha": "Wentian traseira · alfa",
"Wentian aft · beta": "Wentian traseira · beta",
"Mengtian forward · alpha": "Mengtian dianteira · alfa",
"Mengtian forward · beta": "Mengtian dianteira · beta",
"Mengtian aft · alpha": "Mengtian traseira · alfa",
"Mengtian aft · beta": "Mengtian traseira · beta",
"Wentian arm (degrees)": "Braço de Wentian (graus)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Os painéis seguem o Sol, a antena aponta para os satélites de retransmissão e os braços oscilam a título ilustrativo. Calculado: a China não publica telemetria em direto.",
"Telemetry reads while the model is on screen": "A telemetria é lida enquanto o modelo está no ecrã",
"Connecting to telemetry…": "A ligar à telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa."
}
+107 -1
View File
@@ -4531,5 +4531,111 @@
"Finding it…": "Поиск…",
"No reading at this time": "Нет данных на это время",
"Last reading · {age}": "Последние данные · {age}",
"Find it": "Найти"
"Find it": "Найти",
"Underneath": "Снизу",
"Open on YouTube": "Открыть на YouTube",
"Video plays from YouTube, which sees your IP address.": "Видео воспроизводится с YouTube, который видит ваш IP-адрес.",
"Automatic": "Автоматически",
"Manual": "Вручную",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Панели и радиаторы следят за Солнцем, антенны наводятся на спутники-ретрансляторы, а манипуляторы движутся для иллюстрации. Расчёт, а не телеметрия в реальном времени.",
"Overhead": "Сверху",
"Ahead": "Спереди",
"Behind": "Сзади",
"Port side": "Левый борт",
"Starboard side": "Правый борт",
"Night (shadow)": "Ночь (тень)",
"Sun position": "Положение Солнца",
"Follow the Sun": "Следить за Солнцем",
"Fast orbit (40 s)": "Быстрый виток (40 с)",
"Solar arrays": "Солнечные батареи",
"Demonstration: the real arrays stay extended.": "Демонстрация: настоящие батареи остаются раскрытыми.",
"Retract": "Сложить",
"Extend": "Раскрыть",
"Radiators": "Радиаторы",
"Demonstration: the real radiators can fold but stay extended.": "Демонстрация: настоящие радиаторы складываются, но остаются раскрытыми.",
"Dishes": "Антенны",
"Relay satellites": "Спутники-ретрансляторы",
"Up": "Вверх",
"Forward": "Вперёд",
"Sideways": "В сторону",
"Shoulder roll": "Плечо: крен",
"Shoulder yaw": "Плечо: рыскание",
"Shoulder pitch": "Плечо: тангаж",
"Elbow": "Локоть",
"Wrist pitch": "Запястье: тангаж",
"Wrist yaw": "Запястье: рыскание",
"Wrist roll": "Запястье: крен",
"Canadarm2 (degrees)": "Canadarm2 (градусы)",
"Resume sway": "Возобновить движение",
"Zoom to the ISS": "Приблизить к МКС",
"Now: in sunlight": "Сейчас: на свету",
"Now: in the Earth's shadow": "Сейчас: в тени Земли",
"STATION VIEW · {name}": "ВИД СО СТАНЦИИ · {name}",
"Previous station view": "Предыдущий вид со станции",
"Next station view": "Следующий вид со станции",
"OBSERVATION MODULE · ISS": "МОДУЛЬ НАБЛЮДЕНИЯ · МКС",
"European Space Agency (ESA)": "Европейское космическое агентство (ЕКА)",
"7 WINDOWS": "7 ИЛЛЮМИНАТОРОВ",
"LAUNCHED 8 FEB 2010 · STS-130": "ЗАПУЩЕН 8 ФЕВ 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · ПОРТ, ОБРАЩЁННЫЙ К ЗЕМЛЕ",
"LABORATORY MODULE · ISS": "ЛАБОРАТОРНЫЙ МОДУЛЬ · МКС",
"Japan Aerospace Exploration Agency (JAXA)": "Японское агентство аэрокосмических исследований (JAXA)",
"2 WINDOWS": "2 ИЛЛЮМИНАТОРА",
"LAUNCHED 31 MAY 2008 · STS-124": "ЗАПУЩЕН 31 МАЯ 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · ЛЕВЫЙ БОРТ",
"Return to the default view": "Вернуть вид по умолчанию",
"{label} · STATION VIEW": "{label} · ВИД СО СТАНЦИИ",
"ON AIR": "В ЭФИРЕ",
"Starting…": "Запуск…",
"Stream is offline": "Трансляция не ведётся",
"LIVE VIDEO": "ВИДЕО ОНЛАЙН",
"STREAM ATTACHED TO THE SUBJECT": "ТРАНСЛЯЦИЯ ВЫБРАННОГО ОБЪЕКТА",
"Live video": "Видео онлайн",
"Show Live Video": "Показать видео онлайн",
"This stream cannot play here": "Эту трансляцию нельзя воспроизвести здесь",
"Expand Live section": "Развернуть раздел «Эфир»",
"Collapse Live section": "Свернуть раздел «Эфир»",
"Expand Live": "Развернуть «Эфир»",
"Collapse Live": "Свернуть «Эфир»",
"Live streams for the selected object": "Прямые трансляции выбранного объекта",
"Stream": "Трансляция",
"Previous stream": "Предыдущая трансляция",
"Next stream": "Следующая трансляция",
"Try again": "Повторить",
"Exterior cameras": "Внешние камеры",
"Live video and space-to-ground audio": "Прямое видео и переговоры с Землёй",
"NASA video, via YouTube": "Видео NASA, через YouTube",
"Controls for the selected space station": "Управление выбранной космической станцией",
"Expand Station section": "Развернуть раздел «Станция»",
"Collapse Station section": "Свернуть раздел «Станция»",
"Expand Station": "Развернуть «Станцию»",
"Collapse Station": "Свернуть «Станцию»",
"Manual · telemetry paused": "Вручную · телеметрия приостановлена",
"Telemetry · updated {ago} ago": "Телеметрия · обновлено {ago} назад",
"No signal since {time} · computed values": "Нет сигнала с {time} · расчётные значения",
"No signal · computed values": "Нет сигнала · расчётные значения",
"Telemetry unavailable · last update {ago} ago · computed values": "Телеметрия недоступна · последнее обновление {ago} назад · расчётные значения",
"Telemetry unavailable · computed values": "Телеметрия недоступна · расчётные значения",
"Telemetry not enabled on this server · computed values": "Телеметрия не включена на этом сервере · расчётные значения",
"No public telemetry · computed values": "Открытой телеметрии нет · расчётные значения",
"Zoom to Tiangong": "Приблизить к «Тяньгун»",
"Tianhe arm (degrees)": "Манипулятор «Тяньхэ» (градусы)",
"Tianhe wings (degrees)": "Крылья «Тяньхэ» (градусы)",
"Lab wings (degrees)": "Крылья лабораторий (градусы)",
"Port wing": "Левое крыло",
"Starboard wing": "Правое крыло",
"Wentian forward · alpha": "«Вэньтянь», передняя · альфа",
"Wentian forward · beta": "«Вэньтянь», передняя · бета",
"Wentian aft · alpha": "«Вэньтянь», задняя · альфа",
"Wentian aft · beta": "«Вэньтянь», задняя · бета",
"Mengtian forward · alpha": "«Мэнтянь», передняя · альфа",
"Mengtian forward · beta": "«Мэнтянь», передняя · бета",
"Mengtian aft · alpha": "«Мэнтянь», задняя · альфа",
"Mengtian aft · beta": "«Мэнтянь», задняя · бета",
"Wentian arm (degrees)": "Манипулятор «Вэньтянь» (градусы)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Панели следят за Солнцем, антенна наводится на спутники-ретрансляторы, а манипуляторы покачиваются для наглядности. Расчёт: Китай не публикует телеметрию в реальном времени.",
"Telemetry reads while the model is on screen": "Телеметрия читается, пока модель на экране",
"Connecting to telemetry…": "Подключение к телеметрии…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
}
+107 -1
View File
@@ -4319,5 +4319,111 @@
"Finding it…": "Söker…",
"No reading at this time": "Ingen avläsning vid den här tiden",
"Last reading · {age}": "Senaste avläsning · {age}",
"Find it": "Hitta"
"Find it": "Hitta",
"Underneath": "Nedanför",
"Open on YouTube": "Öppna på YouTube",
"Video plays from YouTube, which sees your IP address.": "Videon spelas upp från YouTube, som ser din IP-adress.",
"Automatic": "Automatiskt",
"Manual": "Manuellt",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Paneler och radiatorer följer solen, antennerna riktas mot relästationer i rymden och armarna rör sig som illustration. Beräknat, inte telemetri i realtid.",
"Overhead": "Ovanför",
"Ahead": "Framför",
"Behind": "Bakom",
"Port side": "Babord",
"Starboard side": "Styrbord",
"Night (shadow)": "Natt (skugga)",
"Sun position": "Solens läge",
"Follow the Sun": "Följ solen",
"Fast orbit (40 s)": "Snabbt varv (40 s)",
"Solar arrays": "Solpaneler",
"Demonstration: the real arrays stay extended.": "Demonstration: de verkliga panelerna förblir utfällda.",
"Retract": "Fäll in",
"Extend": "Fäll ut",
"Radiators": "Radiatorer",
"Demonstration: the real radiators can fold but stay extended.": "Demonstration: de verkliga radiatorerna kan vikas men förblir utfällda.",
"Dishes": "Antenner",
"Relay satellites": "Reläsatelliter",
"Up": "Uppåt",
"Forward": "Framåt",
"Sideways": "Åt sidan",
"Shoulder roll": "Axel, roll",
"Shoulder yaw": "Axel, gir",
"Shoulder pitch": "Axel, tipp",
"Elbow": "Armbåge",
"Wrist pitch": "Handled, tipp",
"Wrist yaw": "Handled, gir",
"Wrist roll": "Handled, roll",
"Canadarm2 (degrees)": "Canadarm2 (grader)",
"Resume sway": "Återuppta rörelsen",
"Zoom to the ISS": "Zooma in på ISS",
"Now: in sunlight": "Nu: i solljus",
"Now: in the Earth's shadow": "Nu: i jordens skugga",
"{label} · STATION VIEW": "{label} · STATIONSVY",
"STATION VIEW · {name}": "STATIONSVY · {name}",
"Previous station view": "Föregående stationsvy",
"Next station view": "Nästa stationsvy",
"OBSERVATION MODULE · ISS": "OBSERVATIONSMODUL · ISS",
"European Space Agency (ESA)": "Europeiska rymdorganisationen (ESA)",
"7 WINDOWS": "7 FÖNSTER",
"LAUNCHED 8 FEB 2010 · STS-130": "UPPSKJUTEN 8 FEB 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · DOCKNINGSPORT MOT JORDEN",
"LABORATORY MODULE · ISS": "LABORATORIEMODUL · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Japans rymdorganisation (JAXA)",
"2 WINDOWS": "2 FÖNSTER",
"LAUNCHED 31 MAY 2008 · STS-124": "UPPSKJUTEN 31 MAJ 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · BABORDSSIDAN",
"Return to the default view": "Återgå till standardvyn",
"ON AIR": "PÅ LUFTEN",
"Starting…": "Startar…",
"Stream is offline": "Strömmen är offline",
"LIVE VIDEO": "LIVEVIDEO",
"STREAM ATTACHED TO THE SUBJECT": "STRÖM KNUTEN TILL OBJEKTET",
"Live video": "Livevideo",
"Show Live Video": "Visa livevideo",
"This stream cannot play here": "Den här strömmen kan inte spelas upp här",
"Expand Live section": "Expandera Live-sektionen",
"Collapse Live section": "Fäll ihop Live-sektionen",
"Expand Live": "Expandera Live",
"Collapse Live": "Fäll ihop Live",
"Live streams for the selected object": "Liveströmmar för det valda objektet",
"Stream": "Ström",
"Previous stream": "Föregående ström",
"Next stream": "Nästa ström",
"Try again": "Försök igen",
"Exterior cameras": "Yttre kameror",
"Live video and space-to-ground audio": "Livevideo och ljud rymd–mark",
"NASA video, via YouTube": "NASA-video, via YouTube",
"Controls for the selected space station": "Reglage för den valda rymdstationen",
"Expand Station section": "Expandera Station-sektionen",
"Collapse Station section": "Fäll ihop Station-sektionen",
"Expand Station": "Expandera Station",
"Collapse Station": "Fäll ihop Station",
"Manual · telemetry paused": "Manuellt · telemetri pausad",
"Telemetry · updated {ago} ago": "Telemetri · uppdaterad för {ago} sedan",
"No signal since {time} · computed values": "Ingen signal sedan {time} · beräknade värden",
"No signal · computed values": "Ingen signal · beräknade värden",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetri otillgänglig · senast uppdaterad för {ago} sedan · beräknade värden",
"Telemetry unavailable · computed values": "Telemetri otillgänglig · beräknade värden",
"Telemetry not enabled on this server · computed values": "Telemetri inte aktiverad på den här servern · beräknade värden",
"No public telemetry · computed values": "Ingen offentlig telemetri · beräknade värden",
"Zoom to Tiangong": "Zooma in på Tiangong",
"Tianhe arm (degrees)": "Tianhe-armen (grader)",
"Tianhe wings (degrees)": "Tianhes vingar (grader)",
"Lab wings (degrees)": "Laboratoriernas vingar (grader)",
"Port wing": "Babordsvinge",
"Starboard wing": "Styrbordsvinge",
"Wentian forward · alpha": "Wentian fram · alfa",
"Wentian forward · beta": "Wentian fram · beta",
"Wentian aft · alpha": "Wentian bak · alfa",
"Wentian aft · beta": "Wentian bak · beta",
"Mengtian forward · alpha": "Mengtian fram · alfa",
"Mengtian forward · beta": "Mengtian fram · beta",
"Mengtian aft · alpha": "Mengtian bak · alfa",
"Mengtian aft · beta": "Mengtian bak · beta",
"Wentian arm (degrees)": "Wentian-armen (grader)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Panelerna följer solen, antennen riktas mot relästationer i rymden och armarna svänger i illustrativt syfte. Beräknat: Kina publicerar ingen live-telemetri.",
"Telemetry reads while the model is on screen": "Telemetri läses medan modellen syns på skärmen",
"Connecting to telemetry…": "Ansluter till telemetri…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration."
}
+107 -1
View File
@@ -4531,5 +4531,111 @@
"Finding it…": "Пошук…",
"No reading at this time": "Немає даних на цей час",
"Last reading · {age}": "Останні дані · {age}",
"Find it": "Знайти"
"Find it": "Знайти",
"Underneath": "Знизу",
"Open on YouTube": "Відкрити на YouTube",
"Video plays from YouTube, which sees your IP address.": "Відео відтворюється з YouTube, який бачить вашу IP-адресу.",
"Automatic": "Автоматично",
"Manual": "Вручну",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Панелі й радіатори стежать за Сонцем, антени наводяться на супутники-ретранслятори, а маніпулятори рухаються для ілюстрації. Розрахунок, а не телеметрія в реальному часі.",
"Overhead": "Згори",
"Ahead": "Спереду",
"Behind": "Позаду",
"Port side": "Лівий борт",
"Starboard side": "Правий борт",
"Night (shadow)": "Ніч (тінь)",
"Sun position": "Положення Сонця",
"Follow the Sun": "Стежити за Сонцем",
"Fast orbit (40 s)": "Швидкий виток (40 с)",
"Solar arrays": "Сонячні батареї",
"Demonstration: the real arrays stay extended.": "Демонстрація: справжні батареї залишаються розкритими.",
"Retract": "Скласти",
"Extend": "Розкрити",
"Radiators": "Радіатори",
"Demonstration: the real radiators can fold but stay extended.": "Демонстрація: справжні радіатори складаються, але залишаються розкритими.",
"Dishes": "Антени",
"Relay satellites": "Супутники-ретранслятори",
"Up": "Вгору",
"Forward": "Вперед",
"Sideways": "Убік",
"Shoulder roll": "Плече: крен",
"Shoulder yaw": "Плече: рискання",
"Shoulder pitch": "Плече: тангаж",
"Elbow": "Лікоть",
"Wrist pitch": "Зап'ястя: тангаж",
"Wrist yaw": "Зап'ястя: рискання",
"Wrist roll": "Зап'ястя: крен",
"Canadarm2 (degrees)": "Canadarm2 (градуси)",
"Resume sway": "Відновити рух",
"Zoom to the ISS": "Наблизити до МКС",
"Now: in sunlight": "Зараз: на світлі",
"Now: in the Earth's shadow": "Зараз: у тіні Землі",
"STATION VIEW · {name}": "ВИГЛЯД ЗІ СТАНЦІЇ · {name}",
"Previous station view": "Попередній вигляд зі станції",
"Next station view": "Наступний вигляд зі станції",
"OBSERVATION MODULE · ISS": "МОДУЛЬ СПОСТЕРЕЖЕННЯ · МКС",
"European Space Agency (ESA)": "Європейське космічне агентство (ЄКА)",
"7 WINDOWS": "7 ІЛЮМІНАТОРІВ",
"LAUNCHED 8 FEB 2010 · STS-130": "ЗАПУЩЕНО 8 ЛЮТ 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · ПОРТ, ЗВЕРНЕНИЙ ДО ЗЕМЛІ",
"LABORATORY MODULE · ISS": "ЛАБОРАТОРНИЙ МОДУЛЬ · МКС",
"Japan Aerospace Exploration Agency (JAXA)": "Японське агентство аерокосмічних досліджень (JAXA)",
"2 WINDOWS": "2 ІЛЮМІНАТОРИ",
"LAUNCHED 31 MAY 2008 · STS-124": "ЗАПУЩЕНО 31 ТРАВ 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · ЛІВИЙ БОРТ",
"Return to the default view": "Повернути типовий вигляд",
"{label} · STATION VIEW": "{label} · ВИГЛЯД ЗІ СТАНЦІЇ",
"ON AIR": "В ЕФІРІ",
"Starting…": "Запуск…",
"Stream is offline": "Трансляція не ведеться",
"LIVE VIDEO": "ВІДЕО ОНЛАЙН",
"STREAM ATTACHED TO THE SUBJECT": "ТРАНСЛЯЦІЯ ВИБРАНОГО ОБ’ЄКТА",
"Live video": "Відео онлайн",
"Show Live Video": "Показати відео онлайн",
"This stream cannot play here": "Цю трансляцію не можна відтворити тут",
"Expand Live section": "Розгорнути розділ «Ефір»",
"Collapse Live section": "Згорнути розділ «Ефір»",
"Expand Live": "Розгорнути «Ефір»",
"Collapse Live": "Згорнути «Ефір»",
"Live streams for the selected object": "Прямі трансляції вибраного об’єкта",
"Stream": "Трансляція",
"Previous stream": "Попередня трансляція",
"Next stream": "Наступна трансляція",
"Try again": "Повторити",
"Exterior cameras": "Зовнішні камери",
"Live video and space-to-ground audio": "Пряме відео та переговори із Землею",
"NASA video, via YouTube": "Відео NASA, через YouTube",
"Controls for the selected space station": "Керування вибраною космічною станцією",
"Expand Station section": "Розгорнути розділ «Станція»",
"Collapse Station section": "Згорнути розділ «Станція»",
"Expand Station": "Розгорнути «Станцію»",
"Collapse Station": "Згорнути «Станцію»",
"Manual · telemetry paused": "Вручну · телеметрію призупинено",
"Telemetry · updated {ago} ago": "Телеметрія · оновлено {ago} тому",
"No signal since {time} · computed values": "Немає сигналу з {time} · розрахункові значення",
"No signal · computed values": "Немає сигналу · розрахункові значення",
"Telemetry unavailable · last update {ago} ago · computed values": "Телеметрія недоступна · останнє оновлення {ago} тому · розрахункові значення",
"Telemetry unavailable · computed values": "Телеметрія недоступна · розрахункові значення",
"Telemetry not enabled on this server · computed values": "Телеметрію не ввімкнено на цьому сервері · розрахункові значення",
"No public telemetry · computed values": "Відкритої телеметрії немає · розрахункові значення",
"Zoom to Tiangong": "Наблизити до «Тяньгун»",
"Tianhe arm (degrees)": "Маніпулятор «Тяньхе» (градуси)",
"Tianhe wings (degrees)": "Крила «Тяньхе» (градуси)",
"Lab wings (degrees)": "Крила лабораторій (градуси)",
"Port wing": "Ліве крило",
"Starboard wing": "Праве крило",
"Wentian forward · alpha": "«Веньтянь», передня · альфа",
"Wentian forward · beta": "«Веньтянь», передня · бета",
"Wentian aft · alpha": "«Веньтянь», задня · альфа",
"Wentian aft · beta": "«Веньтянь», задня · бета",
"Mengtian forward · alpha": "«Ментянь», передня · альфа",
"Mengtian forward · beta": "«Ментянь», передня · бета",
"Mengtian aft · alpha": "«Ментянь», задня · альфа",
"Mengtian aft · beta": "«Ментянь», задня · бета",
"Wentian arm (degrees)": "Маніпулятор «Веньтянь» (градуси)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Панелі стежать за Сонцем, антена наводиться на супутники-ретранслятори, а маніпулятори похитуються для наочності. Розрахунок: Китай не публікує телеметрію в реальному часі.",
"Telemetry reads while the model is on screen": "Телеметрія читається, поки модель на екрані",
"Connecting to telemetry…": "Підключення до телеметрії…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
}
+107 -1
View File
@@ -4213,5 +4213,111 @@
"Finding it…": "正在查找…",
"No reading at this time": "此时无数据",
"Last reading · {age}": "最后数据 · {age}",
"Find it": "查找"
"Find it": "查找",
"Underneath": "正下方",
"Open on YouTube": "在 YouTube 上打开",
"Video plays from YouTube, which sees your IP address.": "视频从 YouTube 播放,YouTube 会看到你的 IP 地址。",
"Automatic": "自动",
"Manual": "手动",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "太阳能板和散热器跟随太阳,天线指向中继卫星,机械臂仅作演示性摆动。均为计算结果,并非实时遥测。",
"Overhead": "正上方",
"Ahead": "前方",
"Behind": "后方",
"Port side": "左舷",
"Starboard side": "右舷",
"Night (shadow)": "夜间(阴影)",
"Sun position": "太阳位置",
"Follow the Sun": "跟随太阳",
"Fast orbit (40 s)": "快速绕行(40 秒)",
"Solar arrays": "太阳能板",
"Demonstration: the real arrays stay extended.": "演示:真实的太阳能板保持展开。",
"Retract": "收起",
"Extend": "展开",
"Radiators": "散热器",
"Demonstration: the real radiators can fold but stay extended.": "演示:真实的散热器可以折叠,但保持展开。",
"Dishes": "天线",
"Relay satellites": "中继卫星",
"Up": "向上",
"Forward": "向前",
"Sideways": "向侧面",
"Shoulder roll": "肩部滚转",
"Shoulder yaw": "肩部偏航",
"Shoulder pitch": "肩部俯仰",
"Elbow": "肘部",
"Wrist pitch": "腕部俯仰",
"Wrist yaw": "腕部偏航",
"Wrist roll": "腕部滚转",
"Canadarm2 (degrees)": "Canadarm2(度)",
"Resume sway": "恢复摆动",
"Zoom to the ISS": "拉近到国际空间站",
"Now: in sunlight": "当前:处于日照中",
"Now: in the Earth's shadow": "当前:处于地球阴影中",
"STATION VIEW · {name}": "空间站视图 · {name}",
"Previous station view": "上一个空间站视图",
"Next station view": "下一个空间站视图",
"OBSERVATION MODULE · ISS": "观测舱 · 国际空间站",
"European Space Agency (ESA)": "欧洲航天局(ESA)",
"7 WINDOWS": "7 扇舷窗",
"LAUNCHED 8 FEB 2010 · STS-130": "2010年2月8日发射 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "宁静号节点舱 · 对地端口",
"LABORATORY MODULE · ISS": "实验舱 · 国际空间站",
"Japan Aerospace Exploration Agency (JAXA)": "日本宇宙航空研究开发机构(JAXA)",
"2 WINDOWS": "2 扇舷窗",
"LAUNCHED 31 MAY 2008 · STS-124": "2008年5月31日发射 · STS-124",
"HARMONY · PORT SIDE": "和谐号节点舱 · 左舷",
"Return to the default view": "恢复默认视图",
"{label} · STATION VIEW": "{label} · 空间站视图",
"ON AIR": "直播中",
"Starting…": "正在启动…",
"Stream is offline": "直播已离线",
"LIVE VIDEO": "实时视频",
"STREAM ATTACHED TO THE SUBJECT": "与所选对象关联的直播",
"Live video": "实时视频",
"Show Live Video": "显示实时视频",
"This stream cannot play here": "此直播无法在此播放",
"Expand Live section": "展开直播区",
"Collapse Live section": "收起直播区",
"Expand Live": "展开直播",
"Collapse Live": "收起直播",
"Live streams for the selected object": "所选对象的直播",
"Stream": "直播",
"Previous stream": "上一个直播",
"Next stream": "下一个直播",
"Try again": "重试",
"Exterior cameras": "外部摄像头",
"Live video and space-to-ground audio": "实时视频与天地通话音频",
"NASA video, via YouTube": "NASA 视频,经由 YouTube",
"Controls for the selected space station": "所选空间站的控制",
"Expand Station section": "展开空间站区",
"Collapse Station section": "收起空间站区",
"Expand Station": "展开空间站",
"Collapse Station": "收起空间站",
"Manual · telemetry paused": "手动 · 遥测已暂停",
"Telemetry · updated {ago} ago": "遥测 · {ago}前更新",
"No signal since {time} · computed values": "自 {time} 起无信号 · 计算值",
"No signal · computed values": "无信号 · 计算值",
"Telemetry unavailable · last update {ago} ago · computed values": "遥测不可用 · 最后更新于{ago}前 · 计算值",
"Telemetry unavailable · computed values": "遥测不可用 · 计算值",
"Telemetry not enabled on this server · computed values": "此服务器未启用遥测 · 计算值",
"No public telemetry · computed values": "无公开遥测 · 计算值",
"Zoom to Tiangong": "拉近到天宫",
"Tianhe arm (degrees)": "天和机械臂(度)",
"Tianhe wings (degrees)": "天和翼板(度)",
"Lab wings (degrees)": "实验舱翼板(度)",
"Port wing": "左侧翼板",
"Starboard wing": "右侧翼板",
"Wentian forward · alpha": "问天前侧 · α",
"Wentian forward · beta": "问天前侧 · β",
"Wentian aft · alpha": "问天后侧 · α",
"Wentian aft · beta": "问天后侧 · β",
"Mengtian forward · alpha": "梦天前侧 · α",
"Mengtian forward · beta": "梦天前侧 · β",
"Mengtian aft · alpha": "梦天后侧 · α",
"Mengtian aft · beta": "梦天后侧 · β",
"Wentian arm (degrees)": "问天机械臂(度)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "太阳能板跟随太阳,天线指向中继卫星,机械臂仅作示意摆动。计算值:中国不公开实时遥测。",
"Telemetry reads while the model is on screen": "模型显示在屏幕上时读取遥测",
"Connecting to telemetry…": "正在连接遥测…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
}
+107 -1
View File
@@ -4213,5 +4213,111 @@
"Finding it…": "正在查找…",
"No reading at this time": "此時無數據",
"Last reading · {age}": "最後數據 · {age}",
"Find it": "查找"
"Find it": "查找",
"Underneath": "正下方",
"Open on YouTube": "在 YouTube 上打開",
"Video plays from YouTube, which sees your IP address.": "視頻從 YouTube 播放,YouTube 會看到你的 IP 地址。",
"Automatic": "自動",
"Manual": "手動",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "太陽能板和散熱器跟隨太陽,天線指向中繼衛星,機械臂僅作演示性擺動。均為計算結果,並非實時遙測。",
"Overhead": "正上方",
"Ahead": "前方",
"Behind": "後方",
"Port side": "左舷",
"Starboard side": "右舷",
"Night (shadow)": "夜間(陰影)",
"Sun position": "太陽位置",
"Follow the Sun": "跟隨太陽",
"Fast orbit (40 s)": "快速繞行(40 秒)",
"Solar arrays": "太陽能板",
"Demonstration: the real arrays stay extended.": "演示:真實的太陽能板保持展開。",
"Retract": "收起",
"Extend": "展開",
"Radiators": "散熱器",
"Demonstration: the real radiators can fold but stay extended.": "演示:真實的散熱器可以摺疊,但保持展開。",
"Dishes": "天線",
"Relay satellites": "中繼衛星",
"Up": "向上",
"Forward": "向前",
"Sideways": "向側面",
"Shoulder roll": "肩部滾轉",
"Shoulder yaw": "肩部偏航",
"Shoulder pitch": "肩部俯仰",
"Elbow": "肘部",
"Wrist pitch": "腕部俯仰",
"Wrist yaw": "腕部偏航",
"Wrist roll": "腕部滾轉",
"Canadarm2 (degrees)": "Canadarm2(度)",
"Resume sway": "恢復擺動",
"Zoom to the ISS": "拉近到國際空間站",
"Now: in sunlight": "當前:處於日照中",
"Now: in the Earth's shadow": "當前:處於地球陰影中",
"STATION VIEW · {name}": "空間站視圖 · {name}",
"Previous station view": "上一個空間站視圖",
"Next station view": "下一個空間站視圖",
"OBSERVATION MODULE · ISS": "觀測艙 · 國際空間站",
"European Space Agency (ESA)": "歐洲航天局(ESA)",
"7 WINDOWS": "7 扇舷窗",
"LAUNCHED 8 FEB 2010 · STS-130": "2010年2月8日發射 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "寧靜號節點艙 · 對地端口",
"LABORATORY MODULE · ISS": "實驗艙 · 國際空間站",
"Japan Aerospace Exploration Agency (JAXA)": "日本宇宙航空研究開發機構(JAXA)",
"2 WINDOWS": "2 扇舷窗",
"LAUNCHED 31 MAY 2008 · STS-124": "2008年5月31日發射 · STS-124",
"HARMONY · PORT SIDE": "和諧號節點艙 · 左舷",
"Return to the default view": "恢復默認視圖",
"{label} · STATION VIEW": "{label} · 空間站視圖",
"ON AIR": "直播中",
"Starting…": "正在啟動…",
"Stream is offline": "直播已離線",
"LIVE VIDEO": "實時視頻",
"STREAM ATTACHED TO THE SUBJECT": "與所選對象關聯的直播",
"Live video": "實時視頻",
"Show Live Video": "顯示實時視頻",
"This stream cannot play here": "此直播無法在此播放",
"Expand Live section": "展開直播區",
"Collapse Live section": "收起直播區",
"Expand Live": "展開直播",
"Collapse Live": "收起直播",
"Live streams for the selected object": "所選對象的直播",
"Stream": "直播",
"Previous stream": "上一個直播",
"Next stream": "下一個直播",
"Try again": "重試",
"Exterior cameras": "外部攝像頭",
"Live video and space-to-ground audio": "實時視頻與天地通話音頻",
"NASA video, via YouTube": "NASA 視頻,經由 YouTube",
"Controls for the selected space station": "所選空間站的控制",
"Expand Station section": "展開空間站區",
"Collapse Station section": "收起空間站區",
"Expand Station": "展開空間站",
"Collapse Station": "收起空間站",
"Manual · telemetry paused": "手動 · 遙測已暫停",
"Telemetry · updated {ago} ago": "遙測 · {ago}前更新",
"No signal since {time} · computed values": "自 {time} 起無信號 · 計算值",
"No signal · computed values": "無信號 · 計算值",
"Telemetry unavailable · last update {ago} ago · computed values": "遙測不可用 · 最後更新於{ago}前 · 計算值",
"Telemetry unavailable · computed values": "遙測不可用 · 計算值",
"Telemetry not enabled on this server · computed values": "此服務器未啟用遙測 · 計算值",
"No public telemetry · computed values": "無公開遙測 · 計算值",
"Zoom to Tiangong": "拉近到天宮",
"Tianhe arm (degrees)": "天和機械臂(度)",
"Tianhe wings (degrees)": "天和翼板(度)",
"Lab wings (degrees)": "實驗艙翼板(度)",
"Port wing": "左側翼板",
"Starboard wing": "右側翼板",
"Wentian forward · alpha": "問天前側 · α",
"Wentian forward · beta": "問天前側 · β",
"Wentian aft · alpha": "問天後側 · α",
"Wentian aft · beta": "問天後側 · β",
"Mengtian forward · alpha": "夢天前側 · α",
"Mengtian forward · beta": "夢天前側 · β",
"Mengtian aft · alpha": "夢天後側 · α",
"Mengtian aft · beta": "夢天後側 · β",
"Wentian arm (degrees)": "問天機械臂(度)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "太陽能板跟隨太陽,天線指向中繼衛星,機械臂僅作示意擺動。計算值:中國不公開實時遙測。",
"Telemetry reads while the model is on screen": "模型顯示在屏幕上時讀取遙測",
"Connecting to telemetry…": "正在連接遙測…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
}
+17 -6
View File
@@ -295,7 +295,11 @@
"{n} mm",
"Route",
"3D",
"KT"
"KT",
"ON AIR",
"Stream",
"{seconds} s",
"Mode"
],
"es": [
"1 min/s",
@@ -489,7 +493,9 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"Manual",
"{seconds} s"
],
"fr": [
"1 min/s",
@@ -746,7 +752,8 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"{seconds} s"
],
"it": [
"1 min/s",
@@ -979,7 +986,8 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"{seconds} s"
],
"ja": [
"1090 MHz",
@@ -1257,7 +1265,9 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"Manual",
"{seconds} s"
],
"ru": [
"1900–1945",
@@ -1494,7 +1504,8 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"{seconds} s"
],
"uk": [
"1900–1945",
+31
View File
@@ -139,3 +139,34 @@ test('same pixels at a new aspect redraw at the new fit', () => {
]);
assert.equal(runtime.canvasStamp, 2);
});
test('same pixels at a new resolution with the same fit skip the redraw', () => {
const { runtime, load } = stillHarness();
load(640, 480);
assert.deepEqual(load(1280, 960), []);
assert.equal(runtime.canvasStamp, 1);
assert.equal(runtime.drawnImageStamp, 2);
});
test('changed pixels redraw even when the fitted rectangle is unchanged', () => {
const { runtime, load } = stillHarness();
load(640, 480);
const changedPixels = new Uint8ClampedArray(
FRAME_SIGNATURE_W * FRAME_SIGNATURE_H * 4,
).fill(90);
runtime.signatureCtx.getImageData = () => ({ data: changedPixels });
const calls = load(640, 480);
assert.equal(calls[0][0], 'fillRect');
assert.deepEqual(calls[1], ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
test('a failed pixel signature redraws rather than assuming equal content', () => {
const { runtime, load } = stillHarness();
load(640, 480);
runtime.signatureCtx.getImageData = () => {
throw new Error('tainted canvas');
};
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
+2 -3
View File
@@ -81,9 +81,8 @@ export function createNavigation({
return false;
const nearest = nearestCameraIdToViewer();
if (!nearest || nearest === layerState._activeCameraId) return false;
parts.selection.setActiveCamera(nearest);
// setActiveCamera ends the opening pick; this is still that pick.
layerState._openingCameraProvisional = true;
// Still the opening pick: later settled moves may replace it.
parts.selection.setActiveCamera(nearest, { opening: true });
return true;
}
+74
View File
@@ -428,6 +428,80 @@ test('a pose with no perspective field of view is projected by the renderer', ()
}
});
test('focus release restores video hue and alpha after the style throttle', () => {
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } },
});
const { unbind } = bindFakeDraw(viewer, {
camera: camera.port,
query: { project: () => ({ x: 10, y: 20 }) },
});
let target = {};
const records = ['mp4', 'webm'].map((feedType) => ({
camera: { id: feedType, feedType },
position: { x: 6378137, y: 0, z: 0 },
}));
const state = {
_enabled: true,
_viewer: viewer,
_records: records,
_activeCameraId: null,
_activeFocusStyleCount: 0,
_lastFocusStyleAt: -Infinity,
};
const focus = {
focusNowMs: (nowMs) => nowMs,
getFocusTarget: () => target,
focusPassIsNeeded: (value, count) => !!value || count > 0,
advanceSpriteFocus: () => ({
factor: target ? FOCUS_FACTOR : 1,
active: !!target,
transitioning: false,
}),
focusAlphaNeedsWrite: (before, after) => before !== after,
};
const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedCamera: (camera) => isVideoFeedType(camera.feedType),
},
},
source: {},
});
try {
createCameraIcons(viewer);
for (const record of records) addCameraIcon(record);
const icons = state._icons;
refreshCctvFocusStyles(1000);
for (const record of records) {
assertKeepsColor(
icons,
record.camera.id,
LIVE_CAMERA_COLOR,
record.camera.id,
);
}
target = null;
refreshCctvFocusStyles(1050);
for (const record of records) {
assert.equal(icons.focus(record.camera.id), FOCUS_FACTOR, 'throttled');
}
refreshCctvFocusStyles(1100);
for (const record of records) {
assert.deepEqual(icons.item(record.camera.id).color, LIVE_CAMERA_COLOR);
assert.equal(icons.focus(record.camera.id), 1);
}
assert.equal(state._activeFocusStyleCount, 0);
} finally {
unbind();
}
});
test('hover picks the underlying camera only outside a painted count', () => {
const viewer = {};
const icon = { set: 'icons', id: 'camera' };
+8 -2
View File
@@ -108,10 +108,13 @@ export function createSelection({
* Sets the active camera by ID, initializes its projection runtime, refreshes
* its frame, and updates styles.
* @param {string} cameraId - ID of the camera to activate.
* @param {Object} [options]
* @param {boolean} [options.opening=false] - The opening camera following
* the view, not someone's pick: settled moves may still replace it.
* @returns {'activated'|'unchanged'|'not-found'} Discriminated activation result.
*/
function setActiveCamera(cameraId) {
function setActiveCamera(cameraId, { opening = false } = {}) {
if (!cameraId || !layerState._recordById.has(cameraId))
return CCTV_ACTIVATION_RESULT.NOT_FOUND;
const record = layerState._recordById.get(cameraId);
@@ -129,6 +132,9 @@ export function createSelection({
record,
)
) {
// Picking the camera a settled move re-opened is still a pick: later
// settled moves must leave it alone.
if (!opening) layerState._openingCameraProvisional = false;
// Browser-only feeds have a separate player; a reselect retries it
// without re-running activation or touching the projection geometry.
if (parts.model.isBrowserOverlayCamera(record.camera)) {
@@ -139,7 +145,7 @@ export function createSelection({
}
layerState._activeCameraId = cameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = false;
layerState._openingCameraProvisional = opening;
// A real activation creates projection work — wake the self-stopping loop.
parts.projection.startProjectionLoop();
if (previousActiveRecord && previousActiveRecord !== record) {
+13
View File
@@ -215,3 +215,16 @@ test('a count click is the card on top for every layer, unless the count yields'
picking.unregisterPickOwner('flights');
}
});
test('same-camera selection ends the opening pick without notifying snapshot feeds', () => {
const fixture = makeSelection('tripcheck-odot');
fixture.state._openingCameraProvisional = true;
assert.equal(
fixture.selection.setActiveCamera('same-camera'),
CCTV_ACTIVATION_RESULT.UNCHANGED,
);
assert.equal(fixture.state._openingCameraProvisional, false);
assert.equal(fixture.state._activeCameraReselection, 0);
assert.equal(fixture.notifications(), 0);
});
-2
View File
@@ -22,8 +22,6 @@ function frameUrlFor(camera, refreshMs = ACTIVE_FRAME_REFRESH_MS) {
const params = new URLSearchParams({
label: camera.name,
city: camera.city,
lat: camera.lat.toFixed(6),
lon: camera.lon.toFixed(6),
heading: String(Math.round(camera.headingDeg)),
fov: String(Math.round(camera.fovDeg)),
pitch: String(Math.round(camera.pitchDeg || -10)),
+2 -2
View File
@@ -82,8 +82,8 @@ test('frame and media URLs preserve registered camera identity and encoded metad
);
assert.equal(frame.searchParams.get('label'), camera.name);
assert.equal(frame.searchParams.get('city'), camera.city);
assert.equal(frame.searchParams.get('lat'), '30.267000');
assert.equal(frame.searchParams.get('lon'), '-97.744000');
assert.equal(frame.searchParams.has('lat'), false);
assert.equal(frame.searchParams.has('lon'), false);
assert.equal(frame.searchParams.get('heading'), '45');
assert.equal(frame.searchParams.get('pitch'), '-12');
assert.deepEqual([...media.searchParams.keys()], ['ts']);
+1
View File
@@ -108,6 +108,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
} = {}) {
layerState._viewer = viewer;
layerState._records = Array.isArray(records) ? records : [];
layerState._count = layerState._records.length;
layerState._recordById = new Map(
layerState._records
.filter((record) => record?.camera?.id)
+30 -1
View File
@@ -10,7 +10,13 @@ import { surfaceDistance } from '../../geo/geodesic.js';
import { toDegrees, toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createControls({ state: layerState, services, parts, source }) {
export function createControls({
state: layerState,
services,
parts,
source,
overlayHost,
}) {
const methods = {
id: LAYER_ID,
@@ -171,6 +177,29 @@ export function createControls({ state: layerState, services, parts, source }) {
return id ? methods.getById(id) : null;
},
/**
* The mapped installation whose label box the shared overlay paints at a
* canvas position: what a click lands on from far out, where the dot is
* 7 px. Another layer's card or label that takes clicks there wins, so
* this answers null. The dot, outline and fill themselves are query port
* hits, read with {@link findByPick}. Null for anything else.
* @param {{x: number, y: number}|null|undefined} position Canvas CSS px.
* @returns {object|null} As {@link getById}.
*/
findAt(position) {
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
return null;
let top = null;
try {
top = overlayHost?.hitTest?.(position.x, position.y) ?? null;
} catch {
top = null;
}
if (top) return null;
const id = parts.namedMarkers?.labelAt?.(position) ?? null;
return id ? methods.getById(id) : null;
},
/**
* Select and frame a mapped installation from another contextual UI.
* @param {string} id Source-backed installation id.
@@ -0,0 +1,83 @@
// src/layers/installations/labelBoxClick.test.mjs — a click on a mapped
// installation's label box finds the site, read from the box the overlay
// painted for it, unless another layer's card or label that takes clicks is
// painted there.
import assert from 'node:assert/strict';
import test from 'node:test';
import { createControls } from './controls.js';
const RECORD = Object.freeze({
id: 'base',
kind: 'installation',
name: 'Base',
class: 'base',
latitude: 10,
longitude: 20,
});
const inside = (box, { x, y }) =>
x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.h;
/**
* The installations controls over a fake overlay: `cards` are the hit rects
* of entries that take clicks (other layers'), `labels` the boxes painted
* for this layer's labels, which are not cards.
*/
function controlsWith({ cards = [], labels = {} }) {
const overlayHost = {
// As the world overlay does: the last painted card under the point wins.
hitTest(x, y) {
for (let i = cards.length - 1; i >= 0; i--)
if (inside(cards[i], { x, y }))
return { sourceId: cards[i].sourceId, entryId: cards[i].entryId };
return null;
},
};
const namedMarkers = {
labelAt: (position) =>
Object.keys(labels).find((id) => inside(labels[id], position)) ?? null,
};
const controls = createControls({
state: {
enabled: true,
records: [RECORD],
recordById: new Map([[RECORD.id, RECORD]]),
},
services: {},
parts: {
rendering: { installationSurfaceHeightM: () => 0 },
namedMarkers,
},
source: {},
overlayHost,
});
return controls.methods;
}
const BASE_LABEL = { x: 100, y: 100, w: 80, h: 20 };
test("a click on the site's own label box finds the site", () => {
const methods = controlsWith({ labels: { base: BASE_LABEL } });
assert.equal(methods.findAt({ x: 120, y: 110 })?.id, 'base');
assert.equal(methods.findAt({ x: 10, y: 10 }), null, 'outside every box');
assert.equal(methods.findAt(null), null);
});
test("another layer's card painted over the site's label keeps the click", () => {
const methods = controlsWith({
labels: { base: BASE_LABEL },
cards: [
{ sourceId: 'flights', entryId: 'abc123', x: 110, y: 105, w: 40, h: 12 },
],
});
assert.equal(
methods.findAt({ x: 120, y: 110 }),
null,
'the flight card is on top',
);
assert.equal(
methods.findAt({ x: 170, y: 110 })?.id,
'base',
'past the card, the site is found',
);
});
+31
View File
@@ -221,6 +221,11 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
// What `visit` hands out: the marker's id, position and whether
// it is on this side of the horizon.
point: { id: { installationId: record.id }, position, show: false },
// Not an interactive overlay entry: those are cards that take every
// click from what is drawn under them, and an aircraft or vessel
// under a base's label must stay selectable. The label box still
// finds the site through its painted box (labelAt), which the
// layer's click claim reads where nothing else is drawn.
entry: createInfrastructureOverlayEntry({
id: record.id,
source: LAYER_ID,
@@ -274,6 +279,32 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
visitor(marker.recordId, marker.point);
}
},
/**
* The site whose label box the shared overlay painted at a canvas
* position in its last frame, or null: what a click lands on from far
* out, where the dot is 7 px.
* @param {{x: number, y: number}|null|undefined} position Canvas CSS px.
* @returns {string|null} The installation id.
*/
labelAt(position) {
if (!state.enabled) return null;
const x = position?.x;
const y = position?.y;
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
for (let i = ordered.length - 1; i >= 0; i--) {
const { recordId } = ordered[i];
const box = overlayHost.paintRect?.(LAYER_ID, recordId);
if (
box &&
x >= box.x &&
x <= box.x + box.w &&
y >= box.y &&
y <= box.y + box.h
)
return recordId;
}
return null;
},
refresh,
enable,
hide,
+111 -23
View File
@@ -9,15 +9,30 @@ import { fakeSceneFrame, fakeSceneQuery } from '../../testSupport/fakeCesiumScen
import { createLocalInfrastructureOverlayEntry } from '../../data/localGeojsonCore.js';
function setup(t) {
let labels = [], options, publications = 0, visible = false;
let labels = [],
options,
publications = 0,
visible = false;
const overlayHost = {
setEntries(id, entries, policy) {
assert.equal(id, 'military-installations');
labels = entries; options = policy; publications++;
labels = entries;
options = policy;
publications++;
},
clearSource() {
labels = [];
},
setVisible(_id, value) {
visible = value;
},
// The boxes the overlay painted last frame, by entry id.
paintRect(id, entryId) {
assert.equal(id, 'military-installations');
return boxes.get(entryId) ?? null;
},
clearSource() { labels = []; },
setVisible(_id, value) { visible = value; },
};
const boxes = new Map();
let x = -100;
t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', () => new C.Cartesian2(x, 300));
const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), directionWC: new C.Cartesian3(0, 0, -1) };
@@ -33,14 +48,16 @@ function setup(t) {
lifecycle.init(state.viewer); lifecycle.enable();
const records = [1, 2].map((n) => ({ id: `osm:military:w${n}`, name: `Site ${n}`, namedArea: true, areaM2: 100 / n, latitude: 0, longitude: 0, pointOnly: true }));
const points = () => [...draw.sets.values()].find((set) => set.kind === 'points' && !set.disposed);
return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads };
return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, boxes, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads };
}
test('Contacts camera motion reprojects and declutters existing labels without source loads or primitive replacement', (t) => {
const h = setup(t);
h.markers.sync(h.records);
assert.equal(h.markers.stats().pointsOnScreen, 0);
h.setX(600); h.camera.changed.raiseEvent(); h.camera.moveEnd.raiseEvent();
h.setX(600);
h.camera.changed.raiseEvent();
h.camera.moveEnd.raiseEvent();
assert.equal(h.markers.stats().pointsOnScreen, 2);
assert.equal(h.labels.length, 2);
assert.equal(h.options.collisionCapacity, 24);
@@ -61,7 +78,8 @@ test('Contacts camera motion reprojects and declutters existing labels without s
assert.equal(h.labels.length, 0);
assert.equal(h.visible, false);
h.state.records = h.records;
h.setX(600); h.lifecycle.enable();
h.setX(600);
h.lifecycle.enable();
assert.equal(h.labels.length, 2);
assert.equal(h.publications(), 5);
h.lifecycle.destroy(h.state.viewer);
@@ -73,13 +91,25 @@ test('Contacts camera motion reprojects and declutters existing labels without s
test('wide named markers retain primitives until close polygons publish with the same identity', async (t) => {
const { retainNamedHandoff } = await import('./ingestion.js');
const h = setup(t);
h.setX(600); h.markers.sync(h.records);
h.setX(600);
h.markers.sync(h.records);
const first = h.labels[0];
const box = { west: -1, east: 1, south: -1, north: 1 };
h.markers.sync(retainNamedHandoff(h.records, [], box));
assert.equal(h.labels[0], first);
assert.equal(first.title, 'Site 1');
const polygon = { ...h.records[0], namedArea: false, name: 'Military area', pointOnly: false, footprint: [[0, 0], [0.1, 0], [0, 0.1], [0, 0]] };
const polygon = {
...h.records[0],
namedArea: false,
name: 'Military area',
pointOnly: false,
footprint: [
[0, 0],
[0.1, 0],
[0, 0.1],
[0, 0],
],
};
const handed = retainNamedHandoff(h.records, [polygon], box);
assert.equal(handed.length, 2);
assert.equal(handed[0].name, 'Site 1');
@@ -88,7 +118,11 @@ test('wide named markers retain primitives until close polygons publish with the
assert.equal(h.labels[0], first);
assert.equal(first.title, 'Site 1');
assert.equal(h.labels.length, 2, 'no duplicate title at handoff');
assert.equal(retainNamedHandoff(h.records, [], { west: 1, east: 2, south: 1, north: 2 }).length, 0);
assert.equal(
retainNamedHandoff(h.records, [], { west: 1, east: 2, south: 1, north: 2 })
.length,
0,
);
h.lifecycle.destroy(h.state.viewer);
});
@@ -98,7 +132,9 @@ test('canonical aliases transfer named marker ownership without replacing marker
const parent = h.records[1];
h.markers.sync([parent]);
let originalPoint;
h.markers.visit((_id, point) => { originalPoint = point; });
h.markers.visit((_id, point) => {
originalPoint = point;
});
const label = h.labels[0];
for (const record of [
{ ...parent, id: h.records[0].id, aliasIds: [parent.id], pointOnly: false },
@@ -120,17 +156,29 @@ test('canonical aliases transfer named marker ownership without replacing marker
h.lifecycle.destroy(h.state.viewer);
});
test('the bounded host cohort ranks wide points and polygon titles by area', (t) => {
const h = setup(t);
h.markers.sync(Array.from({ length: 600 }, (_, n) => ({
...h.records[0], id: `site:${n}`, name: `Site ${n}`, areaM2: n,
pointOnly: n % 2 === 0,
})));
h.markers.sync(
Array.from({ length: 600 }, (_, n) => ({
...h.records[0],
id: `site:${n}`,
name: `Site ${n}`,
areaM2: n,
pointOnly: n % 2 === 0,
})),
);
assert.equal(h.labels.length, 512);
assert.equal(h.labels[0].id, 'site:599');
assert.equal(h.labels.at(-1).id, 'site:88');
assert.ok(h.labels.every((entry) => !entry.stateless && entry.horizonCull && entry.collisionGroup === 'ambient-card'));
assert.ok(
h.labels.every(
(entry) =>
!entry.stateless &&
entry.horizonCull &&
entry.collisionGroup === 'ambient-card' &&
entry.interactive === false,
),
);
const first = h.labels[0];
const publications = h.publications();
for (let i = 0; i < 100; i++) {
@@ -143,7 +191,6 @@ test('the bounded host cohort ranks wide points and polygon titles by area', (t)
assert.equal(h.labels.length, 0);
});
test('wide and polygon titles use the Data Centers entry contract and persistent shared domain', (t) => {
const h = setup(t);
h.markers.sync([h.records[0], { ...h.records[1], pointOnly: false }]);
@@ -151,12 +198,43 @@ test('wide and polygon titles use the Data Centers entry contract and persistent
assert.equal(h.options.solveIntervalMs, undefined);
assert.equal(h.options.maxVisible, 24);
for (const entry of h.labels) {
const reference = createLocalInfrastructureOverlayEntry({ id: entry.id, layerId: 'military-installations', position: entry.position, properties: { name: entry.title }, priority: entry.priority, accent: entry.accent });
const reference = createLocalInfrastructureOverlayEntry({
id: entry.id,
layerId: 'military-installations',
position: entry.position,
properties: { name: entry.title },
priority: entry.priority,
accent: entry.accent,
});
// Not interactive: an interactive entry is a card that takes the click
// from an aircraft or vessel drawn under it. A click on the label box
// finds the site through its painted box (labelAt).
assert.deepEqual(entry, { ...reference, selected: false });
}
h.lifecycle.destroy(h.state.viewer);
});
test("labelAt finds the site whose label box was painted at a point, in CSS px", (t) => {
const h = setup(t);
h.markers.sync(h.records);
const [first, second] = h.records.map((record) => record.id);
h.boxes.set(first, { x: 100, y: 100, w: 80, h: 20 });
h.boxes.set(second, { x: 300, y: 100, w: 60, h: 20 });
assert.equal(h.markers.labelAt({ x: 120, y: 110 }), first);
assert.equal(h.markers.labelAt({ x: 360, y: 120 }), second, 'edges count');
assert.equal(h.markers.labelAt({ x: 250, y: 110 }), null, 'between boxes');
assert.equal(h.markers.labelAt(null), null);
assert.equal(h.markers.labelAt({ x: Number.NaN, y: 110 }), null);
// A site no longer marked has no label to find, even with a stale box.
h.markers.sync([h.records[1]]);
assert.equal(h.markers.labelAt({ x: 120, y: 110 }), null);
assert.equal(h.markers.labelAt({ x: 320, y: 110 }), second);
// Nor does a layer that is off.
h.state.enabled = false;
assert.equal(h.markers.labelAt({ x: 320, y: 110 }), null);
h.state.enabled = true;
h.lifecycle.destroy(h.state.viewer);
});
test('selection promotes exactly one entry and deselection restores that same label', (t) => {
const h = setup(t);
@@ -167,7 +245,7 @@ test('selection promotes exactly one entry and deselection restores that same la
assert.equal(h.labels.length, 2);
assert.equal(h.labels[0], original);
assert.equal(original.variant, 'selected');
assert.equal(h.labels.filter(e => e.selected).length, 1);
assert.equal(h.labels.filter((e) => e.selected).length, 1);
assert.equal(h.options.maxVisible, 23);
h.state.selectedId = null;
h.markers.sync(h.records);
@@ -180,14 +258,24 @@ test('selection promotes exactly one entry and deselection restores that same la
test('Contacts can select a point outside the normal title cap or an unnamed polygon', (t) => {
const h = setup(t);
const records = Array.from({ length: 520 }, (_, i) => ({ ...h.records[0], id: `site:${i}`, areaM2: 1000 - i }));
records.push({ ...h.records[0], id: 'unnamed', name: 'Military area', namedArea: false, pointOnly: false });
const records = Array.from({ length: 520 }, (_, i) => ({
...h.records[0],
id: `site:${i}`,
areaM2: 1000 - i,
}));
records.push({
...h.records[0],
id: 'unnamed',
name: 'Military area',
namedArea: false,
pointOnly: false,
});
for (const id of ['site:519', 'unnamed']) {
h.state.selectedId = id;
h.markers.sync(records);
assert.equal(h.labels[0].id, id);
assert.equal(h.labels[0].variant, 'selected');
assert.equal(h.labels.filter(e => e.selected).length, 1);
assert.equal(h.labels.filter((e) => e.selected).length, 1);
assert.equal(h.labels.length, 512);
}
h.lifecycle.destroy(h.state.viewer);
+50 -9
View File
@@ -1,5 +1,10 @@
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import {
clickCard,
isUnderOtherCard,
registerClickClaim,
unregisterClickClaim,
} from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
export function createSelection({
@@ -37,8 +42,39 @@ export function createSelection({
return layerState.selectedId === id;
}
/** Whether a draw hit is one of this layer's: a dot, outline, fill or named marker. */
function ownsHit(hit) {
return Boolean(
hit &&
(hit.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit.set)),
);
}
/**
* A site's label box as the card on top of a click, for every layer's
* clickCard (the pick registry's click claim). Only where nothing another
* layer draws is under the click: an aircraft or vessel drawn under a
* base's label keeps its own click, while a label over the map, or over
* this layer's own dots and fills, takes it. Runs only where no card or
* label that takes clicks is painted on top.
* @param {object} event The shared dispatcher click.
* @returns {{sourceId: string, entryId: string}|null}
*/
function labelClickCard(event) {
if (!layerState.enabled || !event) return null;
if (event.topHit && !ownsHit(event.drawHit)) return null;
const id =
parts.namedMarkers?.labelAt?.(event.screenPosition ?? event.position) ??
null;
return id && layerState.recordById.has(id)
? { sourceId: LAYER_ID, entryId: id }
: null;
}
function installInteraction(viewer) {
if (layerState.clickSubscription) return;
registerClickClaim(LAYER_ID, labelClickCard);
const events = [
'gev:entity-selected',
'gev:entity-selection-cleared',
@@ -54,16 +90,20 @@ export function createSelection({
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
// under it does not act, and the click is not empty space either. A
// site's own label box is this layer's.
if (isUnderOtherCard(event, [LAYER_ID])) return;
// The site whose label box is at the click takes it where nothing
// another layer draws is under it (labelClickCard): from far out the
// click lands on the label, not the 7 px dot. Else a site's dot,
// outline or fill, or a named marker: each draw item names its
// installation in its `meta`.
const card = clickCard(event);
const hit = event.drawHit;
const id =
hit?.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit?.set)
? hit.meta?.installationId
: null;
(card?.sourceId === LAYER_ID ? card.entryId : null) ??
(ownsHit(hit) ? hit.meta?.installationId : null) ??
null;
if (id && layerState.recordById.has(id) && id !== layerState.selectedId) {
selectRecord(id);
} else if (layerState.selectedId) {
@@ -82,6 +122,7 @@ export function createSelection({
destroy() {
removeContextListeners?.();
removeContextListeners = null;
unregisterClickClaim(LAYER_ID);
},
};
}
+69 -1
View File
@@ -7,7 +7,8 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { clickCard, setClickCardHitTest } from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -60,6 +61,8 @@ function harness(t) {
() => new Cesium.Cartesian2(640, 400),
);
let labels = [];
// The boxes the overlay painted last frame for this layer's labels.
const boxes = new Map();
const services = {
context,
anchors: {},
@@ -82,6 +85,9 @@ function harness(t) {
},
clearSource() {},
setVisible() {},
paintRect(_id, entryId) {
return boxes.get(entryId) ?? null;
},
},
};
parts.rendering = createRendering(ctx);
@@ -116,6 +122,7 @@ function harness(t) {
draw,
input,
parts,
boxes,
/** Click on what `pick` names, as the scene would pick it. */
click(value) {
picked = value;
@@ -258,3 +265,64 @@ test('a click on a site dot or its outline selects the site; another set does no
h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), false);
});
test("a click on a site's label box selects it where nothing else is drawn under it", (t) => {
const h = harness(t);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.parts.rendering.renderRecords();
// The card every layer reads for each click, as Context's bridge reads it.
const cards = [];
const offCards = h.input.input.onClick((event) =>
cards.push(clickCard(event)),
);
t.after(offCards);
// No label at the click and nothing picked: nothing is selected.
h.click(undefined);
h.assertSelected(false);
assert.equal(cards.at(-1), null);
// The site's label box at the click (CSS px) selects it; again releases it.
h.boxes.set('base', { x: 600, y: 390, w: 80, h: 20 });
h.click(undefined);
h.assertSelected(true);
assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' });
h.click(undefined);
h.assertSelected(false);
// Over the site's own named marker, the label still takes the click.
const setId = h.parts.namedMarkers.setId;
const item = h.draw.set(setId).items.get(namedPointId('base'));
h.click({ id: { set: setId, id: item.id, meta: item.meta } });
h.assertSelected(true);
assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' });
// An aircraft drawn under the label keeps its click: the label is no card
// there, so its own layer and Context can select it, and the site lets go.
h.click({ id: 'flight:abc123' });
h.assertSelected(false);
assert.equal(cards.at(-1), null);
// Another layer's card painted over the label takes the click.
setClickCardHitTest(() => ({ sourceId: 'earthquake-card', entryId: 'ak1' }));
t.after(() => setClickCardHitTest(null));
h.click(undefined);
h.assertSelected(false);
setClickCardHitTest(null);
// A layer that is off claims nothing.
h.state.enabled = false;
h.click(undefined);
assert.equal(cards.at(-1), null);
h.state.enabled = true;
});
test('destroy withdraws the label claim', (t) => {
const h = harness(t);
h.boxes.set('base', { x: 600, y: 390, w: 80, h: 20 });
const cards = [];
const offCards = h.input.input.onClick((event) =>
cards.push(clickCard(event)),
);
t.after(offCards);
h.click(undefined);
assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' });
h.selection.destroy();
h.click(undefined);
assert.equal(cards.at(-1), null);
});
+24
View File
@@ -9,6 +9,7 @@ import {
tleEpochMs,
} from './classes.js';
import { ISS_NORAD } from './policy.js';
import { trackedStation } from './stationModels.js';
/** The layer id a satellite subject carries through Cockpit events and state. */
export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
@@ -261,6 +262,29 @@ export function createCockpitSubject({ state: layerState, parts }) {
return out;
},
/**
* Where the Cockpit camera sits and looks when the subject is the
* station: a view from a point on the ISS model (issMounts.js) in place
* of the straight-down picture. The station offers several (from Nauka,
* from Zarya, from a docked vehicle), whichever of its entries is ridden.
* @param {string|null} [key] The view asked for; the first on offer when
* it is not given or not on offer.
* @returns {{position: object, direction: object, up: object,
* right: object, key: string, label: string,
* views: Array<{key: string, label: string}>}|null} Earth-fixed
* `{x, y, z}` vectors, the view shown and the views on offer; null for
* any other satellite, outside the Cockpit, or until the model has
* loaded.
*/
getCockpitMount(key = null) {
if (!_cockpitHeld()) return null;
// The station the subject belongs to; a station without views on its
// model (Tiangong) answers null, and the Cockpit keeps the nadir picture.
return (
trackedStation(layerState, parts)?.model?._cockpitMount?.(key) ?? null
);
},
/**
* Mark the satellite whose position the Cockpit camera occupies, or
* release it. The hold applies while that satellite is tracked.
@@ -631,3 +631,70 @@ test('the subject says whether its class may be ridden', () => {
])
assert.equal(subject(satelliteClass).enterable, true, satelliteClass);
});
test('the station offers its mount only while the Cockpit rides it', async (t) => {
const f = await fixture(t);
const mount = { label: 'ZARYA' };
// The ISS model part works the mount out (issModel.js, stationModel.js);
// this layer only decides when the Cockpit may have it, asking the part
// whose station the subject is (stationModels.js).
const modelPart = (offered) => ({
key: 'iss',
norad: ISS_NORAD,
_updateStationModel() {},
_destroyStationModel() {},
_standsInFor: () => false,
_cockpitMount: () => offered,
});
f.parts.stationModels = [modelPart(mount)];
assert.equal(f.methods.getCockpitMount(), null, 'nothing tracked');
f.track(ISS_NORAD);
f.nextFrame();
assert.equal(f.methods.getCockpitMount(), null, 'tracked, not ridden');
f.methods.setCockpitSubject(String(ISS_NORAD));
assert.equal(f.methods.getCockpitMount(), mount);
// The view asked for is passed on; none asks for the first on offer.
const asked = [];
f.parts.stationModels = [
{
...modelPart(mount),
_cockpitMount(key) {
asked.push(key);
return mount;
},
},
];
f.methods.getCockpitMount('zarya');
f.methods.getCockpitMount();
assert.deepEqual(asked, ['zarya', null]);
// The model has nothing to offer: not loaded, or not the station.
f.parts.stationModels = [modelPart(null)];
assert.equal(f.methods.getCockpitMount(), null);
delete f.parts.stationModels;
assert.equal(f.methods.getCockpitMount(), null);
// Another station's part is not asked for the ISS.
f.parts.stationModels = [{ ...modelPart(mount), norad: 48274 }];
assert.equal(f.methods.getCockpitMount(), null);
f.parts.stationModels = [modelPart(mount)];
f.methods.setCockpitSubject(null);
assert.equal(f.methods.getCockpitMount(), null, 'released');
});
test('a satellite docked to the ISS draws no ring of its own: the ISS’s shows', async (t) => {
const f = await fixture(t);
f.track(COMPANION);
f.nextFrame();
assert.equal(f.state._trackedDockedToIss, true);
assert.equal(f.ring(COMPANION), undefined, 'no second ring');
assert.equal(f.ring(ISS_NORAD).show, true);
// The ISS's ring stands for it even with the stations class hidden.
f.methods.setParams({ classes: { stations: false } });
assert.equal(f.ring(ISS_NORAD).show, true);
// Another satellite keeps its own ring; the ISS's goes with its class.
f.track(GPS);
f.nextFrame();
assert.equal(f.state._trackedDockedToIss, false);
assert.ok(f.ring(GPS));
assert.equal(f.ring(GPS).show, true);
assert.equal(f.ring(ISS_NORAD).show, false);
});
+21 -2
View File
@@ -9,6 +9,7 @@ import {
mergeClassVisibility,
} from './classes.js';
import { ISS_NORAD, POINT_STYLES, classPointStyle } from './policy.js';
import { modelFor, trackedStation } from './stationModels.js';
export function createControls({ state: layerState, services, parts, source }) {
const { isExplicitLayerStateOrigin } = services.layerState;
@@ -64,7 +65,8 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Whether the ISS's ring shows: orbits on, the layer drawing, and its
* class on or the ISS tracked (a tracked satellite keeps its ring).
* class on or the ISS tracked (a tracked satellite keeps its ring), also
* as an object docked to it, which draws no ring of its own.
*/
function _issOrbitVisible() {
return (
@@ -72,7 +74,9 @@ export function createControls({ state: layerState, services, parts, source }) {
layerState._enabled,
layerState._params.showOrbits,
) &&
(_classVisible(ISS_NORAD) || layerState._trackedNorad === ISS_NORAD)
(_classVisible(ISS_NORAD) ||
layerState._trackedNorad === ISS_NORAD ||
Boolean(layerState._trackedDockedToIss))
);
}
@@ -253,6 +257,9 @@ export function createControls({ state: layerState, services, parts, source }) {
// that card instead. Only members of the tracked cluster are affected —
// unrelated nearby satellites are never suppressed.
if (!isTracked && layerState._dockedCompanions.has(noradId)) continue;
// Up close a station is its 3D model: no mark on it, nor on what is
// docked to it.
if (modelFor(parts, noradId)?._visualPosition?.()) continue;
// The Cockpit camera rides a held subject; a bracket on it would sit
// on the lens.
if (isTracked && parts.cockpit?._cockpitHeld()) continue;
@@ -433,6 +440,18 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* The keys the LIVE section matches streams by for the tracked
* satellite: a station is `station:<key>` (`station:iss`,
* `station:tiangong`) whichever of its entries is tracked (the station,
* a module, a docked vehicle).
* @returns {string[]}
*/
getLiveSubjectKeys() {
const station = trackedStation(layerState, parts);
return station ? [`station:${station.key}`] : [];
},
/**
* Track a satellite by NORAD id (camera follow + orbit path + highlight),
* same path as clicking its point.
+23 -1
View File
@@ -7,13 +7,22 @@ import { createRendering } from './rendering.js';
import { createTracking } from './tracking.js';
import { createTesting } from './testing.js';
import { createInteraction } from './interaction.js';
import { issStationDescription } from './issStation.js';
import { createStationPanel } from './stationPanel.js';
import { createIssModel } from './issModel.js';
import { createTiangongModel } from './tiangongModel.js';
import { tiangongStationDescription } from './tiangongStation.js';
import { createLifecycle } from './lifecycle.js';
import { createIngestion } from './ingestion.js';
import { createRecords } from './records.js';
import { createState } from './state.js';
/** Construct one layer with its own scene state and supplied application services. */
export function createSatellitesLayer({ services, source }) {
export function createSatellitesLayer({
services,
source,
resolveAsset = (url) => url,
}) {
if (typeof source?.readGroup !== 'function')
throw new TypeError('A satellites source is required');
const state = createState({ services });
@@ -25,6 +34,18 @@ export function createSatellitesLayer({ services, source }) {
parts.orbits = createOrbits(context);
parts.records = createRecords(context);
parts.rendering = createRendering(context);
// The stations drawn as models up close; the other parts ask
// stationModels.js which station an entry belongs to.
parts.issModel = createIssModel({ ...context, resolveAsset });
parts.tiangongModel = createTiangongModel({ ...context, resolveAsset });
parts.stationModels = [parts.issModel, parts.tiangongModel];
parts.stationPanel = createStationPanel({
...context,
stations: [
issStationDescription(context),
tiangongStationDescription(context),
],
});
parts.tracking = createTracking(context);
parts.testing = createTesting(context);
parts.interaction = createInteraction(context);
@@ -35,6 +56,7 @@ export function createSatellitesLayer({ services, source }) {
{},
parts.controls.methods,
parts.cockpit.methods,
parts.stationPanel.methods,
parts.lifecycle.methods,
parts.ingestion.methods,
{
+13
View File
@@ -1,4 +1,5 @@
import { inputFor } from '../../input/dispatcher.js';
import { modelHitNorad } from './stationModels.js';
import { onFollowChanged } from '../../data/followed.js';
export function createInteraction({
@@ -67,6 +68,18 @@ export function createInteraction({
parts.tracking._trackSatellite(noradId, { origin: 'user' });
return;
}
// A station's 3D model (stationModel.js) names its station. A click
// on the tracked station's own model is already tracked; on another
// station's model it tracks that one.
const modelNorad = modelHitNorad(parts, hit);
if (modelNorad !== null) {
if (modelNorad === layerState._trackedNorad) return;
if (layerState._catalog.has(modelNorad)) {
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._trackSatellite(modelNorad, { origin: 'user' });
return;
}
}
// A pick that belongs to a sibling layer (plane, vessel, station, CCTV
// camera…) is not "empty space" — leave OUR tracking (and crucially
+834
View File
@@ -0,0 +1,834 @@
import { sunPositionFixed } from '../../geo/celestial.js';
/**
* The ISS model's moving parts. NASA's file names its joints; the build keeps
* each one as a node of its own, with the parts it carries beneath it, all in
* the model's rest frame (glTF axes, meters: X port, Y zenith, Z forward), so
* a joint turns by rotating its node about `pivot`.
*
* By default the angles are computed from where the Sun is: the two alpha
* joints turn the outboard truss about the truss axis, each array's beta
* joint turns it about its mast, and the two radiator joints keep the
* radiators edge-on to the Sun. In the Earth's shadow the arrays feather:
* masts along the flight direction, edge into it.
*
* Where the server relays NASA's public telemetry (issTelemetry.js), the
* arrays, the radiators and one dish take their real angles from it instead,
* and fall back to the computed ones whenever it has nothing to say.
*/
/** Alpha joints (SARJ): rotate about the truss, glTF X. */
export const ISS_ALPHA_JOINTS = Object.freeze([
Object.freeze({ node: 'PORT_ALPHA_ROT', pivot: [19.533, 0, 0] }),
Object.freeze({ node: 'STBD_ALPHA_ROT', pivot: [-19.533, 0, 0] }),
]);
/**
* Beta joints (BGA): rotate about the mast, glTF Z at rest. `face` is the
* sign of the cell side's normal along X at rest (the roll-out arrays sit on
* that side).
*/
export const ISS_BETA_JOINTS = Object.freeze([
Object.freeze({
node: 'PORT_BETA_ROT_2A',
pivot: [36.7319, 0.7256, -3.0077],
face: -1,
}),
Object.freeze({
node: 'PORT_BETA_ROT_4A',
pivot: [36.7319, -0.7258, 2.2332],
face: -1,
}),
Object.freeze({
node: 'PORT_BETA_ROT_2B',
pivot: [53.223, -0.7196, 2.2335],
face: -1,
}),
Object.freeze({
node: 'PORT_BETA_ROT_4B',
pivot: [53.2219, 0.7294, -3.0076],
face: -1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_1A',
pivot: [-36.6608, 0.7257, 3.0224],
face: 1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_3A',
pivot: [-36.6608, -0.7257, -2.2408],
face: 1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_1B',
pivot: [-53.2219, -0.7294, -2.2408],
face: 1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_3B',
pivot: [-53.2232, 0.722, 3.0223],
face: 1,
}),
]);
/** Radiator joints (TRRJ): rotate about glTF Z; the panels face Y at rest. */
export const ISS_RADIATOR_JOINTS = Object.freeze([
Object.freeze({ node: 'PORT_TRRJ_GAMMA_ROT', pivot: [16.1287, 0, -7.4432] }),
Object.freeze({ node: 'STBD_TRRJ_GAMMA_ROT', pivot: [-16.1287, 0, -7.4432] }),
]);
/** How fast a joint may turn on screen, radians per second of wall time. */
export const ISS_JOINT_RATE = (12 * Math.PI) / 180;
/** Below this the Sun is too close to a joint's axis to steer by it. */
const MIN_STEER = 0.05;
const EARTH_RADIUS_M = 6_371_000;
/** The signed difference b - a, wrapped to (-π, π]. */
function wrap(delta) {
let d = delta % (2 * Math.PI);
if (d > Math.PI) d -= 2 * Math.PI;
if (d <= -Math.PI) d += 2 * Math.PI;
return d;
}
/** Of `angle` and `angle + π`, the one nearer to `previous`. */
function nearestHalfTurn(angle, previous) {
const flipped = angle + Math.PI;
return Math.abs(wrap(angle - previous)) <= Math.abs(wrap(flipped - previous))
? angle
: flipped;
}
/**
* Whether a point is in the Earth's shadow, taken as a cylinder.
* @param {number[]} positionEcef Meters.
* @param {number[]} sunEcef Unit vector toward the Sun.
* @returns {boolean}
*/
export function issInShadow(positionEcef, sunEcef) {
const along =
positionEcef[0] * sunEcef[0] +
positionEcef[1] * sunEcef[1] +
positionEcef[2] * sunEcef[2];
if (along >= 0) return false;
const off = Math.hypot(
positionEcef[0] - along * sunEcef[0],
positionEcef[1] - along * sunEcef[1],
positionEcef[2] - along * sunEcef[2],
);
return off < EARTH_RADIUS_M;
}
/**
* The Sun's direction on the model's glTF axes, from the flight axes the
* model is oriented by (x along-track, y orbit normal, z zenith).
* @param {number[]} sunEcef Unit vector toward the Sun, Earth-fixed.
* @param {{x:number[], y:number[], z:number[]}} axes
* @returns {number[]} [port, zenith, forward].
*/
export function issSunInModelFrame(sunEcef, axes) {
const dot = (a) => a[0] * sunEcef[0] + a[1] * sunEcef[1] + a[2] * sunEcef[2];
return [dot(axes.y), dot(axes.z), dot(axes.x)];
}
/**
* The joint angles that point the arrays at the Sun.
* @param {number[]} sun Unit vector toward the Sun on the model's glTF axes.
* @param {boolean} sunlit False in the Earth's shadow: the arrays feather.
* @param {{alpha:number, gamma:number}} [previous] The last targets, so a
* joint with two equivalent answers keeps the nearer one.
* @returns {{alpha:number, beta:number[], gamma:number}} Radians: `alpha`
* about +X for both alpha joints, `beta` about +Z per ISS_BETA_JOINTS entry,
* `gamma` about +Z for both radiator joints.
*/
export function issJointTargets(
sun,
sunlit,
previous = { alpha: 0, gamma: 0 },
) {
const [sx, sy, sz] = sun;
// Radiators: the panel normal, Y at rest, perpendicular to the Sun.
const gamma =
Math.hypot(sx, sy) < MIN_STEER
? previous.gamma
: nearestHalfTurn(Math.atan2(sy, sx), previous.gamma);
if (!sunlit) {
return {
alpha: nearestHalfTurn(0, previous.alpha),
beta: ISS_BETA_JOINTS.map(() => 0),
gamma,
};
}
// Alpha: the masts, ±Z at rest, perpendicular to the Sun.
const alpha =
Math.hypot(sy, sz) < MIN_STEER
? previous.alpha
: nearestHalfTurn(Math.atan2(sz, sy), previous.alpha);
// The Sun as the arrays see it before the alpha turn.
const c = Math.cos(alpha);
const s = Math.sin(alpha);
const lx = sx;
const ly = c * sy + s * sz;
// Beta: the cell side's normal, ±X at rest, onto the Sun.
const beta = ISS_BETA_JOINTS.map(({ face }) =>
Math.atan2(face * ly, face * lx),
);
return { alpha, beta, gamma };
}
/**
* Step `current` toward `target` the short way round, by at most `maxStep`.
* @returns {number}
*/
export function issStepAngle(current, target, maxStep) {
const delta = wrap(target - current);
if (Math.abs(delta) <= maxStep) return current + delta;
return current + Math.sign(delta) * maxStep;
}
/**
* A node's matrix for a turn of `angle` about `axis` ('x' or 'z') through
* `pivot`, column-major.
* @param {'x'|'z'} axis
* @param {number[]} pivot
* @param {number} angle Radians.
* @param {ArrayLike<number>} result Any 16-slot array, column-major.
* @returns {ArrayLike<number>} `result`.
*/
export function issJointMatrix(axis, pivot, angle, result) {
const c = Math.cos(angle);
const s = Math.sin(angle);
const [px, py, pz] = pivot;
// Row-major arguments.
if (axis === 'x')
return set(result, [
1,
0,
0,
0,
0,
c,
-s,
py - (c * py - s * pz),
0,
s,
c,
pz - (s * py + c * pz),
0,
0,
0,
1,
]);
return set(result, [
c,
-s,
0,
px - (c * px - s * py),
s,
c,
0,
py - (s * px + c * py),
0,
0,
1,
0,
0,
0,
0,
1,
]);
}
/**
* Write a row-major 4×4 into `result`, column-major (a renderer's matrix
* layout; `result` is any 16-slot array).
* @param {ArrayLike<number> & {[i: number]: number}} [result] A new one when not given.
* @param {number[]} rowMajor
*/
function set(result, rowMajor) {
result ??= new Float64Array(16);
for (let row = 0; row < 4; row++)
for (let column = 0; column < 4; column++)
result[column * 4 + row] = rowMajor[row * 4 + column];
return result;
}
/**
* Canadarm2's seven joints as NASA's file names them, base to tip: each
* node's pivot and its local Z axis on the model's axes. Where the real arm
* is at any moment is not public, so its motion here is ILLUSTRATIVE: a slow
* sway of `sway` radians about the pose in NASA's file, over `period`
* seconds. Joints with no sway stay as filed.
*/
export const ISS_ARM_JOINTS = Object.freeze(
[
['SHR', [0.6732, -9.3793, 8.3367], [-0.0942, -0.0136, 0.9955], 0, 0],
['SHY', [0.6004, -9.3899, 9.105], [-0.2949, 0.9554, -0.0148], 8, 97],
['SHP_PRIME', [0.7848, -9.9873, 9.1143], [-0.2949, 0.9554, -0.0148], 6, 71],
[
'ELP_PRIME',
[-2.9987, -11.8039, 2.5061],
[-0.2949, 0.9554, -0.0148],
12,
53,
],
['WRP', [-3.8898, -12.6132, 10.249], [-0.2949, 0.9554, -0.0148], 10, 41],
['WRY', [-3.9961, -12.6341, 11.0132], [-0.2949, 0.9554, -0.0148], 0, 0],
['WRR', [-4.2995, -12.7285, 10.9684], [0.2874, -0.5533, -0.7818], 0, 0],
].map(([node, pivot, axis, swayDeg, period]) =>
Object.freeze({
node,
pivot,
axis,
sway: (swayDeg * Math.PI) / 180,
period,
}),
),
);
/**
* The station's smaller arms, swayed the same illustrative way: Dextre's two
* arms (shoulder and elbow pitch each) and the Japanese arm on Kibo
* (shoulder, elbow and wrist pitch). The European arm on Nauka has no joints
* in NASA's file, so it stays as filed.
*/
export const ISS_SMALL_ARM_JOINTS = Object.freeze(
[
[
'SPDM_Arm1_SHP',
[4.3019, -8.7313, 2.9551],
[-0.5183, -0.8218, -0.2366],
5,
61,
],
[
'SPDM_Arm1_ELP',
[4.763, -7.9839, 3.1897],
[0.2256, 0.4303, -0.874],
7,
43,
],
[
'SPDM_Arm2_SHP',
[1.8182, -9.8753, 5.2105],
[-0.27, -0.522, -0.8091],
5,
67,
],
[
'SPDM_Arm2_ELP',
[1.8575, -9.4898, 6.0546],
[-0.3202, -0.5495, -0.7717],
7,
47,
],
['JEM_SP_ROT', [14.2188, -3.6716, 13.394], [-0.001, 0, -1], 5, 83],
['JEM_EP_ROT', [14.2223, 0.6479, 13.394], [-0.0011, 0, -1], 8, 59],
['JEM_WP_ROT', [16.4495, -3.0694, 13.3917], [-0.001, 0, -1], 8, 37],
].map(([node, pivot, axis, swayDeg, period]) =>
Object.freeze({
node,
pivot,
axis,
sway: (swayDeg * Math.PI) / 180,
period,
}),
),
);
/** Every joint that sways. */
const ISS_SWAY_JOINTS = [...ISS_ARM_JOINTS, ...ISS_SMALL_ARM_JOINTS];
/** The arm joints the sway moves; the rest hold NASA's filed pose. */
const ISS_SWAYING_NODES = new Set(
ISS_SWAY_JOINTS.filter((joint) => joint.sway).map((joint) => joint.node),
);
/**
* The arm's illustrative joint angles at a wall-clock time.
* @param {number} seconds
* @returns {number[]} Radians, one per ISS_ARM_JOINTS entry.
*/
export function issArmAngles(seconds, joints = ISS_ARM_JOINTS) {
return joints.map(({ sway, period }) =>
sway ? sway * Math.sin((2 * Math.PI * seconds) / period) : 0,
);
}
/**
* The two Ku-band dishes on the Z1 truss. NASA's file has them welded into
* the truss; the build cuts out everything above each gimbal. At rest a dish
* looks along +Y (zenith).
*/
export const ISS_DISH_JOINTS = Object.freeze([
Object.freeze({ node: 'SGANT_ROT_1', pivot: [-1.105, 4.5, -4.885] }),
Object.freeze({ node: 'SGANT_ROT_2', pivot: [4.56, 4.64, -5.235] }),
]);
/**
* The relay satellites the dishes talk to (NASA's TDRS) sit over the equator
* at fixed longitudes, so each is a fixed point in the Earth-fixed frame.
* These are the fleet's nominal slots (Atlantic, Pacific, Indian Ocean), not
* a live roster: which satellite the station uses at a given moment is not
* public in real time.
*/
export const ISS_RELAY_LONGITUDES_DEG = Object.freeze([-41, -171, 85]);
const GEOSTATIONARY_RADIUS_M = 42_164_000;
/** A dish does not look below this much above the station's horizon plane. */
const DISH_MIN_UP = 0.15;
/**
* Where the relay satellites are from the station, on the model's axes, the
* highest above the station first.
* @param {number[]} positionEcef Meters.
* @param {{x:number[], y:number[], z:number[]}} axes Flight axes.
* @param {readonly number[]} [longitudes] The relays' slots, degrees east;
* NASA's for the ISS, another station passes its own.
* @returns {number[][]} Unit vectors [port, zenith, forward].
*/
export function issRelayDirections(
positionEcef,
axes,
longitudes = ISS_RELAY_LONGITUDES_DEG,
) {
return longitudes
.map((longitude) => {
const lon = (longitude * Math.PI) / 180;
const to = [
GEOSTATIONARY_RADIUS_M * Math.cos(lon) - positionEcef[0],
GEOSTATIONARY_RADIUS_M * Math.sin(lon) - positionEcef[1],
-positionEcef[2],
];
const length = Math.hypot(to[0], to[1], to[2]);
return issSunInModelFrame(
to.map((c) => c / length),
axes,
);
})
.sort((a, b) => b[1] - a[1]);
}
/**
* Turn the unit vector `current` toward `target` by at most `maxStep` radians.
* @returns {number[]}
*/
export function issStepDirection(current, target, maxStep) {
const cos = Math.min(
1,
Math.max(
-1,
current[0] * target[0] + current[1] * target[1] + current[2] * target[2],
),
);
const angle = Math.acos(cos);
if (angle <= maxStep || angle < 1e-6) return target;
const sin = Math.sin(angle);
// Opposite vectors have no single arc between them: nudge off the line.
if (sin < 1e-6)
return issStepDirection(
[current[2], current[0], current[1]],
target,
maxStep,
);
const t = maxStep / angle;
const a = Math.sin((1 - t) * angle) / sin;
const b = Math.sin(t * angle) / sin;
return [0, 1, 2].map((i) => a * current[i] + b * target[i]);
}
/**
* A node's matrix for a turn of `angle` about the unit vector `axis` through
* `pivot`.
* @param {number[]} pivot
* @param {number[]} axis Unit vector.
* @param {number} angle Radians.
* @param {ArrayLike<number>} result Any 16-slot array, column-major.
* @returns {ArrayLike<number>} `result`.
*/
export function issAxisMatrix(pivot, axis, angle, result) {
const [x, y, z] = axis;
const c = Math.cos(angle);
const s = Math.sin(angle);
const t = 1 - c;
const r = [
[t * x * x + c, t * x * y - s * z, t * x * z + s * y],
[t * x * y + s * z, t * y * y + c, t * y * z - s * x],
[t * x * z - s * y, t * y * z + s * x, t * z * z + c],
];
const rows = r.map((row, i) => [
...row,
pivot[i] - (row[0] * pivot[0] + row[1] * pivot[1] + row[2] * pivot[2]),
]);
return set(result, [...rows[0], ...rows[1], ...rows[2], 0, 0, 0, 1]);
}
/**
* A dish node's matrix that turns its rest boresight (+Y) onto `direction`.
* @param {number[]} pivot
* @param {number[]} direction Unit vector on the model's axes.
* @param {ArrayLike<number>} result Any 16-slot array, column-major.
* @returns {ArrayLike<number>} `result`.
*/
export function issAimMatrix(pivot, direction, result) {
// Y × direction
const kx = direction[2];
const kz = -direction[0];
const length = Math.hypot(kx, kz);
if (length < 1e-9)
return issAxisMatrix(
pivot,
[1, 0, 0],
direction[1] > 0 ? 0 : Math.PI,
result,
);
const angle = Math.acos(Math.min(1, Math.max(-1, direction[1])));
return issAxisMatrix(pivot, [kx / length, 0, kz / length], angle, result);
}
/**
* Drives the loaded model's joints. Stateless about the model: `update` looks
* the nodes up once per model and only writes a node whose angle moved.
*/
export function createIssArticulation() {
let boundModel = null;
let nodes = null;
let angles = null;
let targets = { alpha: 0, gamma: 0 };
let lastMs = 0;
let override = null;
let dishOverride = null;
/** Gives the joint angles from telemetry, or null: see setTelemetry. */
let telemetry = null;
/** Command panel state: Manual takes the joints, so telemetry is off. */
let telemetryAllowed = true;
/** Whether the last update took its angles from telemetry; null before one. */
let lastLive = null;
/** Whether the last update had the station in sunlight; null before one. */
let lastSunlit = null;
/** Command panel state: the arm is being posed by hand, so the sway is off. */
/** The arm joints posed by hand (command panel); the rest keep swaying. */
const manualJoints = new Set();
let armNodes = null;
/** Command panel state: how far the arrays are rolled out, 0.05 to 1. */
let deploy = 1;
let deployTarget = 1;
let radiatorDeploy = 1;
let radiatorTarget = 1;
/** The truss face the radiators fold back to, on the model's Z axis. */
const RADIATOR_ROOT_Z = -1.9;
/** The power modules' radiators, cut out by the build, and their root. */
const SMALL_RADIATOR_NODES = [
'PVR_FOLD_P4',
'PVR_FOLD_P6',
'PVR_FOLD_S4',
'PVR_FOLD_S6',
];
const SMALL_RADIATOR_ROOT_Y = -1.6;
/** Where each dish looks now, on the model's axes. */
let dishes = null;
const scratchMatrix = new Float64Array(16);
function bind(model) {
boundModel = model;
const get = (joint) => model.getNode(joint.node) ?? null;
nodes = {
alpha: ISS_ALPHA_JOINTS.map(get),
beta: ISS_BETA_JOINTS.map(get),
gamma: ISS_RADIATOR_JOINTS.map(get),
dish: ISS_DISH_JOINTS.map(get),
};
angles = null;
dishes = null;
armNodes = null;
}
function sunEcef(date) {
const sun = sunPositionFixed(date.getTime());
const length = Math.hypot(sun.x, sun.y, sun.z) || 1;
return [sun.x / length, sun.y / length, sun.z / length];
}
function write(node, axis, pivot, angle) {
if (!node) return;
node.matrix = issJointMatrix(axis, pivot, angle, scratchMatrix);
}
/**
* @param {{ready: boolean, getNode: (name: string) => object|undefined}} model
* A ready model, or any holder of nodes that take a `matrix`.
* @param {Date} date The instant the model is placed at.
* @param {{x:number,y:number,z:number}} position Earth-fixed station position.
* @param {{x:number[], y:number[], z:number[]}} axes Its flight axes.
* @param {number} [nowMs] Wall clock, for the turn rate.
*/
function update(model, date, position, axes, nowMs = Date.now()) {
if (!model.ready) return;
if (model !== boundModel) bind(model);
const forced = override?.(nowMs) ?? null;
if (forced) {
lastSunlit = Boolean(forced.sunlit);
targets = issJointTargets(forced.sun, forced.sunlit, targets);
} else {
const sun = sunEcef(date);
const sunlit = !issInShadow([position.x, position.y, position.z], sun);
lastSunlit = sunlit;
targets = issJointTargets(issSunInModelFrame(sun, axes), sunlit, targets);
}
// Telemetry, when it has a pose, replaces the computed targets; a Sun
// chosen by hand in the command panel is always computed.
const pose = telemetryAllowed && !forced ? (telemetry?.() ?? null) : null;
lastLive = Boolean(pose);
const alphaTargets = pose?.alpha ?? [targets.alpha, targets.alpha];
const betaTargets = pose?.beta ?? targets.beta;
const gammaTargets = pose?.gamma ?? [targets.gamma, targets.gamma];
// A first frame, or one after a pause, goes straight to the pose.
const elapsed = (nowMs - lastMs) / 1000;
lastMs = nowMs;
const maxStep =
!angles || !(elapsed >= 0) || elapsed > 2
? Number.POSITIVE_INFINITY
: ISS_JOINT_RATE * elapsed;
const next = {
alpha: alphaTargets.map((target, i) =>
issStepAngle(angles?.alpha[i] ?? 0, target, maxStep),
),
beta: betaTargets.map((target, i) =>
issStepAngle(angles?.beta[i] ?? 0, target, maxStep),
),
gamma: gammaTargets.map((target, i) =>
issStepAngle(angles?.gamma[i] ?? 0, target, maxStep),
),
};
ISS_ALPHA_JOINTS.forEach((joint, i) => {
if (!angles || next.alpha[i] !== angles.alpha[i])
write(nodes.alpha[i], 'x', joint.pivot, next.alpha[i]);
});
// Command panel: squash the arrays along their masts (see setDeploy).
const deployStep = Number.isFinite(maxStep) ? elapsed / 8 : 1;
const nextDeploy =
deploy +
Math.sign(deployTarget - deploy) *
Math.min(Math.abs(deployTarget - deploy), deployStep);
ISS_BETA_JOINTS.forEach((joint, i) => {
if (
!angles ||
next.beta[i] !== angles.beta[i] ||
nextDeploy !== deploy ||
nextDeploy !== 1
) {
const node = nodes.beta[i];
if (!node) return;
const m = issJointMatrix('z', joint.pivot, next.beta[i], scratchMatrix);
m[10] = nextDeploy;
m[14] = joint.pivot[2] * (1 - nextDeploy);
node.matrix = m;
}
});
deploy = nextDeploy;
// Command panel: fold the radiators toward the truss.
const nextRadiator =
radiatorDeploy +
Math.sign(radiatorTarget - radiatorDeploy) *
Math.min(Math.abs(radiatorTarget - radiatorDeploy), deployStep);
ISS_RADIATOR_JOINTS.forEach((joint, i) => {
if (
angles &&
next.gamma[i] === angles.gamma[i] &&
nextRadiator === radiatorDeploy
)
return;
const node = nodes.gamma[i];
if (!node) return;
const m = issJointMatrix('z', joint.pivot, next.gamma[i], scratchMatrix);
m[10] = nextRadiator;
m[14] = RADIATOR_ROOT_Z * (1 - nextRadiator);
node.matrix = m;
});
// The four small radiators fold up to the truss, along Y.
if (nextRadiator !== radiatorDeploy)
for (const name of SMALL_RADIATOR_NODES) {
const node = model.getNode(name);
if (!node) continue;
node.matrix = set(scratchMatrix, [
1,
0,
0,
0,
0,
nextRadiator,
0,
SMALL_RADIATOR_ROOT_Y * (1 - nextRadiator),
0,
0,
1,
0,
0,
0,
0,
1,
]);
}
radiatorDeploy = nextRadiator;
angles = next;
// Dishes: the highest relay satellite for the first, the next for the
// second; one below the station's horizon plane keeps its last aim.
// Telemetry reports one dish (the station uses one at a time, and does
// not say which): the first takes its real aim, wherever that is, and
// the second holds still.
const liveDish = !dishOverride && pose?.dish ? pose.dish : null;
const relays = dishOverride
? [dishOverride, dishOverride]
: liveDish
? [liveDish, null]
: issRelayDirections([position.x, position.y, position.z], axes);
const nextDishes = ISS_DISH_JOINTS.map((joint, i) => {
const current = dishes?.[i] ?? [0, 1, 0];
const wanted = relays[i];
const target =
wanted && (liveDish || wanted[1] >= DISH_MIN_UP) ? wanted : current;
const stepped = issStepDirection(current, target, maxStep);
const moved =
!dishes || stepped.some((c, k) => Math.abs(c - current[k]) > 1e-9);
if (moved)
if (nodes.dish[i])
nodes.dish[i].matrix = issAimMatrix(
joint.pivot,
stepped,
scratchMatrix,
);
return stepped;
});
dishes = nextDishes;
// Arm: an illustrative sway (see ISS_ARM_JOINTS).
{
const arm = issArmAngles(nowMs / 1000, ISS_SWAY_JOINTS);
ISS_SWAY_JOINTS.forEach((joint, i) => {
if (!joint.sway || manualJoints.has(joint.node)) return;
const node = (armNodes ??= ISS_SWAY_JOINTS.map(
(entry) => model.getNode(entry.node) ?? null,
))[i];
if (node)
node.matrix = issAxisMatrix(
joint.pivot,
joint.axis,
arm[i],
scratchMatrix,
);
});
}
}
/**
* Command panel: turn any named node about an axis through a pivot.
* @param {string} name
* @param {number[]} pivot
* @param {number[]} axis Unit vector.
* @param {number} angle Radians.
*/
function setJoint(name, pivot, axis, angle) {
manualJoints.add(name);
const node = boundModel?.getNode(name);
if (node) node.matrix = issAxisMatrix(pivot, axis, angle, scratchMatrix);
}
/** Forget the model and every manual choice: the next update starts clean. */
function reset() {
boundModel = null;
nodes = null;
angles = null;
dishes = null;
armNodes = null;
targets = { alpha: 0, gamma: 0 };
override = null;
dishOverride = null;
telemetryAllowed = true;
manualJoints.clear();
}
/**
* Command panel: a function giving the Sun on the model's axes (and whether the
* station is lit) in place of the real one, or null for the real one.
* @param {((nowMs:number)=>{sun:number[], sunlit:boolean}|null)|null} fn
*/
function setOverride(fn) {
override = fn;
}
/** Whether the station is in sunlight, as of the last update. */
function isSunlit() {
return lastSunlit;
}
/**
* Where the joint angles come from when telemetry has them: a function
* giving `{alpha, beta, gamma, dish}` (issTelemetryPose) or null.
* @param {(() => {alpha:number[], beta:number[], gamma:number[],
* dish:number[]|null}|null)|null} fn
*/
function setTelemetry(fn) {
telemetry = fn;
}
/** Command panel: Manual switches telemetry off, Automatic back on. */
function setTelemetryAllowed(allowed) {
telemetryAllowed = Boolean(allowed);
}
/** Whether the last update took its angles from telemetry; null before one. */
function isLive() {
return lastLive;
}
/** Command panel: aim both dishes along a unit vector, or null for the relays. */
function setDishOverride(direction) {
dishOverride = direction;
}
/**
* Command panel: squash the arrays toward their bases, or let them
* out again. The real arrays do not retract in service.
* @param {boolean} out
*/
function setDeploy(out) {
deployTarget = out ? 1 : 0.05;
}
/**
* Command panel: fold the radiators toward the truss, or let them
* out. The real ones are accordion panels that can do this, but stay out
* in service.
* @param {boolean} out
*/
function setRadiatorDeploy(out) {
radiatorTarget = out ? 1 : 0.08;
}
/** Command panel: hand the arm back to its sway. */
function resumeArm() {
// A joint the sway does not move would keep its manual angle: it goes
// back to its filed pose. The swaying ones are posed again next update.
for (const name of manualJoints) {
if (ISS_SWAYING_NODES.has(name)) continue;
const node = boundModel?.getNode(name);
if (node) node.matrix = undefined;
}
manualJoints.clear();
}
return {
update,
reset,
setOverride,
setDishOverride,
setJoint,
resumeArm,
setDeploy,
setRadiatorDeploy,
isSunlit,
setTelemetry,
setTelemetryAllowed,
isLive,
};
}
@@ -0,0 +1,231 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import test from 'node:test';
import {
ISS_ALPHA_JOINTS,
ISS_BETA_JOINTS,
ISS_RADIATOR_JOINTS,
issInShadow,
issJointMatrix,
issJointTargets,
issStepAngle,
issSunInModelFrame,
} from './issArticulation.js';
const rotX = (a, [x, y, z]) => [
x,
Math.cos(a) * y - Math.sin(a) * z,
Math.sin(a) * y + Math.cos(a) * z,
];
const rotZ = (a, [x, y, z]) => [
Math.cos(a) * x - Math.sin(a) * y,
Math.sin(a) * x + Math.cos(a) * y,
z,
];
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const unit = (v) => v.map((c) => c / Math.hypot(...v));
const SUNS = [
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0.5, 0.5, 0.7],
[-0.6, 0.2, -0.77],
[0.3, -0.9, 0.3],
[0.9, 0.1, -0.4],
].map(unit);
test('in sunlight every array faces the Sun, masts across it', () => {
for (const sun of SUNS) {
const { alpha, beta } = issJointTargets(sun, true);
assert.ok(Math.abs(dot(rotX(alpha, [0, 0, 1]), sun)) < 1e-9);
ISS_BETA_JOINTS.forEach(({ face }, i) => {
// The beta joint hangs from the alpha joint: beta turns first.
const normal = rotX(alpha, rotZ(beta[i], [face, 0, 0]));
assert.ok(dot(normal, sun) > 1 - 1e-9, `${sun} array ${i}`);
});
}
});
test('the radiators stay edge-on to the Sun', () => {
for (const sun of SUNS) {
const { gamma } = issJointTargets(sun, true);
assert.ok(Math.abs(dot(rotZ(gamma, [0, 1, 0]), sun)) < 1e-9);
}
});
test('in the shadow the arrays feather along the flight direction', () => {
const { alpha, beta } = issJointTargets(unit([0.2, -0.9, 0.3]), false, {
alpha: 3,
gamma: 0,
});
assert.ok(Math.abs(Math.sin(alpha)) < 1e-9); // masts back along ±Z
assert.ok(Math.abs(alpha - Math.PI) < 1e-9); // the nearer half turn
assert.deepEqual(
beta,
ISS_BETA_JOINTS.map(() => 0),
);
});
test('a joint keeps the answer nearer its last one, and holds near its axis', () => {
const first = issJointTargets(unit([0, 1, 0.01]), true);
const next = issJointTargets(unit([0, 1, -0.01]), true, first);
assert.ok(Math.abs(next.alpha - first.alpha) < 0.05);
// Sun along the truss: nothing to steer the alpha joint by.
const held = issJointTargets([1, 0, 0], true, { alpha: 1.2, gamma: 0.4 });
assert.equal(held.alpha, 1.2);
});
test('angles step the short way round, capped', () => {
assert.equal(issStepAngle(0, 1, 0.25), 0.25);
assert.ok(issStepAngle(3, -3, 0.1) > 3); // through π, not back through 0
assert.equal(issStepAngle(0.2, 0.3, 1), 0.3);
});
test('a joint matrix leaves its pivot in place', () => {
for (const axis of ['x', 'z']) {
const pivot = [3, -2, 5];
const m = issJointMatrix(axis, pivot, 0.7, undefined);
const moved = [0, 1, 2].map(
(r) =>
m[r] * pivot[0] + m[4 + r] * pivot[1] + m[8 + r] * pivot[2] + m[12 + r],
);
moved.forEach((v, i) => assert.ok(Math.abs(v - pivot[i]) < 1e-12));
}
});
test('the shadow is the cylinder behind the Earth', () => {
const sun = [1, 0, 0];
assert.equal(issInShadow([6_790_000, 0, 0], sun), false);
assert.equal(issInShadow([-6_790_000, 0, 0], sun), true);
assert.equal(issInShadow([-1_000_000, 6_700_000, 0], sun), false);
});
test('the Sun lands on the model axes: port, zenith, forward', () => {
const axes = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
assert.deepEqual(issSunInModelFrame([0.1, 0.2, 0.3], axes), [0.2, 0.3, 0.1]);
});
test('the model file has every joint node, beta joints under their alpha', () => {
const buf = fs.readFileSync(
new URL('../../../public/models/iss.glb', import.meta.url),
);
const json = JSON.parse(
buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'),
);
const byName = new Map(json.nodes.map((n) => [n.name, n]));
for (const { node } of [
...ISS_ALPHA_JOINTS,
...ISS_BETA_JOINTS,
...ISS_RADIATOR_JOINTS,
]) {
const n = byName.get(node);
assert.ok(n, node);
// Joints rest at identity: the pivots above are in the model's own frame.
assert.equal(n.rotation, undefined);
assert.equal(n.translation, undefined);
assert.equal(n.matrix, undefined);
}
for (const side of ['PORT', 'STBD']) {
const kids = byName
.get(`${side}_ALPHA_ROT`)
.children.map((i) => json.nodes[i].name);
for (const { node } of ISS_BETA_JOINTS)
if (node.startsWith(side)) assert.ok(kids.includes(node), node);
}
});
test('a dish aims its rest boresight (+Y) at the direction, pivot in place', async () => {
const { issAimMatrix, ISS_DISH_JOINTS } =
await import('./issArticulation.js');
for (const direction of SUNS) {
const m = issAimMatrix(ISS_DISH_JOINTS[0].pivot, direction, undefined);
// Column 1 is where +Y goes.
[m[4], m[5], m[6]].forEach((v, i) =>
assert.ok(Math.abs(v - direction[i]) < 1e-9),
);
const p = ISS_DISH_JOINTS[0].pivot;
[0, 1, 2].forEach((r) =>
assert.ok(
Math.abs(
m[r] * p[0] + m[4 + r] * p[1] + m[8 + r] * p[2] + m[12 + r] - p[r],
) < 1e-9,
),
);
}
});
test('relay directions are unit vectors, highest above the station first', async () => {
const { issRelayDirections } = await import('./issArticulation.js');
// Over the equator at 41°W, flying east: the Atlantic relay is overhead.
const lon = (-41 * Math.PI) / 180;
const r = 6_790_000;
const position = [r * Math.cos(lon), r * Math.sin(lon), 0];
const zenith = [Math.cos(lon), Math.sin(lon), 0];
const east = [-Math.sin(lon), Math.cos(lon), 0];
const axes = { x: east, y: [0, 0, 1], z: zenith };
const relays = issRelayDirections(position, axes);
assert.equal(relays.length, 3);
relays.forEach((d) => assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-9));
assert.ok(relays[0][1] > 0.999);
assert.ok(relays[0][1] >= relays[1][1] && relays[1][1] >= relays[2][1]);
});
test('a direction steps along the arc, capped, and lands on the target', async () => {
const { issStepDirection } = await import('./issArticulation.js');
const stepped = issStepDirection([0, 1, 0], [1, 0, 0], 0.1);
assert.ok(Math.abs(Math.hypot(...stepped) - 1) < 1e-9);
assert.ok(Math.abs(Math.acos(stepped[1]) - 0.1) < 1e-9);
assert.deepEqual(issStepDirection([0, 1, 0], [1, 0, 0], 2), [1, 0, 0]);
});
test('the model file has both dish nodes', async () => {
const { ISS_DISH_JOINTS } = await import('./issArticulation.js');
const buf = fs.readFileSync(
new URL('../../../public/models/iss.glb', import.meta.url),
);
const json = JSON.parse(
buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'),
);
for (const { node } of ISS_DISH_JOINTS) {
const n = json.nodes.find((candidate) => candidate.name === node);
assert.ok(n?.children?.length, node);
}
});
test('the arm sways gently about the filed pose, and only where it is set to', async () => {
const { ISS_ARM_JOINTS, issArmAngles } = await import('./issArticulation.js');
assert.equal(ISS_ARM_JOINTS.length, 7);
for (let seconds = 0; seconds < 400; seconds += 7) {
issArmAngles(seconds).forEach((angle, i) => {
assert.ok(Math.abs(angle) <= ISS_ARM_JOINTS[i].sway + 1e-12);
// Illustrative, so kept small.
assert.ok(Math.abs(angle) <= (12 * Math.PI) / 180 + 1e-12);
});
}
assert.deepEqual(issArmAngles(0), [0, 0, 0, 0, 0, 0, 0]);
});
test('the smaller arms sway too, and their joints are in the model file', async () => {
const { ISS_SMALL_ARM_JOINTS, ISS_ARM_JOINTS, issArmAngles } =
await import('./issArticulation.js');
const buf = fs.readFileSync(
new URL('../../../public/models/iss.glb', import.meta.url),
);
const json = JSON.parse(
buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'),
);
const names = new Set(json.nodes.map((n) => n.name));
for (const { node, sway, axis } of [
...ISS_ARM_JOINTS,
...ISS_SMALL_ARM_JOINTS,
]) {
assert.ok(names.has(node), node);
assert.ok(sway <= (12 * Math.PI) / 180 + 1e-12);
assert.ok(Math.abs(Math.hypot(...axis) - 1) < 1e-3);
}
assert.equal(
issArmAngles(10, ISS_SMALL_ARM_JOINTS).length,
ISS_SMALL_ARM_JOINTS.length,
);
});
+105
View File
@@ -0,0 +1,105 @@
const unit = (v) => {
const n = Math.hypot(...v);
return v.map((c) => c / n);
};
/** Where "Zoom to the ISS" stops: the whole 109 m station fills the view. */
export const ISS_COMMAND_ZOOM_RANGE_M = 260;
/** Beyond this the camera counts as far, and the zoom button is offered. */
export const ISS_COMMAND_FAR_M = 1000;
/**
* Whether "Zoom to the ISS" is offered: only from far away, so it goes once
* the camera is in close (by the button or by hand) and returns on zooming
* back out.
* @param {number} distance Meters from the camera to the station.
* @returns {boolean}
*/
export function issCommandOffersZoom(distance) {
return distance > ISS_COMMAND_FAR_M;
}
/**
* One step of the zoom: how far to move in from `distance`, easing out as
* the target range nears, never past it.
* @param {number} distance Meters from the camera to the station.
* @returns {number} Meters to move in; 0 once close enough.
*/
export function issCommandZoomStep(distance) {
const left = distance - ISS_COMMAND_ZOOM_RANGE_M;
if (!(left > ISS_COMMAND_ZOOM_RANGE_M * 0.02)) return 0;
return left * 0.14;
}
/**
* The follow camera's range after one step of the zoom: the step nearer,
* never past the target range, and unchanged once there. The camera is moved
* by scaling its follow offset from the station (the camera port's
* `followOffset`, the eye in the follow's frame) by
* `issCommandZoomRange(range) / range`, which can only bring it in; a move
* along the view direction is not used, since it ran away when the camera
* was not looking at the station.
* @param {number} range Meters from the camera to the station.
* @returns {number} The range to set; `range` itself when there is no step.
*/
export function issCommandZoomRange(range) {
if (!(range > 0) || !Number.isFinite(range)) return range;
const step = issCommandZoomStep(range);
return step > 0 ? Math.max(ISS_COMMAND_ZOOM_RANGE_M, range - step) : range;
}
/**
* One step of the zoom on the follow offset: the same offset, shortened to
* `issCommandZoomRange` of its length, so the eye keeps its bearing on the
* station and only comes in.
* @param {{x: number, y: number, z: number}|null|undefined} offset The
* eye's offset from the station, metres in the follow's frame.
* @returns {{x: number, y: number, z: number}|null} The offset to set; null
* when there is no step (close enough, or no offset to shorten).
*/
export function issCommandZoomOffset(offset) {
if (!offset) return null;
const range = Math.hypot(offset.x, offset.y, offset.z);
const next = issCommandZoomRange(range);
if (!(next < range)) return null;
const k = next / range;
return { x: offset.x * k, y: offset.y * k, z: offset.z * k };
}
/**
* Whether the zoom may run: only while the camera follows the station's
* follow target and has framed it, so that its follow offset is the eye's
* offset from the station and shortening it brings the camera in. From any
* other camera (still flying to the station, following something else, or
* a follow not yet framed) there is no such offset to shorten.
* @param {{followed?: object|null, followFramed?: boolean}|null|undefined}
* camera What the camera port reports (`cameraOf(viewer)`).
* @param {object|null|undefined} target The layer's follow target for the
* station (`layerState._followTarget`).
* @returns {boolean}
*/
export function issCommandCameraOnStation(camera, target) {
return (
Boolean(target) &&
camera?.followed === target &&
camera.followFramed === true
);
}
/** How long one lap of the "fast orbit" takes, and its share in shadow. */
const FAST_ORBIT_MS = 40_000;
/**
* The Sun over one accelerated orbit: it circles the truss, a third of the
* lap in the Earth's shadow.
* @param {number} elapsedMs
* @returns {{sun: number[], sunlit: boolean}}
*/
export function issCommandFastOrbit(elapsedMs) {
const angle = (elapsedMs / FAST_ORBIT_MS) * 2 * Math.PI;
return {
sun: unit([0.35, Math.cos(angle), Math.sin(angle)]),
sunlit: Math.cos(angle) > -0.5,
};
}
+141
View File
@@ -0,0 +1,141 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
issCommandCameraOnStation,
issCommandZoomOffset,
issCommandZoomRange,
ISS_COMMAND_ZOOM_RANGE_M,
issCommandFastOrbit,
issCommandZoomStep,
} from './issCommand.js';
import { ISS_NORAD } from './policy.js';
test('the zoom eases in to its range and stops there, never past it', () => {
let distance = 726_000;
let steps = 0;
for (; steps < 400; steps++) {
const step = issCommandZoomStep(distance);
if (!step) break;
assert.ok(step > 0 && step < distance - ISS_COMMAND_ZOOM_RANGE_M);
distance -= step;
}
assert.ok(steps < 120); // under two seconds at 60 frames a second
assert.ok(distance >= ISS_COMMAND_ZOOM_RANGE_M);
assert.ok(distance <= ISS_COMMAND_ZOOM_RANGE_M * 1.02 + 1e-6);
// Already closer: nothing to do, and it never pushes the camera back out.
assert.equal(issCommandZoomStep(180), 0);
});
test('the fast orbit turns the Sun once per lap, part of it in shadow', () => {
const start = issCommandFastOrbit(0);
assert.ok(Math.abs(Math.hypot(...start.sun) - 1) < 1e-9);
assert.equal(start.sunlit, true);
assert.equal(issCommandFastOrbit(20_000).sunlit, false); // half a lap: below
const lap = issCommandFastOrbit(40_000);
lap.sun.forEach((v, i) => assert.ok(Math.abs(v - start.sun[i]) < 1e-9));
});
test('the zoom is offered only from far away', async () => {
const { ISS_COMMAND_FAR_M, issCommandOffersZoom } =
await import('./issCommand.js');
assert.equal(issCommandOffersZoom(726_000), true);
assert.equal(issCommandOffersZoom(ISS_COMMAND_FAR_M + 1), true);
// Where the zoom itself stops, and anywhere closer, it is gone.
assert.equal(issCommandOffersZoom(ISS_COMMAND_ZOOM_RANGE_M * 1.02), false);
assert.equal(issCommandOffersZoom(150), false);
});
test('an object docked to the ISS is the station too', async () => {
const { issTrackedOnStation } = await import('./policy.js');
const NAUKA = 49044;
// Tracking Nauka, the ISS shares its position; tracking the ISS needs nothing.
assert.equal(issTrackedOnStation(ISS_NORAD, new Set()), true);
assert.equal(issTrackedOnStation(ISS_NORAD, null), true);
assert.equal(issTrackedOnStation(NAUKA, new Set([ISS_NORAD, 68837])), true);
// Another satellite, with or without neighbours, is not.
assert.equal(issTrackedOnStation(20580, new Set()), false);
assert.equal(issTrackedOnStation(20580, new Set([20581])), false);
assert.equal(issTrackedOnStation(null, new Set([ISS_NORAD])), false);
assert.equal(issTrackedOnStation(undefined, undefined), false);
});
test('the zoom range only ever shortens, settles at the target range and never runs away', () => {
let range = 1e9;
let steps = 0;
while (steps < 400) {
const next = issCommandZoomRange(range);
assert.ok(next <= range, `step ${steps} moved out: ${range} -> ${next}`);
assert.ok(next >= ISS_COMMAND_ZOOM_RANGE_M, 'never past the target');
if (next === range) break;
range = next;
steps += 1;
}
assert.ok(steps < 400, "settles within the loop's budget");
assert.ok(range <= ISS_COMMAND_ZOOM_RANGE_M * 1.02);
assert.equal(
issCommandZoomRange(ISS_COMMAND_ZOOM_RANGE_M),
ISS_COMMAND_ZOOM_RANGE_M,
);
assert.equal(
issCommandZoomRange(100),
100,
'closer than the range: left alone',
);
for (const bad of [0, -5, NaN, Infinity])
assert.ok(
Object.is(issCommandZoomRange(bad), bad),
`${bad} passes through`,
);
});
test('one zoom step shortens the follow offset on its own bearing, and stops at the range', () => {
const next = issCommandZoomOffset({ x: 3000, y: 4000, z: 0 });
const range = Math.hypot(next.x, next.y, next.z);
assert.ok(Math.abs(range - issCommandZoomRange(5000)) < 1e-9);
assert.ok(Math.abs(next.x / next.y - 3 / 4) < 1e-12, 'the bearing is kept');
assert.equal(next.z, 0);
// Already at the range, or closer: no step.
assert.equal(
issCommandZoomOffset({ x: ISS_COMMAND_ZOOM_RANGE_M, y: 0, z: 0 }),
null,
);
assert.equal(issCommandZoomOffset({ x: 0, y: 100, z: 0 }), null);
// Nothing to shorten: no follow offset yet (the follow has not framed).
assert.equal(issCommandZoomOffset(null), null);
assert.equal(issCommandZoomOffset(undefined), null);
assert.equal(issCommandZoomOffset({ x: 0, y: 0, z: 0 }), null);
});
test("the zoom needs the camera following the station's target, framed", () => {
const target = { key: 'satellites:25544' };
const on = { followed: target, followFramed: true };
assert.equal(issCommandCameraOnStation(on, target), true);
assert.equal(
issCommandCameraOnStation(
{ followed: target, followFramed: false },
target,
),
false,
'not before the follow has framed the eye',
);
assert.equal(
issCommandCameraOnStation({ followed: null, followFramed: false }, target),
false,
);
assert.equal(
issCommandCameraOnStation(
{ followed: { key: 'flights:a' }, followFramed: true },
target,
),
false,
'following something else',
);
assert.equal(issCommandCameraOnStation(null, target), false);
assert.equal(issCommandCameraOnStation(undefined, target), false);
assert.equal(issCommandCameraOnStation(on, null), false);
assert.equal(
issCommandCameraOnStation({ followed: null, followFramed: true }, null),
false,
'nothing followed and no target is not a match',
);
});
+144
View File
@@ -0,0 +1,144 @@
import { createIssArticulation } from './issArticulation.js';
import {
ISS_MOUNTS,
ISS_NAUKA_NORAD,
ISS_POISK_NORAD,
issMountView,
issMountViews,
issMountWorld,
} from './issMounts.js';
import { createIssTelemetryFeed } from './issTelemetry.js';
import {
ISS_COMPANION_COARSE_M,
ISS_COMPANION_RADIUS_M,
ISS_COMPANION_SCAN_MS,
ISS_CARD_CLEAR_M,
ISS_MODEL_LOCAL_AXES,
ISS_MODEL_MAX_DISTANCE_M,
ISS_MODEL_MIN_PX,
ISS_MODEL_NATIVE_SPAN,
ISS_MODEL_URL,
ISS_NORAD,
ISS_ORBIT_HIDE_M,
ISS_SPAN_M,
} from './policy.js';
import {
createStationModel,
stationFlightAxes,
stationModelShouldShow,
temeToEcefAxes,
} from './stationModel.js';
/** The model's scale for the real 109 m truss. */
export const ISS_MODEL_SCALE = ISS_SPAN_M / ISS_MODEL_NATIVE_SPAN;
// The station-independent rules live in stationModel.js; these names are
// kept for the code and tests written against the ISS-only model.
export { temeToEcefAxes };
export const issFlightAxes = stationFlightAxes;
/**
* Whether the ISS model may be drawn (stationModelShouldShow with the ISS's
* `hasIss` wording).
* @param {{enabled: boolean, showPoints: boolean, hasIss: boolean,
* classVisible: boolean, tracked: boolean, cockpitHidden: boolean}} input
* @returns {boolean}
*/
export function issModelShouldShow({ hasIss, ...rest }) {
return stationModelShouldShow({ hasStation: hasIss, ...rest });
}
/**
* Whether a catalog entry at the ISS is one of the station's own modules
* (Zarya, Nauka, Poisk, or any other the catalog lists as "ISS (…)") rather
* than a visiting vehicle. A missing entry counts as a module.
* @param {number} noradId
* @param {{name?: string}|undefined} entry
* @returns {boolean}
*/
export function issIsModule(noradId, entry) {
return (
noradId === ISS_NORAD ||
noradId === ISS_NAUKA_NORAD ||
noradId === ISS_POISK_NORAD ||
/^ISS\s*\(/i.test(entry?.name ?? 'ISS (')
);
}
/**
* The ISS as the station model factory describes it: NASA's model at the
* real 109 m span, its joints on the Sun or NASA's telemetry, the Cockpit's
* views from mounts on the model (so the model stays drawn in the Cockpit),
* and its orbit ring, which has rules of its own (`_syncIssOrbit`).
* @param {{parts: object}} context
* @returns {import('./stationModel.js').StationModelSpec}
*/
export function issModelSpec({ parts }) {
return {
key: 'iss',
label: 'ISS', // i18n-ignore: the station's name, for log lines
norad: ISS_NORAD,
modelUrl: ISS_MODEL_URL,
scale: ISS_MODEL_SCALE,
minPx: ISS_MODEL_MIN_PX,
maxDistanceM: ISS_MODEL_MAX_DISTANCE_M,
orbitHideM: ISS_ORBIT_HIDE_M,
cardClearM: ISS_CARD_CLEAR_M,
companionRadiusM: ISS_COMPANION_RADIUS_M,
companionCoarseM: ISS_COMPANION_COARSE_M,
companionScanMs: ISS_COMPANION_SCAN_MS,
localAxes: ISS_MODEL_LOCAL_AXES,
isModule: issIsModule,
createArticulation: createIssArticulation,
createTelemetry: createIssTelemetryFeed,
/**
* One of the views on the model (issMounts.js), in the world.
* `noradId` on the result is the catalog entry the view belongs to.
*/
cockpitMount: ({ key, centre, axes, name, entry, dockedVehicle }) => {
const views = issMountViews({
naukaName: name(ISS_NAUKA_NORAD),
zaryaName: name(ISS_NORAD),
poiskName: name(ISS_POISK_NORAD),
dockedName: name(dockedVehicle),
naukaNorad: entry(ISS_NAUKA_NORAD),
zaryaNorad: entry(ISS_NORAD),
poiskNorad: entry(ISS_POISK_NORAD),
dockedNorad: entry(dockedVehicle),
});
const view = issMountView(views, key);
return {
...issMountWorld(ISS_MOUNTS[view.key], centre, axes),
key: view.key,
label: view.label,
noradId: view.noradId,
card: view.card,
views,
};
},
// The Cockpit rides the station from a mount on the model, so the model
// stays while it does.
hideInCockpit: false,
syncOrbit: () => parts.controls._syncIssOrbit?.(),
};
}
/**
* The ISS as a 3D model when the camera is close (stationModel.js), with the
* part's methods also under their former ISS-only names.
* @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context
*/
export function createIssModel(context) {
const model = createStationModel(issModelSpec(context), context);
return {
...model,
_updateIssModel: model._updateStationModel,
_destroyIssModel: model._destroyStationModel,
_issVisualPosition: model._visualPosition,
_issCardClearPx: model._cardClearPx,
_issStandsInFor: model._standsInFor,
_issCockpitMount: model._cockpitMount,
_issTelemetryStatus: model._telemetryStatus,
_issArticulation: model._articulation,
};
}
+153
View File
@@ -0,0 +1,153 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { gstime, propagate, twoline2satrec } from 'satellite.js';
import {
ISS_MODEL_SCALE,
issFlightAxes,
issModelShouldShow,
temeToEcefAxes,
} from './issModel.js';
import {
ISS_MODEL_CENTER_NATIVE,
ISS_MODEL_LOCAL_AXES,
ISS_MODEL_NATIVE_SPAN,
ISS_MODEL_URL,
ISS_NORAD,
ISS_SPAN_M,
} from './policy.js';
const ISS_TLE = [
'1 25544U 98067A 24001.50000000 .00016717 00000-0 10270-3 0 9002',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579 1234',
];
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const norm = (a) => Math.hypot(a[0], a[1], a[2]);
const shown = {
enabled: true,
showPoints: true,
hasIss: true,
classVisible: true,
tracked: false,
cockpitHidden: false,
};
test('the ISS model shows on the same terms as its dot', () => {
assert.equal(issModelShouldShow(shown), true);
assert.equal(issModelShouldShow({ ...shown, enabled: false }), false);
assert.equal(issModelShouldShow({ ...shown, showPoints: false }), false);
assert.equal(issModelShouldShow({ ...shown, hasIss: false }), false);
assert.equal(issModelShouldShow({ ...shown, classVisible: false }), false);
});
test('a tracked ISS keeps its model with its class hidden', () => {
assert.equal(
issModelShouldShow({ ...shown, classVisible: false, tracked: true }),
true,
);
});
test('the Cockpit hold hides the model', () => {
assert.equal(
issModelShouldShow({ ...shown, tracked: true, cockpitHidden: true }),
false,
);
});
test('the model is the ISS by NORAD number, at its real 109 m span', () => {
assert.equal(ISS_NORAD, 25544);
assert.ok(
Math.abs(ISS_MODEL_SCALE * ISS_MODEL_NATIVE_SPAN - ISS_SPAN_M) < 1e-9,
);
});
test('the native span and centre match the shipped asset', () => {
const glb = readFileSync(
new URL(`../../../public${ISS_MODEL_URL}`, import.meta.url),
);
const jsonLength = glb.readUInt32LE(12);
const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8'));
const root = gltf.nodes[gltf.scenes[0].nodes[0]];
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
// Every node below the root rests untransformed (joint nodes included), so
// each mesh's bounds are already in the root's frame.
const visit = (index) => {
const node = gltf.nodes[index];
assert.equal(node.rotation ?? null, null);
assert.equal(node.scale ?? null, null);
assert.equal(node.translation ?? null, null);
for (const primitive of gltf.meshes[node.mesh]?.primitives ?? []) {
const accessor = gltf.accessors[primitive.attributes.POSITION];
for (let i = 0; i < 3; i++) {
min[i] = Math.min(min[i], accessor.min[i]);
max[i] = Math.max(max[i], accessor.max[i]);
}
}
(node.children ?? []).forEach(visit);
};
root.children.forEach(visit);
// The truss is the longest axis, glTF X.
assert.ok(Math.abs(max[0] - min[0] - ISS_MODEL_NATIVE_SPAN) < 0.01);
assert.ok(max[0] - min[0] > max[1] - min[1]);
assert.ok(max[0] - min[0] > max[2] - min[2]);
ISS_MODEL_CENTER_NATIVE.forEach((value, i) =>
assert.ok(Math.abs((min[i] + max[i]) / 2 - value) < 0.01),
);
// The scene root moves that centre to the origin: minimumPixelSize scales
// the model about its origin, so the far-range model stays centred.
assert.deepEqual(
root.translation.map((value, i) => value + ISS_MODEL_CENTER_NATIVE[i]),
[0, 0, 0],
);
// NASA's own textures ship with it.
assert.ok(gltf.textures.length > 0);
});
test('the model axes are a proper rotation of the flight axes', () => {
// A cyclic order of x, y, z keeps the frame right-handed (no mirroring).
const order = ISS_MODEL_LOCAL_AXES.join('');
assert.ok(['xyz', 'yzx', 'zxy'].includes(order));
});
test('flight axes: orthonormal, z away from the Earth, x along the motion', () => {
const satrec = twoline2satrec(ISS_TLE[0], ISS_TLE[1]);
for (const minutes of [0, 17, 46, 80]) {
const date = new Date(Date.UTC(2024, 0, 1, 12, minutes));
const { position, velocity } = propagate(satrec, date);
const gmst = gstime(date);
const r = temeToEcefAxes(position, gmst);
const v = temeToEcefAxes(velocity, gmst);
const axes = issFlightAxes(r, v);
for (const key of ['x', 'y', 'z'])
assert.ok(Math.abs(norm(axes[key]) - 1) < 1e-9);
assert.ok(Math.abs(dot(axes.x, axes.y)) < 1e-9);
assert.ok(Math.abs(dot(axes.y, axes.z)) < 1e-9);
assert.ok(Math.abs(dot(axes.x, axes.z)) < 1e-9);
const rUnit = [r.x, r.y, r.z].map((c) => c / norm([r.x, r.y, r.z]));
assert.ok(dot(axes.z, rUnit) > 0.999999);
// A near-circular orbit: the along-track axis is almost the velocity.
const vUnit = [v.x, v.y, v.z].map((c) => c / norm([v.x, v.y, v.z]));
assert.ok(dot(axes.x, vUnit) > 0.999);
// Right-handed: x × y = z.
const cross = [
axes.x[1] * axes.y[2] - axes.x[2] * axes.y[1],
axes.x[2] * axes.y[0] - axes.x[0] * axes.y[2],
axes.x[0] * axes.y[1] - axes.x[1] * axes.y[0],
];
assert.ok(dot(cross, axes.z) > 0.999999);
}
});
test('flight axes refuse a degenerate state', () => {
assert.equal(issFlightAxes({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }), null);
assert.equal(issFlightAxes({ x: 1, y: 0, z: 0 }, { x: 2, y: 0, z: 0 }), null);
});
test('TEME to Earth-fixed axes keeps the position eciToGeodetic uses', () => {
const v = temeToEcefAxes({ x: 1, y: 0, z: 0 }, Math.PI / 2);
assert.ok(Math.abs(v.x) < 1e-12);
assert.ok(Math.abs(v.y + 1) < 1e-12);
});
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more