Keep shape radii, rim gradients, depth-fail looks, sweep cadence and step camera moves out of the renderer contract

Shapes take their radii in metres; the world annotation ring follows the
camera height itself (ringRadiusAt), resizing on preRender. The radial rim
preset and depthBias go: the launch pad zone draws a canvas image fill made
by the layer. Solid and dashed lines take one depthFail look (solid or
dash) in place of depthFailColor and depthFailDash. sonarCadenceHz goes from
the quality settings: nothing set it, and the sweep moves every 80 ms.

Camera move, look, rotateAround and zoom leave the camera port: the app's pans,
in-place turns, globe turns and zooms are setView views summed over the pose
(geo/eyeMoves), and the Cesium port places a view by direction and up
exactly rather than through heading, pitch and roll. The conformance driver
runs those script steps through setView; the lookAt script turns in place
where it turned about the frame-local axis, and its reference is recorded
again.
This commit is contained in:
Sameh Khamis committed 2026-11-10 04:08:41 -08:00
1 parent 7a376ebefc
commit c8346c9fda
44 files changed
+810 -799

No files matched your search

+31 -30
View File
@@ -1806,7 +1806,7 @@ time. TRACK ACQUIRED stays first. Then:
left out (the satellites layer's bounded `getNearestPositions`, measured left out (the satellites layer's bounded `getNearestPositions`, measured
from the satellite itself), with their bearing from the top of the frame from the satellite itself), with their bearing from the top of the frame
and distance. A row (`Ride …`) rides that satellite. While there is a and distance. A row (`Ride …`) rides that satellite. While there is a
satellite ridden before this one, a RETURN · *name* row goes back to it; if satellite ridden before this one, a RETURN · _name_ row goes back to it; if
that satellite has left the catalogue it is dropped and RETURN offers the that satellite has left the catalogue it is dropped and RETURN offers the
one before. Riding stays in orbit: the satellites layer tracks the new one before. Riding stays in orbit: the satellites layer tracks the new
satellite (`trackById`), the Cockpit takes the camera back at once and satellite (`trackById`), the Cockpit takes the camera back at once and
@@ -2026,6 +2026,7 @@ video; camera poses use the existing low-confidence heading prior.
The CCTV catalog includes Taiwan national freeway cameras from the Freeway Bureau, MOTC. The app first reads the daily MOTC 2.0 CCTV.xml table with a keyless HTTPS request, a 15-second deadline, a 6 MiB response cap, and the shared 15-minute cache. If that catalog is unreachable and no last-good source list exists, the loader uses the Highway Bureau’s public provincial-road CCTV XML feed at https://cctv-maintain.thb.gov.tw/opendataCCTVs.xml. The fallback is capped by the same Taiwan source limit and hourly retry backoff; its MJPEG feeds are restricted to the eight cctv-ss01 through cctv-ss08.thb.gov.tw HTTPS servers. The frame proxy returns one bounded JPEG from each stream, not an unbounded video response. The Highway Bureau open-data page states XML downloads are free and asks users to attribute the source; the app credits Highway Bureau, MOTC. These are provincial-road cameras, not a replacement for the national freeway cameras. CCTV_TAIWAN_ENABLED=0 disables both feeds; CCTV_TAIWAN_MAX_SOURCES sets the shared cap (default 600, bounded to 1–2000), and CCTV_TAIWAN_URL overrides the Freeway Bureau table URL. The CCTV catalog includes Taiwan national freeway cameras from the Freeway Bureau, MOTC. The app first reads the daily MOTC 2.0 CCTV.xml table with a keyless HTTPS request, a 15-second deadline, a 6 MiB response cap, and the shared 15-minute cache. If that catalog is unreachable and no last-good source list exists, the loader uses the Highway Bureau’s public provincial-road CCTV XML feed at https://cctv-maintain.thb.gov.tw/opendataCCTVs.xml. The fallback is capped by the same Taiwan source limit and hourly retry backoff; its MJPEG feeds are restricted to the eight cctv-ss01 through cctv-ss08.thb.gov.tw HTTPS servers. The frame proxy returns one bounded JPEG from each stream, not an unbounded video response. The Highway Bureau open-data page states XML downloads are free and asks users to attribute the source; the app credits Highway Bureau, MOTC. These are provincial-road cameras, not a replacement for the national freeway cameras. CCTV_TAIWAN_ENABLED=0 disables both feeds; CCTV_TAIWAN_MAX_SOURCES sets the shared cap (default 600, bounded to 1–2000), and CCTV_TAIWAN_URL overrides the Freeway Bureau table URL.
Gate: src/data/cctvTaiwan.test.mjs and src/data/cctvProxy.test.mjs. Gate: src/data/cctvTaiwan.test.mjs and src/data/cctvProxy.test.mjs.
## DriveBC CCTV source pack ## DriveBC CCTV source pack
The CCTV catalog adds DriveBC highway cameras for British Columbia alongside the The CCTV catalog adds DriveBC highway cameras for British Columbia alongside the
@@ -4782,35 +4783,35 @@ nearby place—always use station selection. Unqualified “turn on/start the ra
requests use Play; a qualified Play-shaped tool call is normalized to Select so requests use Play; a qualified Play-shaped tool call is normalized to Select so
its criteria cannot be silently ignored. its criteria cannot be silently ignored.
| Layer | Source | File | Proxy | Update Interval | | Layer | Source | File | Proxy | Update Interval |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/flights` (OAuth + fallback) | 30s | | Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/flights` (OAuth + fallback) | 30s |
| Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/military` | 15s | | Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/military` | 15s |
| Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/vessels` | 60s (+800ms visibility pass) | | Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/vessels` | 60s (+800ms visibility pass) |
| Mapped Installations ⌖ | OpenFreeMap military areas; optional configured Overpass names and Google Places search | `src/data/militaryInstallations.js` | OpenFreeMap tiles, `/api/military-installations`, `/api/google/text-search` | viewport-driven; transient errors back off, missing capability switches to tiles | | Mapped Installations ⌖ | OpenFreeMap military areas; optional configured Overpass names and Google Places search | `src/data/militaryInstallations.js` | OpenFreeMap tiles, `/api/military-installations`, `/api/google/text-search` | viewport-driven; transient errors back off, missing capability switches to tiles |
| Earthquakes | USGS | `src/data/earthquakes.js` | — | 60s | | Earthquakes | USGS | `src/data/earthquakes.js` | — | 60s |
| Air quality | ECCC MSC GeoMet OGC API (AQHI, Canada only) | `src/layers/airQuality/` | — | 20 min readings, 12 h station catalog | | Air quality | ECCC MSC GeoMet OGC API (AQHI, Canada only) | `src/layers/airQuality/` | — | 20 min readings, 12 h station catalog |
| Satellites | CelesTrak TLE + SATCAT; bundled UCS pack (purpose) | `src/data/satellites.js` | `/api/celestrak` + `/api/celestrak-satcat` | 120s | | Satellites | CelesTrak TLE + SATCAT; bundled UCS pack (purpose) | `src/data/satellites.js` | `/api/celestrak` + `/api/celestrak-satcat` | 120s |
| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | | Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min |
| Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache | | Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache |
| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + King County (WA) Open Data + WSDOT (WA) Open Data + NYC DOT TMC (opt-in) + City of Toronto RESCU + Catalonia (Servei Català de Trànsit) + Iceland (Vegagerðin / IRCA) + Hong Kong Transport Department + FL511 (FL, opt-in) + Freeway Bureau, MOTC (Taiwan) + Houston TranStar (opt-in) + Autostrada del Brennero (IT, A22 stills) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | | CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + King County (WA) Open Data + WSDOT (WA) Open Data + NYC DOT TMC (opt-in) + City of Toronto RESCU + Catalonia (Servei Català de Trànsit) + Iceland (Vegagerðin / IRCA) + Hong Kong Transport Department + FL511 (FL, opt-in) + Freeway Bureau, MOTC (Taiwan) + Houston TranStar (opt-in) + Autostrada del Brennero (IT, A22 stills) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) |
| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | | Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh |
| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | | Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) |
| Bikeshare 🚲 | GBFS (Lyft + BCycle + Social Bicycles + PBSC incl. Bike Share Toronto, Bike Itaú (Brazil), Bicing (Barcelona) and seven other Spanish cities + Urban Sharing, Entur, JCDecaux (Lillestrøm, Valencia, Seville) + nextbike (AMBici)) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | | Bikeshare 🚲 | GBFS (Lyft + BCycle + Social Bicycles + PBSC incl. Bike Share Toronto, Bike Itaú (Brazil), Bicing (Barcelona) and seven other Spanish cities + Urban Sharing, Entur, JCDecaux (Lillestrøm, Valencia, Seville) + nextbike (AMBici)) | `src/data/bikeshare.js` | `/api/gbfs` | 60s |
| Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change | | Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change |
| Datacenters ▣ | OSM extract (bundled) | `src/data/infrastructure.js` | — | static | | Datacenters ▣ | OSM extract (bundled) | `src/data/infrastructure.js` | — | static |
| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/infrastructure.js` | — | static | | Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/infrastructure.js` | — | static |
| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static | | Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static |
| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×2 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | | FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×2 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) |
| Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) | | Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) |
| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | | Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) |
| GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) | | GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) |
| S2 GhostMaps 👻 (`s2-ghostmaps`) | S2 Underground's public GhostMaps repository on GitHub (KMZ intel products, keyless, CC BY-NC-SA 4.0) | `src/layers/ghostMaps/` via `src/app/layers/ghostMaps.js` | `/api/ghostmaps/catalog`, `/api/ghostmaps/events` (server-sent events), `/api/ghostmaps/file/{product}` | branch head checked every 15 s; new commits pushed to the page; 5 min catalog backstop | | S2 GhostMaps 👻 (`s2-ghostmaps`) | S2 Underground's public GhostMaps repository on GitHub (KMZ intel products, keyless, CC BY-NC-SA 4.0) | `src/layers/ghostMaps/` via `src/app/layers/ghostMaps.js` | `/api/ghostmaps/catalog`, `/api/ghostmaps/events` (server-sent events), `/api/ghostmaps/file/{product}` | branch head checked every 15 s; new commits pushed to the page; 5 min catalog backstop |
| Sea Marks ⚓ (`sea-marks`) | OpenSeaMap seamark raster tiles (keyless; CC BY-SA 2.0 tiles, OSM data ODbL) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | | Sea Marks ⚓ (`sea-marks`) | OpenSeaMap seamark raster tiles (keyless; CC BY-SA 2.0 tiles, OSM data ODbL) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) |
| Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | | Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) |
| Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) | | Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) |
| Prohibited & Restricted Airspace 🚫 | FAA Special Use Airspace prohibited (P) and restricted (R) zones (keyless FeatureServer, simplified geometry) | `src/layers/droneAirspace/` via `src/app/layers/droneAirspace.js` | `/api/drone-airspace` | 1 h (server cache 1 h; stale-on-error) | | Prohibited & Restricted Airspace 🚫 | FAA Special Use Airspace prohibited (P) and restricted (R) zones (keyless FeatureServer, simplified geometry) | `src/layers/droneAirspace/` via `src/app/layers/droneAirspace.js` | `/api/drone-airspace` | 1 h (server cache 1 h; stale-on-error) |
| Wildlife Sightings 🦉 | iNaturalist wildlife observed within 48 h (whales 7 d), per view; Acartia Salish Sea marine mammal coverage (keyless) | `src/layers/wildlifeSightings/` via `src/app/layers/wildlifeSightings.js` | `/api/inaturalist/observations`, `/api/inaturalist/grid`, `/api/acartia/sightings` | camera moveEnd (600 ms debounce; enable settles 300 ms) + 5 min (observations 5 / 10 min; tiles 15 min; stale ≤ 1 h / 24 h) | | Wildlife Sightings 🦉 | iNaturalist wildlife observed within 48 h (whales 7 d), per view; Acartia Salish Sea marine mammal coverage (keyless) | `src/layers/wildlifeSightings/` via `src/app/layers/wildlifeSightings.js` | `/api/inaturalist/observations`, `/api/inaturalist/grid`, `/api/acartia/sightings` | camera moveEnd (600 ms debounce; enable settles 300 ms) + 5 min (observations 5 / 10 min; tiles 15 min; stale ≤ 1 h / 24 h) |
GNSS Integrity samples a 250 nm circle around the Earth point under the screen GNSS Integrity samples a 250 nm circle around the Earth point under the screen
centre. Camera reads debounce for 600 ms with a monotonic 2.5 s minimum gap; centre. Camera reads debounce for 600 ms with a monotonic 2.5 s minimum gap;
@@ -6461,7 +6462,7 @@ request viewbox and continues searching without that geographic preference.
- UTILITIES ▸ **Draw** turns the globe into a whiteboard drawn by hand. Pick a shape (icon buttons for Area, Line and Pin) and a colour swatch for the next shape, click the vertices on the real world, and finish. **Keyboard contract, live only while Draw is on and never while you are typing in another field:** Enter finishes the shape (as does a double-click, and the two cannot both submit it — the session is replaced before the annotate call is awaited); Backspace removes the last vertex; Esc cancels the shape in progress, and a second Esc — Esc on an empty session — leaves draw mode. **Clear** wipes the board (the shape in progress and every placed mark), so removing marks does not require the console or the microphone. - UTILITIES ▸ **Draw** turns the globe into a whiteboard drawn by hand. Pick a shape (icon buttons for Area, Line and Pin) and a colour swatch for the next shape, click the vertices on the real world, and finish. **Keyboard contract, live only while Draw is on and never while you are typing in another field:** Enter finishes the shape (as does a double-click, and the two cannot both submit it — the session is replaced before the annotate call is awaited); Backspace removes the last vertex; Esc cancels the shape in progress, and a second Esc — Esc on an empty session — leaves draw mode. **Clear** wipes the board (the shape in progress and every placed mark), so removing marks does not require the console or the microphone.
- **Drawn shapes are listed under Draw like Import's files** (`src/ui/views/panels/DrawMarkList.vue`, rows worded by `presentDrawMarks` in `src/annotations/drawMarks.js`): one row per hand-drawn mark (`manual: true`; voice marks are not listed) with its colour swatch, its name, and show/hide, fly-to and remove. The draw tool publishes the rows with the rest of its controls and answers the row actions (`renameDrawMark`, `recolorDrawMark`, `toggleDrawMark`, `flyToDrawMark`, `removeDrawMark`) through the display store; it republishes on the engine's `onChange`, so a voice clear or an expiry updates the list. Rows are keyed and updated in place: a board change never takes a name being typed (the field keeps its draft while focused) or the button under a click. The name is saved on Enter or on leaving the field, once; Esc restores it, before anything else and with the row's colours open too. Both keep focus in the field, so neither drops it to the page or leaves Draw. The swatch opens the five colours right after it (shown at the end of the row), with the current colour focused; the arrows, Home and End try another, and a click or Esc closes them and returns focus to the swatch. Both colour groups (the next shape's and a row's) are one `DrawSwatches` radio group with a single tab stop, coloured from `DRAW_COLOR_CSS`; on touch screens each dot answers a 24 px target. An unnamed shape shows its kind, and an unnamed line its length; a renamed line keeps its length (`Ridge walk — 950 m`). **Hidden** keeps a mark on the board at alpha 0, and the world renderer takes every one of its entities out (`show = false`), so no material that keeps its own colour (the line's flowing stroke) still paints it; the screen renderer does not project a hidden callout, so it cannot push a visible label aside; `fly_route` skips a hidden route; and with every mark hidden the annotations render hold is released. **Fly to** is an immediate navigation (`runImmediateNavigation('drawing', …)`), like Import's: Cockpit refuses it and a running orbit, follow or track lets go first. A line is framed by its whole path, across the antimeridian too. - **Drawn shapes are listed under Draw like Import's files** (`src/ui/views/panels/DrawMarkList.vue`, rows worded by `presentDrawMarks` in `src/annotations/drawMarks.js`): one row per hand-drawn mark (`manual: true`; voice marks are not listed) with its colour swatch, its name, and show/hide, fly-to and remove. The draw tool publishes the rows with the rest of its controls and answers the row actions (`renameDrawMark`, `recolorDrawMark`, `toggleDrawMark`, `flyToDrawMark`, `removeDrawMark`) through the display store; it republishes on the engine's `onChange`, so a voice clear or an expiry updates the list. Rows are keyed and updated in place: a board change never takes a name being typed (the field keeps its draft while focused) or the button under a click. The name is saved on Enter or on leaving the field, once; Esc restores it, before anything else and with the row's colours open too. Both keep focus in the field, so neither drops it to the page or leaves Draw. The swatch opens the five colours right after it (shown at the end of the row), with the current colour focused; the arrows, Home and End try another, and a click or Esc closes them and returns focus to the swatch. Both colour groups (the next shape's and a row's) are one `DrawSwatches` radio group with a single tab stop, coloured from `DRAW_COLOR_CSS`; on touch screens each dot answers a 24 px target. An unnamed shape shows its kind, and an unnamed line its length; a renamed line keeps its length (`Ridge walk — 950 m`). **Hidden** keeps a mark on the board at alpha 0, and the world renderer takes every one of its entities out (`show = false`), so no material that keeps its own colour (the line's flowing stroke) still paints it; the screen renderer does not project a hidden callout, so it cannot push a visible label aside; `fly_route` skips a hidden route; and with every mark hidden the annotations render hold is released. **Fly to** is an immediate navigation (`runImmediateNavigation('drawing', …)`), like Import's: Cockpit refuses it and a running orbit, follow or track lets go first. A line is framed by its whole path, across the antimeridian too.
- Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the pointer subscriptions, the preview draw sets, the borrowed click actions and the `window.__gevDrawTool` handle. The live preview (a dashed rubber band, dashed behind the surface too through the line's `depthFailDash`, and a dot per vertex) is two sets on the renderer's draw port, so the tool no longer reaches Cesium; the rubber band follows each move's `pickPosition`, the dispatcher's sensor-corrected pick-buffer point, as clicks do. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam. - Runtime entry: `createApplicationTools` (`src/app/tools.js`, behind the `src/standalone/tools.js` shim) calls `initDrawTool({ viewer, annotations, navigation, publish, connect, markActions })` after `initAnnotations` and defers its `destroy()`, so disposing the shell returns every DOM listener, the pointer subscriptions, the preview draw sets, the borrowed click actions and the `window.__gevDrawTool` handle. The live preview (a dashed rubber band, dashed behind the surface too through the line's `depthFail` style, and a dot per vertex) is two sets on the renderer's draw port, so the tool no longer reaches Cesium; the rubber band follows each move's `pickPosition`, the dispatcher's sensor-corrected pick-buffer point, as clicks do. Its controls are Vue views in the UTILITIES panel (`DrawControls.vue`, `DrawMarkList.vue`) that render what the tool publishes to the display store and call its actions. That handle (`setActive`, `setShape`, `addVertex(lon, lat)`, `finish`, `cancel`, `clearAll`, `marks`, `setColor`, `diagnostics`) is the no-mouse test seam.
- **The pointer, for an application's own tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner)` takes the pointer as Draw does and returns its lease, or `null` while another tool holds it; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. An owner without a name in `pointerOwnerNames.js` is named by its id when another tool reports who holds the pointer. - **The pointer, for an application's own tool.** `createApplicationTools` also returns `pointer` (`data/inputOwnership.js`): `claim(owner)` takes the pointer as Draw does and returns its lease, or `null` while another tool holds it; `release(lease)` gives it back; `isFree()` lets the application's own click handlers yield, as the layers' do. An owner without a name in `pointerOwnerNames.js` is named by its id when another tool reports who holds the pointer.
- **Row actions are an application's own.** `createApplicationTools({ drawMarkActions })` hands `initDrawTool` buttons for drawn areas' and lines' rows; the standalone shell passes none, so the open-source build shows no new button and makes no new request. Each action (`drawMarkActions` in `src/annotations/drawMarks.js`) is `{ id, icon, label(name), shapes: ['area', 'line'], accepts?(geometry, shape), run({ id, shape, name, title, geometry }) }`: the icon a Material Symbols name, the label worded by the application, `name` the person's own and `title` the row's (the name, else `Area` or `Line · 950 m`), the geometry `drawMarkGeometry`'s `[lon, lat]` `Polygon` (closed; a `MultiPolygon` for an area handle with several parts) or `LineString`, longitudes wrapped into [-180, 180]. A pin, and a shape that crosses the antimeridian or has a part that cannot be given whole, has no geometry and is offered nothing. Malformed actions and repeated ids are dropped once, at construction. What `run` returns or resolves to is a note under the row (`role=status`; past 200 characters it is cut at a word with an ellipsis); the row is busy (`aria-disabled`, no second press) until it settles, a rejection or a throw clears the note and is logged (so an action words its own refusals and resolves with them), and a shape's note goes with the shape, so a late answer never lands on a removed one. - **Row actions are an application's own.** `createApplicationTools({ drawMarkActions })` hands `initDrawTool` buttons for drawn areas' and lines' rows; the standalone shell passes none, so the open-source build shows no new button and makes no new request. Each action (`drawMarkActions` in `src/annotations/drawMarks.js`) is `{ id, icon, label(name), shapes: ['area', 'line'], accepts?(geometry, shape), run({ id, shape, name, title, geometry }) }`: the icon a Material Symbols name, the label worded by the application, `name` the person's own and `title` the row's (the name, else `Area` or `Line · 950 m`), the geometry `drawMarkGeometry`'s `[lon, lat]` `Polygon` (closed; a `MultiPolygon` for an area handle with several parts) or `LineString`, longitudes wrapped into [-180, 180]. A pin, and a shape that crosses the antimeridian or has a part that cannot be given whole, has no geometry and is offered nothing. Malformed actions and repeated ids are dropped once, at construction. What `run` returns or resolves to is a note under the row (`role=status`; past 200 characters it is cut at a word with an ellipsis); the row is busy (`aria-disabled`, no second press) until it settles, a rejection or a throw clears the note and is logged (so an action words its own refusals and resolves with them), and a shape's note goes with the shape, so a late answer never lands on a removed one.
- Contract: a finished shape is submitted through the SAME `annotationEngine.annotate()` the voice agent uses, with geometry supplied and `manual: true` (`type: area` + `ring`, `type: route` + `path`, `type: pin` + coordinates). `resolveSpec` short-circuits manual specs (`resolveManualSpec`) so no geocoder, Places or Overpass call is made. A drawn area is a real (not synthesized) outline and drapes solid; a drawn line is a `route` with `mode: 'manual'`, labelled with its length and never a travel time; a pin is a point. Drawn marks therefore render with the whiteboard look, persist, appear in `.list()`, and clear with `clear_annotations` / `.clear()`. A drawn shape is never merged with another as a duplicate: every one is drawn on purpose, and every one is unnamed until its row names it, so two pins dropped close together are two pins. - Contract: a finished shape is submitted through the SAME `annotationEngine.annotate()` the voice agent uses, with geometry supplied and `manual: true` (`type: area` + `ring`, `type: route` + `path`, `type: pin` + coordinates). `resolveSpec` short-circuits manual specs (`resolveManualSpec`) so no geocoder, Places or Overpass call is made. A drawn area is a real (not synthesized) outline and drapes solid; a drawn line is a `route` with `mode: 'manual'`, labelled with its length and never a travel time; a pin is a point. Drawn marks therefore render with the whiteboard look, persist, appear in `.list()`, and clear with `clear_annotations` / `.clear()`. A drawn shape is never merged with another as a duplicate: every one is drawn on purpose, and every one is unnamed until its row names it, so two pins dropped close together are two pins.
+7 -5
View File
@@ -78,9 +78,9 @@ optional, so a renderer written before it still conforms:
- `camera.on('changed', cb, { threshold })` measures each listener by its - `camera.on('changed', cb, { threshold })` measures each listener by its
own threshold under the capability `cameraChangeThreshold`; a renderer own threshold under the capability `cameraChangeThreshold`; a renderer
without it fires every `changed` listener at 0.5. without it fires every `changed` listener at 0.5.
- A line item's `depthFailDash` (`{ length, pattern16? }`) dashes the parts - A line item's `depthFail` style, solid or dashed, draws the parts behind
behind the surface in `depthFailColor`, as the Draw tool's rubber band is. the surface (the Draw tool's rubber band is dashed there too); without one
A renderer that predates it draws those parts solid. they are hidden.
- A shape's `lit` chooses shading by the renderer's fixed light (true) or a - A shape's `lit` chooses shading by the renderer's fixed light (true) or a
flat colour (false); omitted, extruded shapes and boxes are lit and the flat colour (false); omitted, extruded shapes and boxes are lit and the
rest flat, as before. The Cesium port lights unclamped shapes only rest flat, as before. The Cesium port lights unclamped shapes only
@@ -98,8 +98,10 @@ optional, so a renderer written before it still conforms:
The Cesium port also draws `pattern` line styles (the image repeated The Cesium port also draws `pattern` line styles (the image repeated
`repeat` times along the line, in the translucent pass), lines in the `repeat` times along the line, in the translucent pass), lines in the
`inertial` frame (turned each frame by the set's motion clock; never draped `inertial` frame (turned each frame by the set's motion clock; never draped
and never batched), and `radialRim` fills on clamped ellipses (`rimWidth` a and never batched), and image fills on clamped ellipses, cut finely so a
fraction of the radius; `depthBias` pulls the fill toward the eye). A hidden round image (the launch pad zone's rim) runs round. A clamped colour fill
whose geometry alone changes (an annotation's target ring, resized as the
camera climbs) is drawn alone where it now is, in the same frame. A hidden
line that cannot settle into a static batch leaves its polyline collection line that cannot settle into a static batch leaves its polyline collection
until it shows again, since the collection draws every line it holds. until it shows again, since the collection draws every line it holds.
+3
View File
@@ -3414,6 +3414,7 @@
"src/geo/vector.js", "src/geo/vector.js",
"src/geo/ellipsoid.js", "src/geo/ellipsoid.js",
"src/geo/frames.js", "src/geo/frames.js",
"src/geo/eyeMoves.js",
"src/geo/celestial.js", "src/geo/celestial.js",
"src/geo/quaternion.js", "src/geo/quaternion.js",
"src/layers/flights/icons.js", "src/layers/flights/icons.js",
@@ -4994,6 +4995,7 @@
"src/geo/vector.js", "src/geo/vector.js",
"src/geo/ellipsoid.js", "src/geo/ellipsoid.js",
"src/geo/frames.js", "src/geo/frames.js",
"src/geo/eyeMoves.js",
"src/geo/celestial.js", "src/geo/celestial.js",
"src/geo/quaternion.js", "src/geo/quaternion.js",
"src/layers/flights/records.js", "src/layers/flights/records.js",
@@ -6900,6 +6902,7 @@
"src/geo/vector.js", "src/geo/vector.js",
"src/geo/ellipsoid.js", "src/geo/ellipsoid.js",
"src/geo/frames.js", "src/geo/frames.js",
"src/geo/eyeMoves.js",
"src/geo/celestial.js", "src/geo/celestial.js",
"src/geo/quaternion.js", "src/geo/quaternion.js",
"src/render/stub/camera.js", "src/render/stub/camera.js",
+5 -2
View File
@@ -217,8 +217,11 @@ export function initDrawTool({
length: 16, length: 16,
}, },
// Dashed behind the surface too, as the band in front of it is. // Dashed behind the surface too, as the band in front of it is.
depthFailColor: withAlpha(cssColor(PREVIEW.primary), 0.35), depthFail: {
depthFailDash: { length: 16 }, kind: 'dash',
color: withAlpha(cssColor(PREVIEW.primary), 0.35),
length: 16,
},
}, },
]); ]);
}; };
+3 -4
View File
@@ -503,11 +503,10 @@ test('the rubber band follows the pointer, closes an area and takes the chosen c
'the band takes the colour', 'the band takes the colour',
); );
assert.deepEqual( assert.deepEqual(
band().depthFailColor, band().depthFail,
[139 / 255, 233 / 255, 1, 0.35], { kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 },
'behind the surface it stays the primary colour, as before', 'behind the surface it stays the primary colour, dashed, as before',
); );
assert.deepEqual(band().depthFailDash, { length: 16 }, 'and dashed there');
assert.equal(band().style.kind, 'dash'); assert.equal(band().style.kind, 'dash');
assert.equal(band().style.length, 16); assert.equal(band().style.length, 16);
assert.equal(band().widthPx, 3); assert.equal(band().widthPx, 3);
+109 -16
View File
@@ -2,7 +2,12 @@ import { recordWorkSlice } from '../sources/phaseTiming.js';
import { ringCentroid } from '../sources/featureGeometry.js'; import { ringCentroid } from '../sources/featureGeometry.js';
import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
import { fromDegrees } from '../geo/ellipsoid.js'; import { fromDegrees } from '../geo/ellipsoid.js';
import { drawOf, frameOf } from '../render/rendererOf.js'; import {
drawOf,
findCamera,
findFrame,
frameOf,
} from '../render/rendererOf.js';
import { heightsOf } from '../queries/heights.js'; import { heightsOf } from '../queries/heights.js';
/** /**
@@ -22,7 +27,8 @@ import { heightsOf } from '../queries/heights.js';
* Fades follow the mark's alpha: the engine calls `sync` as it changes, and * Fades follow the mark's alpha: the engine calls `sync` as it changes, and
* each mark's items take their new colours where they are. Pulsing fills * each mark's items take their new colours where they are. Pulsing fills
* are a declarative pulse the renderer runs; target rings follow the * are a declarative pulse the renderer runs; target rings follow the
* camera's height, which the renderer reads each frame. * camera's height, read before each frame, and are sent again at the radius
* it gives when that changes.
* *
* Each mark draws into sets of its own, so adding or removing one leaves * Each mark draws into sets of its own, so adding or removing one leaves
* the others' geometry alone. * the others' geometry alone.
@@ -57,9 +63,23 @@ const PULSE_MS = (2 * Math.PI) / 0.005;
const PULSE_LOW = 0.6; const PULSE_LOW = 0.6;
/** Target rings: 3% of the camera's height, between 14 m and 170 m. */ /** Target rings: 3% of the camera's height, between 14 m and 170 m. */
const RING_RADIUS = Object.freeze({ const RING_RADIUS = Object.freeze({ factor: 0.03, min: 14, max: 170 });
byCameraHeight: Object.freeze({ factor: 0.03, min: 14, max: 170 }),
}); /** Relative change of the ring radius under which rings are not redrawn. */
const RING_RESIZE = 1e-3;
/**
* A target ring's radius, metres, for a camera `height` metres above the
* ellipsoid; 1000 m stands in for a height the camera cannot give.
* @param {number} height
*/
export function ringRadiusAt(height) {
const h = Number.isFinite(height) ? height : 1000;
return Math.max(
RING_RADIUS.min,
Math.min(RING_RADIUS.max, h * RING_RADIUS.factor),
);
}
/** /**
* Each renderer's sets have ids of their own, unique across copies of this * Each renderer's sets have ids of their own, unique across copies of this
@@ -79,6 +99,56 @@ export function createWorldAnnotationRenderer(viewer) {
const groundQueue = []; const groundQueue = [];
let offGroundFrame = null; let offGroundFrame = null;
let destroyed = false; let destroyed = false;
// Marks with a target ring, and the radius they are drawn at.
const ringed = new Set();
let offRingFrame = null;
let ringRadius = ringRadiusAt(cameraHeight());
/** The camera's height above the ellipsoid, or NaN when it has none. */
function cameraHeight() {
try {
return findCamera(viewer)?.pose().height ?? Number.NaN;
} catch {
return Number.NaN;
}
}
/** The current ring radius, for the items that draw rings. */
const ringRadiusNow = () => ringRadius;
/**
* Before each frame: when the camera's height gives the rings another
* radius, every shown mark's ring is sent again at it. A hidden mark's
* ring catches up when it shows (`sync`).
*/
function followRings() {
const radius = ringRadiusAt(cameraHeight());
if (Math.abs(radius - ringRadius) <= RING_RESIZE * ringRadius) return;
ringRadius = radius;
for (const anno of ringed) if (!anno.hidden) resizeRing(anno);
}
/** Send a mark's ring again at the current radius, when it differs. */
function resizeRing(anno) {
const was = anno._drawn;
const set = anno._draw?.shapes;
if (!was?.ring || !set || was.ringRadius === ringRadius) return;
was.ringRadius = ringRadius;
set.upsert([was.ring(was.alpha)]);
}
/**
* Keep the ring frame listener while any mark has a ring. A host with no
* frame port draws its rings at the radius they were added with.
*/
function watchRings() {
if (ringed.size && !offRingFrame)
offRingFrame = findFrame(viewer)?.on('preRender', followRings) ?? null;
else if (!ringed.size && offRingFrame) {
offRingFrame();
offRingFrame = null;
}
}
const requestRender = () => frameOf(viewer).requestRender('annotations'); const requestRender = () => frameOf(viewer).requestRender('annotations');
@@ -338,8 +408,18 @@ export function createWorldAnnotationRenderer(viewer) {
return sampleBuilding(anno, options); return sampleBuilding(anno, options);
} }
const items = itemsOf(anno, options); // Rings not yet followed take the camera's height now.
anno._drawn = { alpha: alphaOf(anno), items }; if (!offRingFrame) ringRadius = ringRadiusAt(cameraHeight());
const items = itemsOf(anno, options, ringRadiusNow);
anno._drawn = {
alpha: alphaOf(anno),
items,
ring: items.ring,
ringRadius,
};
if (items.ring) ringed.add(anno);
else ringed.delete(anno);
watchRings();
const current = () => options.isCurrent?.() ?? true; const current = () => options.isCurrent?.() ?? true;
const building = anno.footprintKind === 'building'; const building = anno.footprintKind === 'building';
for (const kind of ['shapes', 'lines', 'points']) { for (const kind of ['shapes', 'lines', 'points']) {
@@ -394,6 +474,8 @@ export function createWorldAnnotationRenderer(viewer) {
hideOsmCredit(viewer, anno); hideOsmCredit(viewer, anno);
osmAnnotations.delete(anno); osmAnnotations.delete(anno);
drawn.delete(anno); drawn.delete(anno);
ringed.delete(anno);
watchRings();
clearSets(anno); clearSets(anno);
if (anno) { if (anno) {
anno._draw = null; anno._draw = null;
@@ -415,8 +497,13 @@ export function createWorldAnnotationRenderer(viewer) {
if (sets[kind] && sets[kind].show !== show) sets[kind].show = show; if (sets[kind] && sets[kind].show !== show) sets[kind].show = show;
const was = anno._drawn; const was = anno._drawn;
const alpha = alphaOf(anno); const alpha = alphaOf(anno);
if (!was || was.alpha === alpha) continue; if (!was || was.alpha === alpha) {
// Shown again: its ring catches up with the camera.
if (show) resizeRing(anno);
continue;
}
was.alpha = alpha; was.alpha = alpha;
was.ringRadius = ringRadius;
for (const kind of ['shapes', 'lines', 'points']) for (const kind of ['shapes', 'lines', 'points'])
if (sets[kind] && was.items[kind].length) if (sets[kind] && was.items[kind].length)
sets[kind].upsert(was.items[kind].map((item) => item(alpha))); sets[kind].upsert(was.items[kind].map((item) => item(alpha)));
@@ -428,6 +515,8 @@ export function createWorldAnnotationRenderer(viewer) {
for (const task of [...pendingGround.values()]) task.finish('cancelled'); for (const task of [...pendingGround.values()]) task.finish('cancelled');
for (const anno of osmAnnotations) hideOsmCredit(viewer, anno); for (const anno of osmAnnotations) hideOsmCredit(viewer, anno);
osmAnnotations.clear(); osmAnnotations.clear();
ringed.clear();
watchRings();
for (const anno of drawn) { for (const anno of drawn) {
clearSets(anno); clearSets(anno);
anno._draw = null; anno._draw = null;
@@ -455,14 +544,16 @@ const pulse = (alpha) => ({
/** /**
* What a mark draws, as item makers by kind, each taking the mark's alpha: * What a mark draws, as item makers by kind, each taking the mark's alpha:
* built once per add, called again on each fade step. * built once per add, called again on each fade step. `ring` is the target
* ring's maker among the shapes, drawn at `ringRadiusNow()`.
*/ */
function itemsOf(anno, options) { function itemsOf(anno, options, ringRadiusNow) {
const base = PALETTE[anno.color] || PALETTE.primary; const base = PALETTE[anno.color] || PALETTE.primary;
const shapes = []; const shapes = [];
const lines = []; const lines = [];
const points = []; const points = [];
const meta = { annotation: anno.id }; const meta = { annotation: anno.id };
let ring = null;
const draped = (id, positions, widthPx, style) => (alpha) => ({ const draped = (id, positions, widthPx, style) => (alpha) => ({
id, id,
positions, positions,
@@ -612,21 +703,23 @@ function itemsOf(anno, options) {
} else { } else {
// pin / highlight / label — a camera-proportional target ring + a marker. // pin / highlight / label — a camera-proportional target ring + a marker.
const pos = { lon: anno.anchor.lon, lat: anno.anchor.lat }; const pos = { lon: anno.anchor.lon, lat: anno.anchor.lat };
if (anno.type !== 'label') if (anno.type !== 'label') {
shapes.push((alpha) => ({ ring = (alpha) => ({
id: 'ring', id: 'ring',
geometry: { geometry: {
kind: 'ellipse', kind: 'ellipse',
center: pos, center: pos,
semiMajor: RING_RADIUS, semiMajor: ringRadiusNow(),
semiMinor: RING_RADIUS, semiMinor: ringRadiusNow(),
}, },
fill: colour(base, 0.38 * alpha), fill: colour(base, 0.38 * alpha),
animate: pulse(0.38 * alpha), animate: pulse(0.38 * alpha),
height: 'clampGround', height: 'clampGround',
clampTo: CLAMP_TO, clampTo: CLAMP_TO,
meta, meta,
})); });
shapes.push(ring);
}
// Captions belong to the hybrid renderer's screen-space callouts. // Captions belong to the hybrid renderer's screen-space callouts.
points.push((alpha) => ({ points.push((alpha) => ({
id: 'marker', id: 'marker',
@@ -640,7 +733,7 @@ function itemsOf(anno, options) {
meta, meta,
})); }));
} }
return { shapes, lines, points }; return { shapes, lines, points, ring };
} }
/** `[lon, lat]` pairs as ECEF positions on the ellipsoid. */ /** `[lon, lat]` pairs as ECEF positions on the ellipsoid. */
@@ -8,29 +8,40 @@ import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js'; import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js';
/** A viewer with a fake draw port, frame and query bound. */ /**
* A viewer with a fake draw port, frame, camera and query bound. The camera
* stands at `camera.height`; `preRender()` runs the frame's preRender
* listeners, `emit()` its postRender ones.
*/
function viewer(t, { heights = () => null } = {}) { function viewer(t, { heights = () => null } = {}) {
const draw = fakeDrawPort(); const draw = fakeDrawPort();
const frames = new Set(); const frames = new Set();
const before = new Set();
const v = { requests: 0 }; const v = { requests: 0 };
const frame = { const frame = {
on(phase, cb) { on(phase, cb) {
if (phase !== 'postRender') return () => {}; const listeners =
frames.add(cb); phase === 'postRender' ? frames : phase === 'preRender' ? before : null;
return () => frames.delete(cb); if (!listeners) return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
}, },
requestRender() { requestRender() {
v.requests += 1; v.requests += 1;
}, },
}; };
const camera = { height: 2000, pose: () => ({ height: camera.height }) };
const query = { sampleHeightNow: (point) => heights(point) }; const query = { sampleHeightNow: (point) => heights(point) };
const unbind = bindRenderer(v, { draw, frame, query }); const unbind = bindRenderer(v, { draw, frame, query, camera });
t.after(unbind); t.after(unbind);
return { return {
v, v,
draw, draw,
frames, frames,
before,
camera,
emit: () => [...frames].forEach((cb) => cb()), emit: () => [...frames].forEach((cb) => cb()),
preRender: () => [...before].forEach((cb) => cb()),
}; };
} }
@@ -213,9 +224,7 @@ test('every kind draws as it did: draped on terrain and tiles alike, rings by ca
); );
const [ring] = items(pin, 'shapes'); const [ring] = items(pin, 'shapes');
assert.deepEqual(ring.geometry.semiMajor, { assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height');
byCameraHeight: { factor: 0.03, min: 14, max: 170 },
});
assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor); assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor);
const [marker] = items(pin, 'points'); const [marker] = items(pin, 'points');
assert.deepEqual( assert.deepEqual(
@@ -232,6 +241,67 @@ test('every kind draws as it did: draped on terrain and tiles alike, rings by ca
renderer.destroy(); renderer.destroy();
}); });
test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => {
const { v, draw, camera, preRender, before } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [, , pin] = marks();
const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } };
renderer.add(pin);
renderer.add(other);
const ringOf = (anno) =>
setsOf(draw, anno)
.find((r) => r.kind === 'shapes')
.items.get('ring');
// Writes to the rings' sets since they were drawn.
const shapeSets = [pin, other].map((anno) =>
setsOf(draw, anno).find((r) => r.kind === 'shapes'),
);
const upserts = {
get length() {
return shapeSets.reduce((n, record) => n + record.writes - 1, 0);
},
};
assert.equal(ringOf(pin).geometry.semiMajor, 60);
assert.equal(before.size, 1, 'one listener for every ring');
// The camera has not moved: nothing is sent.
preRender();
assert.equal(upserts.length, 0);
// It climbs: both rings are sent at the new radius, once.
camera.height = 4000;
preRender();
preRender();
assert.equal(upserts.length, 2);
assert.equal(ringOf(pin).geometry.semiMajor, 120);
assert.equal(ringOf(pin).geometry.semiMinor, 120);
assert.equal(ringOf(other).geometry.semiMajor, 120);
// A change under 0.1% sends nothing.
camera.height = 4002;
preRender();
assert.equal(upserts.length, 2);
// Held within 14 m and 170 m.
camera.height = 1e6;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 170);
camera.height = 10;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 14);
// A hidden mark waits, and catches up when shown.
other.hidden = true;
renderer.sync();
camera.height = 3000;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 90);
assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent');
other.hidden = false;
renderer.sync();
assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up');
// The last ring gone, the listener goes with it.
renderer.remove(pin);
renderer.remove(other);
assert.equal(before.size, 0);
renderer.destroy();
});
test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => { test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => {
const { v, draw, emit, frames } = viewer(t, { heights: () => 150 }); const { v, draw, emit, frames } = viewer(t, { heights: () => 150 });
const renderer = createWorldAnnotationRenderer(v); const renderer = createWorldAnnotationRenderer(v);
+6 -3
View File
@@ -67,6 +67,7 @@ import {
toRadians, toRadians,
vec, vec,
} from './geo/index.js'; } from './geo/index.js';
import { eyeMoved, eyeRotatedAbout, eyeTurned } from './geo/eyeMoves.js';
import { heightsOf } from './queries/heights.js'; import { heightsOf } from './queries/heights.js';
import { import {
cameraOf, cameraOf,
@@ -1083,7 +1084,7 @@ function lookWithinFrame(camera, m, look, angle) {
if (allowed < owed) allowed = owed; if (allowed < owed) allowed = owed;
m.turnedRad += allowed; m.turnedRad += allowed;
} }
if (allowed > 0) camera.look(look, allowed); if (allowed > 0) camera.setView(eyeTurned(camera.pose(), look, allowed));
// The pose this turn leaves, for a turn that continues from it. // The pose this turn leaves, for a turn that continues from it.
if (_lookBaseline) _lookBaseline.direction = camera.pose().direction; if (_lookBaseline) _lookBaseline.direction = camera.pose().direction;
if (allowed < angle) interruptCameraMotion('globe-out-of-frame'); if (allowed < angle) interruptCameraMotion('globe-out-of-frame');
@@ -1343,7 +1344,9 @@ function onTick() {
? heightM * ONCE.panViewFraction * (scale - (m.lastScale || 0)) ? heightM * ONCE.panViewFraction * (scale - (m.lastScale || 0))
: heightM * PAN_VIEW_FRACTION_S[m.speed] * dt; : heightM * PAN_VIEW_FRACTION_S[m.speed] * dt;
m.lastScale = scale; m.lastScale = scale;
camera.move(PAN_MOVES[m.direction] ?? 'down', step); camera.setView(
eyeMoved(camera.pose(), PAN_MOVES[m.direction] ?? 'down', step),
);
} else if (m.kind === 'tilt') { } else if (m.kind === 'tilt') {
tickTilt(camera, m, scale, dt); tickTilt(camera, m, scale, dt);
} else if (m.kind === 'rotate' || m.kind === 'rotate_globe') { } else if (m.kind === 'rotate' || m.kind === 'rotate_globe') {
@@ -1377,7 +1380,7 @@ function onTick() {
interruptCameraMotion('globe-surface-limit'); interruptCameraMotion('globe-surface-limit');
return; return;
} }
camera.rotateAround(m.rotationAxis, angle); camera.setView(eyeRotatedAbout(pose, m.rotationAxis, angle));
} else { } else {
lookWithinFrame( lookWithinFrame(
camera, camera,
+7 -19
View File
@@ -6,8 +6,8 @@
* Each tick, before the renderer decides whether to draw: a change of the * Each tick, before the renderer decides whether to draw: a change of the
* theme, the sweep, its settings or the map's size sets the sector at once; * theme, the sweep, its settings or the map's size sets the sector at once;
* while sweeping, the sector moves to the current angle on every tick that * while sweeping, the sector moves to the current angle on every tick that
* draws anyway, and at least at the renderer's `sonarCadenceHz` (which then * draws anyway, and at least every `CYBER_SONAR_RENDER_INTERVAL_MS` (which
* asks for a frame). Out of the theme the sector is cleared. * then asks for a frame). Out of the theme the sector is cleared.
* *
* A renderer without the capability, or one that does not list the pass * A renderer without the capability, or one that does not list the pass
* once a sector is set, leaves markers as they are: the document's * once a sector is set, leaves markers as they are: the document's
@@ -25,16 +25,8 @@ import {
readCyberSonarSettings, readCyberSonarSettings,
syncCyberSonarAnimation, syncCyberSonarAnimation,
} from './cyberSonar.js'; } from './cyberSonar.js';
import { import { canvasOf, findEffects, findFrame } from './render/rendererOf.js';
canvasOf,
findEffects,
findFrame,
rendererOf,
} from './render/rendererOf.js';
/** Sweep updates per second when the renderer's quality has no setting. */
export const CYBER_SONAR_DEFAULT_CADENCE_HZ =
1000 / CYBER_SONAR_RENDER_INTERVAL_MS;
const UNSUPPORTED_MESSAGE = const UNSUPPORTED_MESSAGE =
'Contact GPU unavailable. Native contacts remain visible.'; 'Contact GPU unavailable. Native contacts remain visible.';
@@ -54,14 +46,8 @@ export function createCyberSonarScene(viewer, manager) {
let current = null; let current = null;
let key = null; let key = null;
let lastSetAt = Number.NEGATIVE_INFINITY; let lastSetAt = Number.NEGATIVE_INFINITY;
let interval = CYBER_SONAR_RENDER_INTERVAL_MS;
let disposed = false; let disposed = false;
const readCadence = () => {
const hz = Number(rendererOf(viewer)?.quality?.get?.()?.sonarCadenceHz);
interval = 1000 / (hz > 0 ? hz : CYBER_SONAR_DEFAULT_CADENCE_HZ);
};
const publish = () => { const publish = () => {
const support = failed ? 'unsupported' : 'supported'; const support = failed ? 'unsupported' : 'supported';
if (root?.dataset && root.dataset.cyberSonarGpu !== support) if (root?.dataset && root.dataset.cyberSonarGpu !== support)
@@ -120,11 +106,13 @@ export function createCyberSonarScene(viewer, manager) {
const now = performance.now(); const now = performance.now();
if ( if (
next === key && next === key &&
!(sweeping && (now - lastSetAt >= interval || t.rendering)) !(
sweeping &&
(now - lastSetAt >= CYBER_SONAR_RENDER_INTERVAL_MS || t.rendering)
)
) )
return; return;
key = next; key = next;
readCadence();
set(cyberSonarSector(width, height, now, { sweeping, root }), now); set(cyberSonarSector(width, height, now, { sweeping, root }), now);
}); });
+1 -23
View File
@@ -92,7 +92,7 @@ test('the sector is the sweep the HUD shows, in CSS pixels and radians', () => {
* viewer: its frame's preUpdate is ticked by hand and its effects record * viewer: its frame's preUpdate is ticked by hand and its effects record
* each sector. * each sector.
*/ */
function fixture({ modulation = true, lists = true, cadenceHz } = {}) { function fixture({ modulation = true, lists = true } = {}) {
const previous = { const previous = {
document: globalThis.document, document: globalThis.document,
matchMedia: globalThis.matchMedia, matchMedia: globalThis.matchMedia,
@@ -137,7 +137,6 @@ function fixture({ modulation = true, lists = true, cadenceHz } = {}) {
const unbind = bindRenderer(viewer, { const unbind = bindRenderer(viewer, {
canvas, canvas,
effects, effects,
quality: { get: () => (cadenceHz ? { sonarCadenceHz: cadenceHz } : {}) },
frame: { frame: {
on(phase, cb) { on(phase, cb) {
assert.equal(phase, 'preUpdate'); assert.equal(phase, 'preUpdate');
@@ -277,27 +276,6 @@ test('the sweep sets its sector on drawing ticks and at the cadence, and changes
} }
}); });
test('the renderer cadence paces the idle sweep', () => {
const f = fixture({ cadenceHz: 4 });
const now = performance.now;
let clock = 0;
performance.now = () => clock;
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick();
clock += CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick();
assert.equal(f.sets.length, 1, '4 Hz waits 250 ms');
clock += 250 - CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick();
assert.equal(f.sets.length, 2);
dispose();
} finally {
performance.now = now;
f.restore();
}
});
test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => { test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => {
const f = fixture({ lists: false }); const f = fixture({ lists: false });
try { try {
+1 -1
View File
@@ -294,7 +294,7 @@ export function createCalibrationGizmo({
// Standard gizmo convention: parts behind geometry stay clearly // Standard gizmo convention: parts behind geometry stay clearly
// visible, just dimmed (a street-level mount buries half the heading // visible, just dimmed (a street-level mount buries half the heading
// ring in sloped photogrammetry tiles — smoke-tested 2026-07-05). // ring in sloped photogrammetry tiles — smoke-tested 2026-07-05).
depthFailColor: rgba(color, 0.45), depthFail: { kind: 'solid', color: rgba(color, 0.45) },
show: shown, show: shown,
}); });
} }
+1 -1
View File
@@ -211,7 +211,7 @@ test('the gizmo draws its parts through the draw port, shown in ADJUST mode only
assert.equal(ring.widthPx, 3); assert.equal(ring.widthPx, 3);
assert.equal(ring.positions.length, 97, 'a closed 96-segment ring'); assert.equal(ring.positions.length, 97, 'a closed 96-segment ring');
assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12); assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12);
assert.ok(Math.abs(ring.depthFailColor[3] - 0.45) < 1e-12); assert.ok(Math.abs(ring.depthFail.color[3] - 0.45) < 1e-12);
const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`); const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.equal(arrow.style.kind, 'arrow'); assert.equal(arrow.style.kind, 'arrow');
assert.equal(arrow.widthPx, 12); assert.equal(arrow.widthPx, 12);
+1 -1
View File
@@ -126,7 +126,7 @@ export function createTrail(viewer, { color, width = 2.5 }) {
style: { kind: 'solid', color: colorAt(color, alpha) }, style: { kind: 'solid', color: colorAt(color, alpha) },
// The owner-locked rule (round 6): a segment below the photoreal // The owner-locked rule (round 6): a segment below the photoreal
// mesh renders dimmed — it must never disappear into the ground. // mesh renders dimmed — it must never disappear into the ground.
depthFailColor: colorAt(color, occludedAlpha), depthFail: { kind: 'solid', color: colorAt(color, occludedAlpha) },
}; };
drawn.set(id, { key, item }); drawn.set(id, { key, item });
lines.upsert([item]); lines.upsert([item]);
+5 -2
View File
@@ -34,7 +34,10 @@ test('a trail draws its history as one dimmed-when-hidden geodesic line', (t) =>
assert.equal(line.mode, 'geodesic'); assert.equal(line.mode, 'geodesic');
assert.equal(line.style.kind, 'solid'); assert.equal(line.style.kind, 'solid');
assert.deepEqual(line.style.color, [0, 212 / 255, 1, 0.85]); assert.deepEqual(line.style.color, [0, 212 / 255, 1, 0.85]);
assert.deepEqual(line.depthFailColor, [0, 212 / 255, 1, 0.4]); assert.deepEqual(line.depthFail, {
kind: 'solid',
color: [0, 212 / 255, 1, 0.4],
});
// The same positions again change nothing; fewer than two distinct hide it. // The same positions again change nothing; fewer than two distinct hide it.
const writes = set.writes; const writes = set.writes;
@@ -65,7 +68,7 @@ test('a trail head is a line of its own beside the history, at the head alphas',
); );
assert.equal(findPickOwner(head.id), 'trails'); assert.equal(findPickOwner(head.id), 'trails');
assert.equal(head.style.color[3], 0.9); assert.equal(head.style.color[3], 0.9);
assert.equal(head.depthFailColor[3], 0.45); assert.equal(head.depthFail.color[3], 0.45);
assert.equal(head.mode, '3d', 'short: straight, two positions a frame'); assert.equal(head.mode, '3d', 'short: straight, two positions a frame');
// No head: hidden once, then nothing more to write. // No head: hidden once, then nothing more to write.
trail.setHead(null); trail.setHead(null);
+104
View File
@@ -0,0 +1,104 @@
/**
* @module geo/eyeMoves
* @description Moving and turning the eye from its pose, as `setView` takes
* the result: the app's step-by-step camera motions (pans, in-place turns, the
* globe turned under the eye, zooms) are these sums over the camera port's
* pose, so the renderer moves this way without a verb of its own.
* Each keeps the eye's world pose otherwise; a renderer keeps a `lookAt`
* frame across `setView`.
*/
import { add, cross, negate, normalize, scale } from './vector.js';
import { rotate } from './frames.js';
/**
* A `setView` view: the eye at `position`, looking along `direction` with
* `up` up.
* @typedef {{destination: {x: number, y: number, z: number},
* orientation: {direction: {x: number, y: number, z: number},
* up: {x: number, y: number, z: number}}}} EyeView
*/
const view = (position, direction, up) => ({
destination: position,
orientation: { direction, up },
});
/**
* The eye moved `metres` along one of its own axes.
* @param {{position: object, direction: object, up: object, right: object}} pose
* @param {'forward'|'back'|'left'|'right'|'up'|'down'} direction
* @param {number} metres
* @returns {EyeView}
*/
export function eyeMoved(pose, direction, metres) {
const axes = {
forward: pose.direction,
back: negate(pose.direction),
right: pose.right,
left: negate(pose.right),
up: pose.up,
down: negate(pose.up),
};
if (!Object.hasOwn(axes, direction))
throw new RangeError(`no move direction '${direction}'`);
return view(
add(pose.position, scale(axes[direction], metres)),
pose.direction,
pose.up,
);
}
/**
* The eye turned in place by `radians`: left and right about its own up,
* up and down about its own right.
* @param {{position: object, direction: object, up: object, right: object}} pose
* @param {'left'|'right'|'up'|'down'} direction
* @param {number} radians
* @returns {EyeView}
*/
export function eyeTurned(pose, direction, radians) {
const turns = {
left: [pose.up, radians],
right: [pose.up, -radians],
up: [pose.right, radians],
down: [pose.right, -radians],
};
if (!Object.hasOwn(turns, direction))
throw new RangeError(`no look direction '${direction}'`);
const [axis, angle] = turns[direction];
const a = normalize(axis);
return view(
pose.position,
rotate(pose.direction, a, angle),
rotate(pose.up, a, angle),
);
}
/**
* The eye carried about `axis` through the Earth's centre by `radians`,
* position and view together: a positive angle turns it clockwise seen
* from the axis's tip (the globe seems to turn the other way).
* @param {{position: object, direction: object, up: object}} pose
* @param {{x: number, y: number, z: number}} axis
* @param {number} radians
* @returns {EyeView}
*/
export function eyeRotatedAbout(pose, axis, radians) {
const a = normalize(axis);
const direction = rotate(pose.direction, a, -radians);
const turnedUp = rotate(pose.up, a, -radians);
const right = cross(direction, turnedUp);
return view(
rotate(pose.position, a, -radians),
normalize(direction),
normalize(cross(right, direction)),
);
}
/**
* The eye moved `metres` along its view direction; negative backs away.
* @param {{position: object, direction: object, up: object, right: object}} pose
* @param {number} metres
* @returns {EyeView}
*/
export const eyeZoomed = (pose, metres) => eyeMoved(pose, 'forward', metres);
+4 -2
View File
@@ -32,7 +32,9 @@ function lineItemOf(handle) {
style: handle.dashed style: handle.dashed
? { kind: 'dash', color, length: 16, pattern16: 255 } ? { kind: 'dash', color, length: 16, pattern16: 255 }
: { kind: 'solid', color }, : { kind: 'solid', color },
depthFailColor: handle.depthFailColor ?? null, depthFail: handle.depthFailColor
? { kind: 'solid', color: handle.depthFailColor }
: null,
meta: { cameraId: handle.cameraId }, meta: { cameraId: handle.cameraId },
show: handle.show !== false, show: handle.show !== false,
}; };
@@ -45,7 +47,7 @@ const lineKey = (item) =>
item.widthPx, item.widthPx,
item.style.kind, item.style.kind,
item.style.color.join(','), item.style.color.join(','),
item.depthFailColor ? item.depthFailColor.join(',') : '', item.depthFail ? item.depthFail.color.join(',') : '',
item.show, item.show,
].join('|'); ].join('|');
+2 -2
View File
@@ -39,7 +39,7 @@ test('lines are written as they change, and drawn as their handles say', () => {
widthPx: 1.2, widthPx: 1.2,
mode: 'geodesic', mode: 'geodesic',
style: { kind: 'solid', color: a.color }, style: { kind: 'solid', color: a.color },
depthFailColor: null, depthFail: null,
meta: { cameraId: 'cam' }, meta: { cameraId: 'cam' },
show: true, show: true,
}); });
@@ -58,7 +58,7 @@ test('lines are written as they change, and drawn as their handles say', () => {
length: 16, length: 16,
pattern16: 255, pattern16: 255,
}); });
assert.deepEqual(cap.depthFailColor, [1, 1, 1, 0.2]); assert.deepEqual(cap.depthFail, { kind: 'solid', color: [1, 1, 1, 0.2] });
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage'); assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
assert.equal(drawSets.roleOfSet('other:1:lines'), null); assert.equal(drawSets.roleOfSet('other:1:lines'), null);
+67 -11
View File
@@ -10,11 +10,69 @@ const ZONE_FILL_ALPHA = 0.105;
const ZONE_RIM_ALPHA = 0.72; const ZONE_RIM_ALPHA = 0.72;
/** The rim's width, a fraction of the zone's radius. */ /** The rim's width, a fraction of the zone's radius. */
const ZONE_RIM_WIDTH = 0.033; const ZONE_RIM_WIDTH = 0.033;
/** Where the zone's soft edge starts, a fraction of its radius. */
const ZONE_EDGE = 0.985;
/** How much brighter the rim glows than its colour. */
const ZONE_RIM_GLOW = 0.35;
/** The zone image's side, pixels. */
const ZONE_IMAGE_PX = 512;
const smoothstep = (edge0, edge1, x) => {
const t = Math.min(1, Math.max(0, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
};
/** /**
* Pulled toward the eye, metres, so the zone is not buried by the pad's * The zone's colour and alpha at `r`, a fraction of its radius from its
* mesh at oblique angles, without a height that would float it. * centre: the fill's colour, easing into the rim's (which glows a little)
* over `ZONE_RIM_WIDTH` just inside a soft edge, nothing past it.
* @param {number} r
* @returns {[number, number, number, number]} `r, g, b, a`, 0..1.
*/ */
const ZONE_DEPTH_BIAS_M = 1; export function launchPadZoneColour(r) {
const [red, green, blue] = hexColor(ZONE_COLOR, 1);
const inside = 1 - smoothstep(ZONE_EDGE, 1, r);
const rim = smoothstep(ZONE_EDGE - ZONE_RIM_WIDTH, ZONE_EDGE, r) * inside;
const glow = 1 + ZONE_RIM_GLOW * rim;
return [
Math.min(1, red * glow),
Math.min(1, green * glow),
Math.min(1, blue * glow),
inside * (ZONE_FILL_ALPHA + (ZONE_RIM_ALPHA - ZONE_FILL_ALPHA) * rim),
];
}
/** The zone's image, made on first use; null where there is no 2D canvas. */
let zoneImage;
/**
* The zone as an image fill: `launchPadZoneColour` across a square canvas,
* its centre at the middle and its edge at the sides.
* @param {() => HTMLCanvasElement} [createCanvas]
* @returns {?{canvas: HTMLCanvasElement, key: string}}
*/
export function launchPadZoneImage(
createCanvas = () => globalThis.document?.createElement('canvas'),
) {
if (zoneImage !== undefined) return zoneImage;
const canvas = createCanvas();
const context = canvas?.getContext?.('2d');
if (!context) return (zoneImage = null);
canvas.width = ZONE_IMAGE_PX;
canvas.height = ZONE_IMAGE_PX;
const image = context.createImageData(ZONE_IMAGE_PX, ZONE_IMAGE_PX);
const half = ZONE_IMAGE_PX / 2;
for (let y = 0; y < ZONE_IMAGE_PX; y++)
for (let x = 0; x < ZONE_IMAGE_PX; x++) {
const r = Math.hypot(x + 0.5 - half, y + 0.5 - half) / half;
const colour = launchPadZoneColour(r);
const at = (y * ZONE_IMAGE_PX + x) * 4;
for (let k = 0; k < 4; k++)
image.data[at + k] = Math.round(colour[k] * 255);
}
context.putImageData(image, 0, 0);
return (zoneImage = { canvas, key: 'launch-pad-zone' });
}
export function createLaunchPad({ export function createLaunchPad({
state: layerState, state: layerState,
@@ -39,9 +97,13 @@ export function createLaunchPad({
layerState._launchPadZoneLaunchId = null; layerState._launchPadZoneLaunchId = null;
} }
/** The zone drawn around a launch's pad, draped on the ground. */ /**
* The zone drawn around a launch's pad, draped on the ground (and on the
* pad's mesh); a plain fill where there is no canvas to draw it with.
*/
function createLaunchPadZonePrimitive(launch) { function createLaunchPadZonePrimitive(launch) {
removeLaunchPadZonePrimitive(); removeLaunchPadZonePrimitive();
const image = launchPadZoneImage();
const item = { const item = {
id: `rocket-pad-zone:${launch.id}`, id: `rocket-pad-zone:${launch.id}`,
geometry: { geometry: {
@@ -50,15 +112,9 @@ export function createLaunchPad({
semiMajor: LAUNCH_PAD_ZONE_RADIUS_M, semiMajor: LAUNCH_PAD_ZONE_RADIUS_M,
semiMinor: LAUNCH_PAD_ZONE_RADIUS_M, semiMinor: LAUNCH_PAD_ZONE_RADIUS_M,
}, },
fill: { fill: image ? { image } : hexColor(ZONE_COLOR, ZONE_FILL_ALPHA),
preset: 'radialRim',
color: hexColor(ZONE_COLOR, ZONE_FILL_ALPHA),
rimColor: hexColor(ZONE_COLOR, ZONE_RIM_ALPHA),
rimWidth: ZONE_RIM_WIDTH,
},
height: 'clampGround', height: 'clampGround',
clampTo: 'both', clampTo: 'both',
depthBias: ZONE_DEPTH_BIAS_M,
show: true, show: true,
}; };
layerState._launchPadZoneItem = item; layerState._launchPadZoneItem = item;
+2 -2
View File
@@ -477,8 +477,8 @@ test('the trail head runs from the last fix to the marker every frame, dimmed be
color: hexColor('#ff4fd8', 0.9), color: hexColor('#ff4fd8', 0.9),
}); });
assert.deepEqual( assert.deepEqual(
head.depthFailColor, head.depthFail,
hexColor('#ff4fd8', 0.45), { kind: 'solid', color: hexColor('#ff4fd8', 0.45) },
'dimmed, not hidden, behind the surface', 'dimmed, not hidden, behind the surface',
); );
assert.equal(head.positions.length, 2); assert.equal(head.positions.length, 2);
@@ -481,7 +481,10 @@ test('tracking without a Cockpit subject keeps its marks', async (t) => {
/** A ring's drawn colour and behind-the-globe colour. */ /** A ring's drawn colour and behind-the-globe colour. */
function ringColors(f, id) { function ringColors(f, id) {
const item = f.ring(id); const item = f.ring(id);
return { color: [...item.style.color], depthFail: [...item.depthFailColor] }; return {
color: [...item.style.color],
depthFail: [...item.depthFail.color],
};
} }
test('a Cockpit subject dims every other orbit ring and restores it exactly', async (t) => { test('a Cockpit subject dims every other orbit ring and restores it exactly', async (t) => {
@@ -506,7 +509,11 @@ test('a Cockpit subject dims every other orbit ring and restores it exactly', as
); );
assert.equal(f.ring(ISS_NORAD).show, true, 'other rings stay visible'); assert.equal(f.ring(ISS_NORAD).show, true, 'other rings stay visible');
assert.equal(f.ring(GPS).show, false, 'the ridden ring stays hidden'); assert.equal(f.ring(GPS).show, false, 'the ridden ring stays hidden');
assert.deepEqual(ringColors(f, GPS), gpsBuilt, 'the ridden ring is not dimmed'); assert.deepEqual(
ringColors(f, GPS),
gpsBuilt,
'the ridden ring is not dimmed',
);
// Other satellites' points stay as they are. // Other satellites' points stay as they are.
assert.equal(f.state._points.get(COMPANION).show, true); assert.equal(f.state._points.get(COMPANION).show, true);
+1 -1
View File
@@ -251,7 +251,7 @@ test('the rendering part draws the dots, the tracked dot and the rings through t
assert.equal(rings.spec.pickable, false, 'ring clicks fall through'); assert.equal(rings.spec.pickable, false, 'ring clicks fall through');
const ring = rings.items.get('25544'); const ring = rings.items.get('25544');
assert.deepEqual(ring.style, { kind: 'solid', color: [1, 1, 0, 0.6] }); assert.deepEqual(ring.style, { kind: 'solid', color: [1, 1, 0, 0.6] });
assert.deepEqual(ring.depthFailColor, [1, 1, 0, 0.35]); assert.deepEqual(ring.depthFail, { kind: 'solid', color: [1, 1, 0, 0.35] });
assert.equal(ring.widthPx, 2.5, 'the ISS ring is wider'); assert.equal(ring.widthPx, 2.5, 'the ISS ring is wider');
assert.equal(ring.mode, 'geodesic'); assert.equal(ring.mode, 'geodesic');
assert.deepEqual([...ring.positions.slice(0, 3)], [7e6, 0, 0]); assert.deepEqual([...ring.positions.slice(0, 3)], [7e6, 0, 0]);
+10 -7
View File
@@ -229,10 +229,10 @@ export function createRendering({
kind: 'solid', kind: 'solid',
color: withAlpha(path.color, RING_ALPHA * factor), color: withAlpha(path.color, RING_ALPHA * factor),
}; };
path.item.depthFailColor = withAlpha( path.item.depthFail = {
path.color, kind: 'solid',
RING_BEHIND_ALPHA * factor, color: withAlpha(path.color, RING_BEHIND_ALPHA * factor),
); };
sets?.rings.upsert([path.item]); sets?.rings.upsert([path.item]);
return true; return true;
} }
@@ -460,7 +460,7 @@ export function createRendering({
/** /**
* Show orbital path for a satellite: the ring over one orbit, baked once * Show orbital path for a satellite: the ring over one orbit, baked once
* in ECEF at the current GMST, bright in front of the globe and dimmed * in ECEF at the current GMST, bright in front of the globe and dimmed
* behind it (`depthFailColor`), and turned with the Earth each * behind it (`depthFail`), and turned with the Earth each
* `RING_ROTATION_MS` (`_updateOrbitPathRotations`). * `RING_ROTATION_MS` (`_updateOrbitPathRotations`).
*/ */
@@ -494,7 +494,10 @@ export function createRendering({
// Along the ellipsoid between samples, as the ring always ran. // Along the ellipsoid between samples, as the ring always ran.
mode: 'geodesic', mode: 'geodesic',
style: { kind: 'solid', color: withAlpha(pathColor, RING_ALPHA) }, style: { kind: 'solid', color: withAlpha(pathColor, RING_ALPHA) },
depthFailColor: withAlpha(pathColor, RING_BEHIND_ALPHA), depthFail: {
kind: 'solid',
color: withAlpha(pathColor, RING_BEHIND_ALPHA),
},
show: true, show: true,
}; };
layerState._orbitPaths.set(noradId, path); layerState._orbitPaths.set(noradId, path);
@@ -521,7 +524,7 @@ export function createRendering({
* *
* No SGP4 here: WGS84 is rotationally symmetric about Z, so rotating the * No SGP4 here: WGS84 is rotationally symmetric about Z, so rotating the
* baked curve rigidly equals rebaking from rotated points. A ring with a * baked curve rigidly equals rebaking from rotated points. A ring with a
* `depthFailColor` is built at once where it now runs, so it never blinks. * `depthFail` style is built at once where it now runs, so it never blinks.
* @param {Date} nowDate Epoch used for current GMST. * @param {Date} nowDate Epoch used for current GMST.
*/ */
+48 -41
View File
@@ -38,25 +38,6 @@ export const EASINGS = Object.freeze({
sineInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT, sineInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
}); });
/**
* The contract's moves and looks as Cesium camera method names, called by
* name: a caller's camera may come from another copy of Cesium.
*/
const MOVES = Object.freeze({
forward: 'moveForward',
back: 'moveBackward',
left: 'moveLeft',
right: 'moveRight',
up: 'moveUp',
down: 'moveDown',
});
const LOOKS = Object.freeze({
left: 'lookLeft',
right: 'lookRight',
up: 'lookUp',
down: 'lookDown',
});
/** A contract destination as Cesium's: a Cartesian3, or a Rectangle. */ /** A contract destination as Cesium's: a Cartesian3, or a Rectangle. */
export function toDestination(d) { export function toDestination(d) {
if ('rect' in d) { if ('rect' in d) {
@@ -219,16 +200,60 @@ export function createCesiumCamera({
if (frustum.fov !== fov) frustum.fov = fov; if (frustum.fov !== fov) frustum.fov = fov;
} }
/**
* Put the eye at world point `destination` looking along `direction` with
* `up` up (made square to it), in the camera's frame: a `lookAt` frame
* stays, as Cesium's setView keeps it.
*/
function placeEye(destination, { direction, up }) {
const at = toCartesian(destination);
const dir = Cesium.Cartesian3.normalize(
toCartesian(direction),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(dir, toCartesian(up), new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const square = Cesium.Cartesian3.cross(right, dir, new Cesium.Cartesian3());
const transform = camera.transform;
if (
transform &&
!Cesium.Matrix4.equals(transform, Cesium.Matrix4.IDENTITY)
) {
const inverse = Cesium.Matrix4.inverseTransformation(
transform,
new Cesium.Matrix4(),
);
Cesium.Matrix4.multiplyByPoint(inverse, at, camera.position);
Cesium.Matrix4.multiplyByPointAsVector(inverse, dir, camera.direction);
Cesium.Matrix4.multiplyByPointAsVector(inverse, square, camera.up);
Cesium.Matrix4.multiplyByPointAsVector(inverse, right, camera.right);
return;
}
Cesium.Cartesian3.clone(at, camera.position);
Cesium.Cartesian3.clone(dir, camera.direction);
Cesium.Cartesian3.clone(square, camera.up);
Cesium.Cartesian3.clone(right, camera.right);
}
const cameraPort = { const cameraPort = {
on: (event, cb, options) => cameraEvents.on(event, cb, options), on: (event, cb, options) => cameraEvents.on(event, cb, options),
onCommand: (cb) => commandHooks.on(cb), onCommand: (cb) => commandHooks.on(cb),
setView(spec) { setView(spec) {
command('setView'); command('setView');
const d = spec.destination; const d = spec.destination;
camera.setView({ const o = spec.orientation;
...(d ? { destination: toDestination(d) } : {}), // A view by direction and up at a point is placed as given: Cesium's
orientation: toOrientation(spec.orientation), // own setView would round it through heading, pitch and roll, which
}); // drifts looking straight down, where steps add up (the app's pans,
// turns and globe turns are setViews).
if (d && !('rect' in d) && o && 'direction' in o) placeEye(d, o);
else
camera.setView({
...(d ? { destination: toDestination(d) } : {}),
orientation: toOrientation(o),
});
scene.requestRender(); scene.requestRender();
}, },
flyTo(destination, options = {}) { flyTo(destination, options = {}) {
@@ -314,24 +339,6 @@ export function createCesiumCamera({
camera.lookAtTransform(Cesium.Matrix4.IDENTITY); camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
scene.requestRender(); scene.requestRender();
}, },
move(direction, metres) {
camera[MOVES[direction]](metres);
scene.requestRender();
},
look(direction, radians) {
camera[LOOKS[direction]](radians);
scene.requestRender();
},
rotateAround(axis, radians) {
camera.rotate(toCartesian(axis), radians);
scene.requestRender();
},
zoom(metres) {
// Cesium's zoom, not a move: outside 3D it changes the view's width.
if (metres < 0) camera.zoomOut(-metres);
else camera.zoomIn(metres);
scene.requestRender();
},
setFov({ vertical }) { setFov({ vertical }) {
// Cesium would take a bad angle and draw a garbage projection. // Cesium would take a bad angle and draw a garbage projection.
if (!(vertical > 0 && vertical < Math.PI)) if (!(vertical > 0 && vertical < Math.PI))
+50 -227
View File
@@ -189,40 +189,11 @@ czm_material czm_getMaterial(czm_materialInput materialInput) {
return m; return m;
}`; }`;
/** The `radialRim` fill's material type. */
const RADIAL_RIM_MATERIAL = 'DrawRadialRimFill';
/** /**
* Across the ellipse (`st` from its centre, 1 at its edge) the fill's * How finely a clamped ellipse with an image fill is cut, radians, so an
* colour, easing into the rim's over `rimWidth` (a fraction of the * image's round edge (a zone's rim) runs round.
* radius) just inside a soft edge; the rim glows a little.
*/ */
const RADIAL_RIM_SOURCE = ` const IMAGE_ELLIPSE_GRANULARITY = Cesium.Math.toRadians(0.08);
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 centered = (materialInput.st - vec2(0.5)) * 2.0;
float radius = length(centered);
float inside = 1.0 - smoothstep(0.985, 1.0, radius);
float rim = smoothstep(0.985 - rimWidth, 0.985, radius) * inside;
material.diffuse = mix(color.rgb, rimColor.rgb, rim);
material.emission = rimColor.rgb * rim * 0.35;
material.alpha = inside * mix(color.a, rimColor.a, rim);
return material;
}`;
/** How finely a rim-filled ellipse is cut, radians. */
const RIM_GRANULARITY = Cesium.Math.toRadians(0.08);
/**
* A ground fill pulled toward the eye (`depthBias`): depth-tested, not
* writing depth, offset toward the camera, alpha blended.
*/
const DEPTH_BIASED_STATE = Object.freeze({
depthTest: { enabled: true },
depthMask: false,
polygonOffset: { enabled: true, factor: -1, units: -4 },
blending: Cesium.BlendingState.ALPHA_BLEND,
});
/** /**
* An image fill's material. The image carries its own alpha, so it draws in * An image fill's material. The image carries its own alpha, so it draws in
@@ -241,33 +212,6 @@ function imageMaterial(image, repeat = [1, 1]) {
return material; return material;
} }
/** A `radialRim` fill's material. */
function radialRimMaterial(fill) {
const uniforms = {
color: toColor(fill.color),
rimColor: toColor(fill.rimColor),
rimWidth: fill.rimWidth,
};
// Built from its type, then given its values, as the line materials are.
const material = new Cesium.Material({
fabric: { type: RADIAL_RIM_MATERIAL, uniforms, source: RADIAL_RIM_SOURCE },
});
Object.assign(material.uniforms, uniforms);
return material;
}
/**
* An ellipse radius at a camera `height`: a fixed one as it is, one by
* camera height scaled by its factor and held within its bounds.
* @param {number|{byCameraHeight: {factor: number, min: number, max: number}}} radius
* @param {number} height
*/
export function radiusAt(radius, height) {
if (typeof radius === 'number') return radius;
const { factor, min, max } = radius.byCameraHeight;
return Math.max(min, Math.min(max, height * factor));
}
/** /**
* A shape's `animate`, checked: the Cesium renderer pulses alpha, forever. * A shape's `animate`, checked: the Cesium renderer pulses alpha, forever.
* Null for a shape that does not pulse. * Null for a shape that does not pulse.
@@ -305,12 +249,6 @@ export function pulseAlpha(pulse, now) {
return pulse.from + (pulse.to - pulse.from) * (0.5 + 0.5 * Math.sin(turn)); return pulse.from + (pulse.to - pulse.from) * (0.5 + 0.5 * Math.sin(turn));
} }
/** Whether a shape is an ellipse with a radius by camera height. */
const byCameraHeight = (item) =>
item.geometry?.kind === 'ellipse' &&
(typeof item.geometry.semiMajor !== 'number' ||
typeof item.geometry.semiMinor !== 'number');
/** The line styles the port drapes. */ /** The line styles the port drapes. */
const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow', 'arrow']); const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow', 'arrow']);
@@ -1932,8 +1870,8 @@ export function createCesiumDraw({
positions.some((p) => !Cesium.Cartesian3.equals(p, positions[0])); positions.some((p) => !Cesium.Cartesian3.equals(p, positions[0]));
/** /**
* A line not draped that has a `depthFailColor`: a primitive of its own, * A line not draped that has a `depthFail` style: a primitive of its own,
* drawn in that colour where the surface hides it. Built at once, so one * drawn in that style where the surface hides it. Built at once, so one
* built anew where it moves draws in the frame it replaces the old one. * built anew where it moves draws in the frame it replaces the old one.
* Null when its positions make no line. * Null when its positions make no line.
*/ */
@@ -1961,18 +1899,7 @@ export function createCesiumDraw({
}), }),
appearance: new Cesium.PolylineMaterialAppearance({ material }), appearance: new Cesium.PolylineMaterialAppearance({ material }),
depthFailAppearance: new Cesium.PolylineMaterialAppearance({ depthFailAppearance: new Cesium.PolylineMaterialAppearance({
material: lineMaterial( material: lineMaterial(record, item.depthFail, reveal),
record,
item.depthFailDash
? {
kind: 'dash',
color: item.depthFailColor,
length: item.depthFailDash.length,
pattern16: item.depthFailDash.pattern16,
}
: { kind: 'solid', color: item.depthFailColor },
reveal,
),
}), }),
show: item.show !== false, show: item.show !== false,
asynchronous: false, asynchronous: false,
@@ -2080,7 +2007,7 @@ export function createCesiumDraw({
const line = { const line = {
...rest, ...rest,
mode: '3d', mode: '3d',
depthFailColor: item.style.color, depthFail: { kind: 'solid', color: item.style.color },
overlaid: true, overlaid: true,
}; };
if (segmentShow?.length) { if (segmentShow?.length) {
@@ -2113,10 +2040,9 @@ export function createCesiumDraw({
return true; return true;
} }
/** An overlay line's look but its colours (its depth-fail colour is its /** An overlay line's look but its colours (its depth-fail style is its
* colour too). */ * colour too). */
const overlayShape = (item) => const overlayShape = (item) => lineLook({ ...item, depthFail: null }, true);
lineLook({ ...item, depthFailColor: null }, true);
/** Stop tracking a line no longer drawn over the surface for a draped /** Stop tracking a line no longer drawn over the surface for a draped
* one. */ * one. */
@@ -2191,11 +2117,20 @@ export function createCesiumDraw({
); );
else if ( else if (
item.frame === 'inertial' && item.frame === 'inertial' &&
(item.mode === 'draped' || item.depthFailColor) (item.mode === 'draped' || item.depthFail)
) )
throw new Error( throw new Error(
'the Cesium renderer draws inertial lines undraped, without depth-fail colours', 'the Cesium renderer draws inertial lines undraped, without depth-fail colours',
); );
else if (
item.mode !== 'draped' &&
item.depthFail &&
item.depthFail.kind !== 'solid' &&
item.depthFail.kind !== 'dash'
)
throw new Error(
'the Cesium renderer draws solid and dashed lines behind the surface only',
);
else if ( else if (
segmented(item) && segmented(item) &&
(item.mode !== 'draped' || (item.mode !== 'draped' ||
@@ -2274,7 +2209,7 @@ export function createCesiumDraw({
draped.get(clampTo).push(drapedInstance(item, part, true)); draped.get(clampTo).push(drapedInstance(item, part, true));
continue; continue;
} }
if (item.depthFailColor) { if (item.depthFail) {
deep ??= new Cesium.PrimitiveCollection(); deep ??= new Cesium.PrimitiveCollection();
const id = pickId(record, item); const id = pickId(record, item);
const primitive = depthFailLine(record, item, id); const primitive = depthFailLine(record, item, id);
@@ -2418,10 +2353,14 @@ export function createCesiumDraw({
item.widthPx, item.widthPx,
item.clampTo, item.clampTo,
colourless ? { ...item.style, color: undefined } : item.style, colourless ? { ...item.style, color: undefined } : item.style,
item.depthFailColor, // The same depth-fail style in any key order.
// A dash is drawn only with a depth-fail colour, the same in any key order. item.depthFail
item.depthFailColor && item.depthFailDash ? [
? [item.depthFailDash.length, item.depthFailDash.pattern16] item.depthFail.kind,
item.depthFail.color,
item.depthFail.length,
item.depthFail.pattern16,
]
: null, : null,
// Segment colours and shows change in place. // Segment colours and shows change in place.
item.segmentColors != null, item.segmentColors != null,
@@ -2439,7 +2378,7 @@ export function createCesiumDraw({
Object.is(a.widthPx, b.widthPx) && Object.is(a.widthPx, b.widthPx) &&
a.clampTo === b.clampTo && a.clampTo === b.clampTo &&
a.style === b.style && a.style === b.style &&
a.depthFailColor === b.depthFailColor && a.depthFail === b.depthFail &&
(a.segmentColors != null) === (b.segmentColors != null) && (a.segmentColors != null) === (b.segmentColors != null) &&
(a.segmentShow != null) === (b.segmentShow != null) && (a.segmentShow != null) === (b.segmentShow != null) &&
revealed(a) === revealed(b) && revealed(a) === revealed(b) &&
@@ -2756,7 +2695,7 @@ export function createCesiumDraw({
const settles = (item) => const settles = (item) =>
item.mode !== 'draped' && item.mode !== 'draped' &&
item.frame !== 'inertial' && item.frame !== 'inertial' &&
!item.depthFailColor && !item.depthFail &&
item.style.kind === 'solid' && item.style.kind === 'solid' &&
!revealed(item) && !revealed(item) &&
// The collection draws no line under half a pixel wide; a batch // The collection draws no line under half a pixel wide; a batch
@@ -3219,10 +3158,6 @@ export function createCesiumDraw({
}; };
} }
case 'ellipse': { case 'ellipse': {
if (byCameraHeight(item))
throw new Error(
'the Cesium renderer takes radii by camera height on clamped ellipses only',
);
const ellipse = { const ellipse = {
center: toCartesian(g.center), center: toCartesian(g.center),
semiMajorAxis: g.semiMajor, semiMajorAxis: g.semiMajor,
@@ -3276,91 +3211,12 @@ export function createCesiumDraw({
} }
} }
/**
* The camera's height for radii by camera height: above the ellipsoid,
* as Cesium places it (1000 m while it has none).
*/
const cameraHeight = () => {
const height = scene.camera?.positionCartographic?.height;
return Number.isFinite(height) ? height : 1000;
};
/** A clamped ellipse's radii by camera height at this frame's height, or null. */
function radiiOf(item) {
if (!byCameraHeight(item)) return null;
const height = cameraHeight();
return [
radiusAt(item.geometry.semiMajor, height),
radiusAt(item.geometry.semiMinor, height),
];
}
/**
* Before a frame draws: clamped ellipses with radii by camera height
* whose radii have changed with the camera are drawn at the new ones. A
* colour fill is drawn alone where it is, built in this frame
* (`moveShape`), as Cesium's entities rebuild a ground ellipse whose
* radius follows a callback, while no more than `MOVING_SHAPES` of the
* set would be drawn alone; past that, and for any other fill once its
* radii have changed by more than `REBUILD_RADII`, its set rebuilds (one
* rebuild at a time). Hidden ones wait until they show.
*/
function followCameraHeight() {
for (const record of sets.values()) {
const parts = record.shapeParts;
if (record.kind !== 'shapes' || !parts || record.spec.show === false)
continue;
try {
followIn(record, parts);
} catch (error) {
// The set draws as it did; the next frame tries again.
report(error);
}
}
}
/** Relative change of radii past which a fill drawn in a batch rebuilds. */
const REBUILD_RADII = 0.02;
function followIn(record, parts) {
const changed = (radii, part, by) =>
Math.abs(radii[0] - part.radii[0]) > by * part.radii[0] ||
Math.abs(radii[1] - part.radii[1]) > by * part.radii[1];
let alone = 0;
for (const part of parts.values()) if (part.solo) alone += 1;
// Those the host still retiring draws alone count too, until it goes.
if (record.retiring)
for (const part of record.retiringShapeParts?.values() ?? [])
if (part.solo && part.ground && !part.ground.isDestroyed()) alone += 1;
let rebuild = false;
for (const [id, part] of parts) {
if (!part.radii || !part.ground) continue;
const item = record.items.get(id);
if (!item || item.show === false || !byCameraHeight(item)) continue;
const radii = radiiOf(item);
if (!changed(radii, part, 1e-3)) continue;
if (part.ground.isDestroyed() || part.batch?.isDestroyed()) continue;
const movable =
colourFill(item) &&
groundSyncs() &&
typeof record.host?.add === 'function' &&
(part.solo || alone < MOVING_SHAPES);
if (movable) {
if (!part.solo) alone += 1;
moveShape(record, part, item);
} else if (changed(radii, part, REBUILD_RADII)) rebuild = true;
}
if (rebuild && !record.pending) {
record.rebuild();
requestRender();
}
}
/** /**
* A clamped shape's fill geometry, on the ellipsoid for draping; an * A clamped shape's fill geometry, on the ellipsoid for draping; an
* ellipse with a rim fill is cut finely, so its rim runs round. * ellipse with an image fill is cut finely, so a round image's edge runs
* round.
*/ */
function groundGeometry(item, rimFill = null) { function groundGeometry(item, imageFill = false) {
const g = item.geometry; const g = item.geometry;
switch (g.kind) { switch (g.kind) {
case 'polygon': { case 'polygon': {
@@ -3373,21 +3229,19 @@ export function createCesiumDraw({
}); });
} }
case 'ellipse': { case 'ellipse': {
// Radii by camera height are the ones it has at this frame's height. const major = g.semiMajor;
const height = cameraHeight(); const minor = g.semiMinor;
const major = radiusAt(g.semiMajor, height); // A semi-minor axis longer than the semi-major one is drawn as
const minor = radiusAt(g.semiMinor, height); // Cesium's semi-major axis, a quarter turn on.
// Radii that follow the camera apart may cross: the longer is then
// drawn as Cesium's semi-major axis, a quarter turn on.
const crossed = minor > major; const crossed = minor > major;
return new Cesium.EllipseGeometry({ return new Cesium.EllipseGeometry({
center: toCartesian(g.center), center: toCartesian(g.center),
semiMajorAxis: crossed ? minor : major, semiMajorAxis: crossed ? minor : major,
semiMinorAxis: crossed ? major : minor, semiMinorAxis: crossed ? major : minor,
rotation: (g.rotation ?? 0) + (crossed ? Math.PI / 2 : 0), rotation: (g.rotation ?? 0) + (crossed ? Math.PI / 2 : 0),
...(rimFill ...(imageFill
? { ? {
granularity: RIM_GRANULARITY, granularity: IMAGE_ELLIPSE_GRANULARITY,
vertexFormat: vertexFormat:
Cesium.MaterialAppearance.MaterialSupport.TEXTURED Cesium.MaterialAppearance.MaterialSupport.TEXTURED
.vertexFormat, .vertexFormat,
@@ -3436,11 +3290,7 @@ export function createCesiumDraw({
typeof item.fill === 'object' && !Array.isArray(item.fill) typeof item.fill === 'object' && !Array.isArray(item.fill)
? item.fill ? item.fill
: null; : null;
const rimFill = const imageFill = objectFill;
objectFill?.preset === 'radialRim' && item.geometry.kind === 'ellipse'
? objectFill
: null;
const imageFill = rimFill ? null : objectFill;
if (imageFill && !imageFill.image) if (imageFill && !imageFill.image)
throw new Error('the Cesium renderer fills shapes with colours only'); throw new Error('the Cesium renderer fills shapes with colours only');
if (item.extrudeHeight !== undefined) if (item.extrudeHeight !== undefined)
@@ -3457,7 +3307,7 @@ export function createCesiumDraw({
// load when they show. // load when they show.
let geometry; let geometry;
try { try {
geometry = groundGeometry(item, rimFill); geometry = groundGeometry(item, Boolean(imageFill));
} catch (error) { } catch (error) {
if (item.show === false) continue; if (item.show === false) continue;
throw error; throw error;
@@ -3466,8 +3316,6 @@ export function createCesiumDraw({
look: lookOf(item), look: lookOf(item),
id: pickId(record, item), id: pickId(record, item),
ground: null, ground: null,
// Radii by camera height as drawn (`followCameraHeight`).
radii: radiiOf(item),
pulse: pulseOf(item), pulse: pulseOf(item),
show: item.show !== false, show: item.show !== false,
}; };
@@ -3477,29 +3325,17 @@ export function createCesiumDraw({
); );
const instance = new Cesium.GeometryInstance({ const instance = new Cesium.GeometryInstance({
geometry, geometry,
attributes: attributes: imageFill
imageFill || rimFill ? { show }
? { show } : {
: { color: Cesium.ColorGeometryInstanceAttribute.fromColor(
color: Cesium.ColorGeometryInstanceAttribute.fromColor( toColor(item.fill),
toColor(item.fill), ),
), show,
show, },
},
id: part.id, id: part.id,
}); });
const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both';
if (rimFill) {
// A rim fill is a ground primitive of its own, with its material.
batches.push({
clampTo,
instances: [instance],
parts: [part],
rimFill,
depthBias: item.depthBias,
});
continue;
}
if (imageFill) { if (imageFill) {
// An image fill is a ground primitive of its own, with its material. // An image fill is a ground primitive of its own, with its material.
// (Cesium turns its texture wrongly across the antimeridian: its // (Cesium turns its texture wrongly across the antimeridian: its
@@ -3540,9 +3376,7 @@ export function createCesiumDraw({
const grounds = batches.map((batch) => { const grounds = batches.map((batch) => {
const material = batch.imageFill const material = batch.imageFill
? imageMaterial(batch.image, batch.imageFill.repeat) ? imageMaterial(batch.image, batch.imageFill.repeat)
: batch.rimFill : null;
? radialRimMaterial(batch.rimFill)
: null;
const ground = new Ground({ const ground = new Ground({
geometryInstances: batch.instances, geometryInstances: batch.instances,
classificationType: classificationOf(batch.clampTo), classificationType: classificationOf(batch.clampTo),
@@ -3555,15 +3389,6 @@ export function createCesiumDraw({
Cesium.MaterialAppearance.MaterialSupport.TEXTURED, Cesium.MaterialAppearance.MaterialSupport.TEXTURED,
translucent: true, translucent: true,
flat: true, flat: true,
...(batch.rimFill
? {
closed: false,
faceForward: true,
...(batch.depthBias
? { renderState: DEPTH_BIASED_STATE }
: {}),
}
: {}),
}), }),
} }
: {}), : {}),
@@ -3943,7 +3768,6 @@ export function createCesiumDraw({
part.solo = true; part.solo = true;
part.pendingShow = undefined; part.pendingShow = undefined;
part.look = lookOf(item); part.look = lookOf(item);
part.radii = radiiOf(item);
part.pulse = pulseOf(item); part.pulse = pulseOf(item);
part.show = item.show !== false; part.show = item.show !== false;
part.pendingColour = undefined; part.pendingColour = undefined;
@@ -4344,7 +4168,6 @@ export function createCesiumDraw({
building: () => [...sets.values()].some((record) => record.pending), building: () => [...sets.values()].some((record) => record.pending),
/** Each frame, before it draws: the horizon cull. */ /** Each frame, before it draws: the horizon cull. */
beforeRender() { beforeRender() {
followCameraHeight();
pulsing = runPulses(); pulsing = runPulses();
cullHorizon(); cullHorizon();
runFlows(); runFlows();
+73 -168
View File
@@ -508,7 +508,7 @@ test('hidden clamped fills wait for nothing, and the hidden ones it cannot build
set.set([ set.set([
fill('a', 0, false, { outline: '#000' }), fill('a', 0, false, { outline: '#000' }),
fill('b', 1, false, { extrudeHeight: 10 }), fill('b', 1, false, { extrudeHeight: 10 }),
fill('c', 2, false, { fill: { preset: 'radialRim' } }), fill('c', 2, false, { fill: { gradient: 'radial' } }),
]), ]),
); );
assert.equal(groundsIn(scene.added.at(-1)).length, 0); assert.equal(groundsIn(scene.added.at(-1)).length, 0);
@@ -596,57 +596,22 @@ test('clamped shapes refuse what they cannot draw', () => {
fill: '#fff', fill: '#fff',
height: 'clampGround', height: 'clampGround',
}; };
// A rim fill is drawn on ellipses alone. // A fill that is neither a colour nor an image.
assert.throws( assert.throws(
() => () => set.set([{ ...disc, fill: { gradient: 'radial' } }]),
set.set([
{
...disc,
geometry: {
kind: 'rectangle',
rect: { west: 0, south: 0, east: 1, north: 1 },
},
fill: {
preset: 'radialRim',
color: '#fff',
rimColor: '#fff',
rimWidth: 0.1,
},
},
]),
/colours only/, /colours only/,
); );
set.dispose(); set.dispose();
// Radii by camera height are for clamped ellipses alone.
const unclamped = draw.shapes({ id: 'refuse-unclamped' });
assert.throws(
() =>
unclamped.set([
{
...disc,
height: 'absolute',
geometry: {
...disc.geometry,
semiMajor: { byCameraHeight: { factor: 1, min: 1, max: 2 } },
},
},
]),
/radii by camera height on clamped ellipses only/,
);
unclamped.dispose();
}); });
test('a clamped ellipse with radii by camera height draws at the camera height and follows it', () => test('a clamped colour ring whose radius alone changes is drawn alone where it now is', () =>
withTerrainHeights(() => { withTerrainHeights(() => {
const scene = fakeScene(); const scene = fakeScene();
let height = 2000;
Object.defineProperty(scene.camera, 'positionCartographic', {
get: () => ({ height }),
});
const { draw, frame } = drawOver(scene); const { draw, frame } = drawOver(scene);
const set = draw.shapes({ id: 'rings' }); const set = draw.shapes({ id: 'rings' });
const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; // The app follows the camera's height and sends the radius it wants, as
const ring = (show = true) => ({ // annotation target rings do.
const ring = (radius, show = true) => ({
id: 'ring', id: 'ring',
geometry: { geometry: {
kind: 'ellipse', kind: 'ellipse',
@@ -658,115 +623,65 @@ test('a clamped ellipse with radii by camera height draws at the camera height a
height: 'clampGround', height: 'clampGround',
show, show,
}); });
set.set([ring()]); set.set([ring(60)]);
const host = scene.added[0]; const host = scene.added[0];
const radiusIn = (ground) => const radiusIn = (ground) =>
ground.geometryInstances[0].geometry._semiMajorAxis; ground.geometryInstances[0].geometry._semiMajorAxis;
const last = () => host.get(host.length - 1); const last = () => host.get(host.length - 1);
assert.equal(radiusIn(last()), 60, '3% of 2000 m'); assert.equal(radiusIn(last()), 60);
// The camera has not moved: nothing is built.
const built = last(); const built = last();
frame(); frame();
assert.equal(last(), built); assert.equal(last(), built, 'nothing built while nothing changes');
// It climbs: the ring is drawn wider in the frame that draws it, alone. // Wider: drawn alone, built in this frame, under its own pick id.
height = 4000; set.upsert([ring(120)]);
frame();
const wider = last(); const wider = last();
assert.notEqual(wider, built); assert.notEqual(wider, built);
assert.equal(wider.asynchronous, false); assert.equal(wider.asynchronous, false);
assert.equal(radiusIn(wider), 120); assert.equal(radiusIn(wider), 120);
assert.equal(wider.geometryInstances[0].id.id, 'ring', 'its own pick id'); assert.equal(wider.geometryInstances[0].id.id, 'ring', 'its own pick id');
// Held within its bounds. set.upsert([ring(14)]);
height = 1e6;
frame();
assert.equal(radiusIn(last()), 170);
height = 10;
frame();
assert.equal(radiusIn(last()), 14); assert.equal(radiusIn(last()), 14);
// Hidden, it waits; shown, it catches up.
set.upsert([ring(false)]);
const lastShown = last();
height = 3000;
frame();
assert.equal(last(), lastShown, 'hidden: not rebuilt');
set.upsert([ring(true)]);
frame();
assert.equal(radiusIn(last()), 90);
assert.equal(scene.added[0], host, 'never a rebuild of the set'); assert.equal(scene.added[0], host, 'never a rebuild of the set');
set.dispose(); set.dispose();
assert.equal(scene.added.length, 0); assert.equal(scene.added.length, 0);
})); }));
test('radii by camera height that cross draw the longer as the major axis; past the cap of shapes drawn alone, the set rebuilds', () => test('a semi-minor axis longer than the semi-major is drawn as the major axis, a quarter turn on', () =>
withTerrainHeights(() => { withTerrainHeights(() => {
const scene = fakeScene(); const scene = fakeScene();
let height = 1000; const { draw } = drawOver(scene);
Object.defineProperty(scene.camera, 'positionCartographic', {
get: () => ({ height }),
});
const { draw, frame } = drawOver(scene);
const set = draw.shapes({ id: 'crossing' }); const set = draw.shapes({ id: 'crossing' });
const ring = (id, lon) => ({ set.set([
id, {
geometry: { id: 'r',
kind: 'ellipse', geometry: {
center: { lon, lat: 0 }, kind: 'ellipse',
semiMajor: { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }, center: { lon: 0, lat: 0 },
semiMinor: { byCameraHeight: { factor: 0.05, min: 20, max: 100 } }, semiMajor: 30,
rotation: 0.25, semiMinor: 50,
rotation: 0.25,
},
fill: [0.5, 0.9, 1, 0.38],
height: 'clampGround',
}, },
fill: [0.5, 0.9, 1, 0.38], ]);
height: 'clampGround', const host = scene.added[0];
}); let ground = null;
const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => for (let i = 0; i < host.length; i++)
ring(`r${i}`, i * 0.1), if (host.get(i) instanceof Cesium.GroundPrimitive) ground = host.get(i);
); const geometry = ground.geometryInstances[0].geometry;
assert.doesNotThrow(() => set.set(rings)); assert.equal(geometry._semiMajorAxis, 50);
const first = scene.added[0];
const ground = (host) => {
for (let i = 0; i < host.length; i++)
if (host.get(i) instanceof Cesium.GroundPrimitive) return host.get(i);
return null;
};
const geometry = ground(first).geometryInstances[0].geometry;
assert.equal(geometry._semiMajorAxis, 50, 'the longer, 5% of 1000 m');
assert.equal(geometry._semiMinorAxis, 30); assert.equal(geometry._semiMinorAxis, 30);
assert.ok(Math.abs(geometry._rotation - (0.25 + Math.PI / 2)) < 1e-12); assert.ok(Math.abs(geometry._rotation - (0.25 + Math.PI / 2)) < 1e-12);
// Its batches built.
for (let i = 0; i < first.length; i++)
if (first.get(i) instanceof Cesium.GroundPrimitive) {
Object.defineProperty(first.get(i), 'ready', { value: true });
first.get(i).getGeometryInstanceAttributes = () => ({
show: new Uint8Array([1]),
});
}
frame();
// The camera climbs: no more than the cap are drawn alone; the set
// rebuilds for the rest, and nothing throws in the frame.
height = 1500;
assert.doesNotThrow(() => frame());
let solo = 0;
for (let i = 0; i < first.length; i++) {
const p = first.get(i);
if (p instanceof Cesium.GroundPrimitive && p.asynchronous === false)
solo += 1;
}
assert.equal(solo, MOVING_SHAPES);
assert.notEqual(scene.added.at(-1), first, 'rebuilt for the rest');
set.dispose(); set.dispose();
})); }));
test('rings drawn alone by a host still retiring count toward the cap when the camera moves again', () => test('rings that would be drawn alone past the cap rebuild their set, counting those a retiring host draws alone', () =>
withTerrainHeights(() => { withTerrainHeights(() => {
const scene = fakeScene(); const scene = fakeScene();
let height = 1000;
Object.defineProperty(scene.camera, 'positionCartographic', {
get: () => ({ height }),
});
const { draw, frame } = drawOver(scene); const { draw, frame } = drawOver(scene);
const set = draw.shapes({ id: 'climbing' }); const set = draw.shapes({ id: 'climbing' });
const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; const ring = (i, radius) => ({
const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => ({
id: `r${i}`, id: `r${i}`,
geometry: { geometry: {
kind: 'ellipse', kind: 'ellipse',
@@ -776,7 +691,9 @@ test('rings drawn alone by a host still retiring count toward the cap when the c
}, },
fill: [0.5, 0.9, 1, 0.38], fill: [0.5, 0.9, 1, 0.38],
height: 'clampGround', height: 'clampGround',
})); });
const all = (radius, from = 0, to = MOVING_SHAPES + 4) =>
Array.from({ length: to - from }, (_, k) => ring(from + k, radius));
const ready = (host) => { const ready = (host) => {
for (let i = 0; i < host.length; i++) for (let i = 0; i < host.length; i++)
if (host.get(i) instanceof Cesium.GroundPrimitive) { if (host.get(i) instanceof Cesium.GroundPrimitive) {
@@ -795,21 +712,22 @@ test('rings drawn alone by a host still retiring count toward the cap when the c
} }
return n; return n;
}; };
set.set(rings); set.set(all(30));
const first = scene.added[0]; const first = scene.added[0];
ready(first); ready(first);
frame(); frame();
// A climb: the cap drawn alone, and a rebuild for the rest. // The cap moves alone.
height = 1500; set.upsert(all(45, 0, MOVING_SHAPES));
frame();
assert.equal(solo(first), MOVING_SHAPES); assert.equal(solo(first), MOVING_SHAPES);
assert.equal(scene.added.at(-1), first);
// One more would pass it: the set rebuilds, the old host retiring.
set.upsert(all(45, MOVING_SHAPES));
const second = scene.added.at(-1); const second = scene.added.at(-1);
assert.notEqual(second, first, 'rebuilding, the old host retiring'); assert.notEqual(second, first, 'rebuilding, the old host retiring');
ready(second); ready(second);
// Climbing on while the old host retires: its rings drawn alone still // While the old host retires, its rings drawn alone still count, so
// count, so none more are drawn alone. // none more are drawn alone.
height = 2500; set.upsert([ring(0, 75)]);
frame();
assert.equal(solo(second), 0, 'nothing more drawn alone'); assert.equal(solo(second), 0, 'nothing more drawn alone');
set.dispose(); set.dispose();
})); }));
@@ -4224,12 +4142,7 @@ test('an unclamped shape filled with an image draws a textured primitive and fre
kind: 'rectangle', kind: 'rectangle',
rect: { west: 0, south: 0, east: 1, north: 1 }, rect: { west: 0, south: 0, east: 1, north: 1 },
}, },
fill: { fill: { gradient: 'radial' },
preset: 'radialRim',
color: '#fff',
rimColor: '#000',
rimWidth: 1,
},
}, },
]), ]),
/colours only/, /colours only/,
@@ -4564,7 +4477,7 @@ test('a line with a depth-fail colour draws it behind the surface, and moves in
widthPx: 2.5, widthPx: 2.5,
mode: 'geodesic', mode: 'geodesic',
style: { kind: 'solid', color: [1, 0, 1, 0.9] }, style: { kind: 'solid', color: [1, 0, 1, 0.9] },
depthFailColor: [1, 0, 1, 0.45], depthFail: { kind: 'solid', color: [1, 0, 1, 0.45] },
meta: height, meta: height,
...extra, ...extra,
}); });
@@ -4579,7 +4492,7 @@ test('a line with a depth-fail colour draws it behind the surface, and moves in
widthPx: 1, widthPx: 1,
mode: '3d', mode: '3d',
style: { kind: 'solid', color: '#fff' }, style: { kind: 'solid', color: '#fff' },
depthFailColor: null, depthFail: null,
}, },
]); ]);
const host = scene.added[0]; const host = scene.added[0];
@@ -4629,13 +4542,15 @@ test('a line with a depth-fail colour draws it behind the surface, and moves in
assert.equal(deep.length, 1); assert.equal(deep.length, 1);
assert.equal(deep.get(0).show, false, 'hidden as asked'); assert.equal(deep.get(0).show, false, 'hidden as asked');
// A new colour is a new look: rebuilt. // A new colour is a new look: rebuilt.
set.upsert([head(400, { depthFailColor: [1, 1, 1, 1] })]); set.upsert([
head(400, { depthFail: { kind: 'solid', color: [1, 1, 1, 1] } }),
]);
assert.notEqual(scene.added[0], host); assert.notEqual(scene.added[0], host);
set.dispose(); set.dispose();
assert.equal(scene.added.length, 0); assert.equal(scene.added.length, 0);
})); }));
test('a depth-fail dash dashes the parts behind the surface, in the depth-fail colour', () => test('a dashed depth-fail style dashes the parts behind the surface, in its colour', () =>
withImageClasses(() => { withImageClasses(() => {
const { scene, draw } = drawOver(); const { scene, draw } = drawOver();
const set = draw.lines({ id: 'band' }); const set = draw.lines({ id: 'band' });
@@ -4648,8 +4563,7 @@ test('a depth-fail dash dashes the parts behind the surface, in the depth-fail c
widthPx: 3, widthPx: 3,
mode: 'geodesic', mode: 'geodesic',
style: { kind: 'dash', color: [1, 1, 0, 0.9], length: 16 }, style: { kind: 'dash', color: [1, 1, 0, 0.9], length: 16 },
depthFailColor: [0, 1, 1, 0.35], depthFail: { kind: 'dash', color: [0, 1, 1, 0.35], length: 16 },
depthFailDash: { length: 16 },
...extra, ...extra,
}); });
set.set([band()]); set.set([band()]);
@@ -4666,21 +4580,27 @@ test('a depth-fail dash dashes the parts behind the surface, in the depth-fail c
assert.equal(hidden.uniforms.dashLength, 16); assert.equal(hidden.uniforms.dashLength, 16);
assert.equal(hidden.uniforms.dashPattern, 255, 'the default pattern'); assert.equal(hidden.uniforms.dashPattern, 255, 'the default pattern');
// A move keeps the dash; its fields in another order are the same look. // A move keeps the dash; its fields in another order are the same look.
set.upsert([band({ depthFailDash: { length: 16 } })]); set.upsert([
band({ depthFail: { length: 16, color: [0, 1, 1, 0.35], kind: 'dash' } }),
]);
assert.equal(scene.added[0], host, 'not rebuilt'); assert.equal(scene.added[0], host, 'not rebuilt');
assert.equal( assert.equal(
host.get(1).get(0).depthFailAppearance.material.type, host.get(1).get(0).depthFailAppearance.material.type,
'PolylineDash', 'PolylineDash',
); );
set.upsert([band({ depthFailDash: { pattern16: 0xf0f0, length: 8 } })]); const patternedBand = (fields) =>
band({ depthFail: { kind: 'dash', color: [0, 1, 1, 0.35], ...fields } });
set.upsert([patternedBand({ pattern16: 0xf0f0, length: 8 })]);
const patterned = scene.added[0].get(1).get(0).depthFailAppearance.material; const patterned = scene.added[0].get(1).get(0).depthFailAppearance.material;
assert.equal(patterned.uniforms.dashPattern, 0xf0f0); assert.equal(patterned.uniforms.dashPattern, 0xf0f0);
assert.equal(patterned.uniforms.dashLength, 8); assert.equal(patterned.uniforms.dashLength, 8);
const again = scene.added[0]; const again = scene.added[0];
set.upsert([band({ depthFailDash: { length: 8, pattern16: 0xf0f0 } })]); set.upsert([patternedBand({ length: 8, pattern16: 0xf0f0 })]);
assert.equal(scene.added[0], again, 'the same dash in another order'); assert.equal(scene.added[0], again, 'the same dash in another order');
// Without it the hidden parts are solid; the change is a new look. // Solid behind the surface: a new look.
set.upsert([band({ depthFailDash: undefined })]); set.upsert([
band({ depthFail: { kind: 'solid', color: [0, 1, 1, 0.35] } }),
]);
assert.notEqual(scene.added[0], host, 'rebuilt'); assert.notEqual(scene.added[0], host, 'rebuilt');
const solid = scene.added[0].get(1).get(0).depthFailAppearance.material; const solid = scene.added[0].get(1).get(0).depthFailAppearance.material;
assert.equal(solid.type, 'Color'); assert.equal(solid.type, 'Color');
@@ -5456,7 +5376,7 @@ test('where the scene cannot drape, an overlay line is culled by its whole arc,
], ],
widthPx: 2, widthPx: 2,
mode: '3d', mode: '3d',
depthFailColor: [1, 0, 0, 1], depthFail: { kind: 'solid', color: [1, 0, 0, 1] },
style: { kind: 'solid', color: [1, 0, 0, 1] }, style: { kind: 'solid', color: [1, 0, 0, 1] },
}, },
]); ]);
@@ -5615,7 +5535,7 @@ test('revealFraction reveals flow and depth-fail lines too, their clocks still r
widthPx: 2, widthPx: 2,
mode: '3d', mode: '3d',
style: { kind: 'solid', color: '#f0f' }, style: { kind: 'solid', color: '#f0f' },
depthFailColor: [1, 0, 1, 0.45], depthFail: { kind: 'solid', color: [1, 0, 1, 0.45] },
revealFraction: 0.5, revealFraction: 0.5,
}, },
]); ]);
@@ -6889,7 +6809,7 @@ test('a pattern line draws its image along it, repeated, and an inertial line tu
assert.equal(scene.added.length, 0); assert.equal(scene.added.length, 0);
})); }));
test('a clamped ellipse filled with a radial rim drapes its material, finely cut, pulled toward the eye', () => test('a clamped ellipse with an image fill drapes its material, finely cut so a round image runs round', () =>
withImageClasses(() => { withImageClasses(() => {
const { scene, draw } = drawOver(); const { scene, draw } = drawOver();
const set = draw.shapes({ id: 'pad-zone' }); const set = draw.shapes({ id: 'pad-zone' });
@@ -6901,14 +6821,8 @@ test('a clamped ellipse filled with a radial rim drapes its material, finely cut
semiMajor: 500, semiMajor: 500,
semiMinor: 500, semiMinor: 500,
}, },
fill: { fill: { image: 'zone.png' },
preset: 'radialRim',
color: [0.13, 0.9, 0.9, 0.105],
rimColor: [0.13, 0.9, 0.9, 0.72],
rimWidth: 0.033,
},
height: 'clampGround', height: 'clampGround',
depthBias: 1,
}; };
set.set([zone]); set.set([zone]);
const host = scene.added[0]; const host = scene.added[0];
@@ -6918,17 +6832,8 @@ test('a clamped ellipse filled with a radial rim drapes its material, finely cut
assert.ok(ground); assert.ok(ground);
const { appearance } = ground; const { appearance } = ground;
assert.ok(appearance instanceof Cesium.MaterialAppearance); assert.ok(appearance instanceof Cesium.MaterialAppearance);
assert.equal(appearance.material.type, 'DrawRadialRimFill'); assert.equal(appearance.material.type, 'Image');
const { color, rimColor, rimWidth } = appearance.material.uniforms; assert.equal(appearance.material.uniforms.image, 'zone.png');
assert.ok(
color.equalsEpsilon(new Cesium.Color(0.13, 0.9, 0.9, 0.105), 1e-9),
);
assert.ok(
rimColor.equalsEpsilon(new Cesium.Color(0.13, 0.9, 0.9, 0.72), 1e-9),
);
assert.equal(rimWidth, 0.033);
assert.equal(appearance.renderState.polygonOffset.enabled, true);
assert.equal(appearance.renderState.depthMask, false);
assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH);
const [instance] = ground.geometryInstances; const [instance] = ground.geometryInstances;
assert.ok(instance.geometry instanceof Cesium.EllipseGeometry); assert.ok(instance.geometry instanceof Cesium.EllipseGeometry);
+2 -2
View File
@@ -44,7 +44,7 @@ export const CESIUM_CHECKS = new Set([
'draw.field.windStreamlines', 'draw.field.windStreamlines',
'draw.icons.distance', 'draw.icons.distance',
'draw.icons.update', 'draw.icons.update',
'draw.lines.depthFailDash', 'draw.lines.depthFail',
'draw.lines.settled', 'draw.lines.settled',
'draw.lines.styles', 'draw.lines.styles',
'draw.lines.drape', 'draw.lines.drape',
@@ -65,7 +65,7 @@ export const CESIUM_CHECKS = new Set([
'draw.displayRange', 'draw.displayRange',
'draw.sets', 'draw.sets',
'draw.shapes.drapedRotation', 'draw.shapes.drapedRotation',
'draw.shapes.radiusByCameraHeight', 'draw.shapes.resize',
'effects.crossfade', 'effects.crossfade',
'effects.defineStyle', 'effects.defineStyle',
'effects.screenModulation', 'effects.screenModulation',
+20
View File
@@ -6,6 +6,12 @@
* reference recorder's own. * reference recorder's own.
*/ */
import { wheelLines } from '../input/wheel.js'; import { wheelLines } from '../input/wheel.js';
import {
eyeMoved,
eyeRotatedAbout,
eyeTurned,
eyeZoomed,
} from '../../geo/eyeMoves.js';
const NO_MODIFIERS = Object.freeze({ const NO_MODIFIERS = Object.freeze({
shift: false, shift: false,
@@ -187,6 +193,18 @@ function resolveArgs(driver, name, args) {
return args; return args;
} }
/**
* Script steps that are the app's own sums over the pose, not port verbs: the
* contract driver turns them into `setView`, where the reference recorder
* runs Cesium's matching camera functions.
*/
const EYE_STEPS = {
move: eyeMoved,
look: eyeTurned,
rotateAround: eyeRotatedAbout,
zoom: eyeZoomed,
};
/** /**
* A driver over a renderer, through the contract only. * A driver over a renderer, through the contract only.
* @param {import('../contract/renderer').Renderer} renderer * @param {import('../contract/renderer').Renderer} renderer
@@ -200,6 +218,8 @@ export function contractDriver(renderer, hooks) {
const camera = renderer.camera; const camera = renderer.camera;
return { return {
command(name, args) { command(name, args) {
if (Object.hasOwn(EYE_STEPS, name))
return camera.setView(EYE_STEPS[name](camera.pose(), ...args));
return camera[name](...args); return camera[name](...args);
}, },
frame: hooks.frame, frame: hooks.frame,
+1 -1
View File
@@ -253,7 +253,7 @@ export const CAMERA_SCRIPTS = Object.freeze([
}, },
{ do: 'move', args: ['forward', 500] }, { do: 'move', args: ['forward', 500] },
{ record: 'pose' }, { record: 'pose' },
{ do: 'rotateAround', args: [{ x: 0, y: 0, z: 1 }, 0.4] }, { do: 'look', args: ['left', 0.4] },
{ record: 'pose' }, { record: 'pose' },
{ do: 'zoom', args: [-1000] }, { do: 'zoom', args: [-1000] },
{ record: 'pose' }, { record: 'pose' },
+2 -1
View File
@@ -10,6 +10,7 @@ import {
} from '../cameraScripts.js'; } from '../cameraScripts.js';
import { contractDriver, runCameraScript } from '../cameraRunner.js'; import { contractDriver, runCameraScript } from '../cameraRunner.js';
import { deepEqual, equal, near, nearAngle, nearVec, ok } from '../expect.js'; import { deepEqual, equal, near, nearAngle, nearVec, ok } from '../expect.js';
import { eyeMoved } from '../../../geo/eyeMoves.js';
const lonLatToEcef = (h) => h.toEcef; const lonLatToEcef = (h) => h.toEcef;
@@ -389,7 +390,7 @@ export function cameraChecks() {
r.camera.on('moveEnd', () => events.push(['end', h.now(r)])); r.camera.on('moveEnd', () => events.push(['end', h.now(r)]));
await h.frame(r); await h.frame(r);
const movingAt = h.now(r); const movingAt = h.now(r);
r.camera.move('forward', 1000); r.camera.setView(eyeMoved(r.camera.pose(), 'forward', 1000));
await h.frame(r); await h.frame(r);
equal(events[0]?.[0], 'start', 'moveStart after the move'); equal(events[0]?.[0], 'start', 'moveStart after the move');
const movedAt = h.now(r); const movedAt = h.now(r);
+27 -32
View File
@@ -1714,7 +1714,7 @@ export function portChecks() {
}, },
), ),
check( check(
'draw.lines.depthFailDash', 'draw.lines.depthFail',
'a line dashed behind the surface draws, moves in place and changes back to solid', 'a line dashed behind the surface draws, moves in place and changes back to solid',
async (h, r) => { async (h, r) => {
await overAustin(h, r); await overAustin(h, r);
@@ -1727,8 +1727,7 @@ export function portChecks() {
widthPx: 3, widthPx: 3,
mode: 'geodesic', mode: 'geodesic',
style: { kind: 'dash', color: [1, 1, 0, 0.9], length: 16 }, style: { kind: 'dash', color: [1, 1, 0, 0.9], length: 16 },
depthFailColor: [0, 1, 1, 0.35], depthFail: { kind: 'dash', color: [0, 1, 1, 0.35], length: 16 },
depthFailDash: { length: 16 },
...extra, ...extra,
}); });
lines.set([band(-200)]); lines.set([band(-200)]);
@@ -1737,7 +1736,9 @@ export function portChecks() {
lines.upsert([band(-100)]); lines.upsert([band(-100)]);
await drawn(h, r); await drawn(h, r);
equal(lines.size(), 1, 'moved in place, not added'); equal(lines.size(), 1, 'moved in place, not added');
lines.upsert([band(-100, { depthFailDash: undefined })]); lines.upsert([
band(-100, { depthFail: { kind: 'solid', color: [0, 1, 1, 0.35] } }),
]);
await drawn(h, r); await drawn(h, r);
equal(lines.size(), 1, 'solid behind the surface again'); equal(lines.size(), 1, 'solid behind the surface again');
lines.dispose(); lines.dispose();
@@ -1877,24 +1878,21 @@ export function portChecks() {
}, },
), ),
check( check(
'draw.shapes.radiusByCameraHeight', 'draw.shapes.resize',
'a clamped ellipse with radii by camera height draws at the radius the camera height gives, held within its bounds, and follows the camera', 'a clamped ellipse whose radius alone is upserted draws at the new radius, growing and shrinking',
async (h, r) => { async (h, r) => {
const shapes = r.draw.shapes({ id: 'conf:rings' }); const shapes = r.draw.shapes({ id: 'conf:rings' });
const radius = { byCameraHeight: { factor: 0.1, min: 50, max: 600 } }; const ring = (radius) => ({
shapes.set([ id: 'ring',
{ geometry: {
id: 'ring', kind: 'ellipse',
geometry: { center: { lon: AUSTIN.lon, lat: AUSTIN.lat },
kind: 'ellipse', semiMajor: radius,
center: { lon: AUSTIN.lon, lat: AUSTIN.lat }, semiMinor: radius,
semiMajor: radius,
semiMinor: radius,
},
fill: [0.5, 0.9, 1, 0.6],
height: 'clampGround',
}, },
]); fill: [0.5, 0.9, 1, 0.6],
height: 'clampGround',
});
// Metres east of the centre, at its latitude. // Metres east of the centre, at its latitude.
const east = (m) => const east = (m) =>
h.toEcef({ h.toEcef({
@@ -1919,22 +1917,19 @@ export function portChecks() {
} }
return false; return false;
}; };
// 2000 m up: 200 m across its centre.
await overAustin(h, r, 2000);
ok(await until(() => covers(150)), 'at 2000 m it reaches 150 m');
ok(!covers(260), 'and not 260 m');
// 4000 m up: 400 m.
await overAustin(h, r, 4000); await overAustin(h, r, 4000);
shapes.set([ring(200)]);
ok(
await until(() => covers(150) && !covers(260)),
'at 200 m it reaches 150 m, not 260 m',
);
shapes.upsert([ring(400)]);
ok( ok(
await until(() => covers(300) && !covers(460)), await until(() => covers(300) && !covers(460)),
'at 4000 m it reaches 300 m, not 460 m', 'at 400 m it reaches 300 m, not 460 m',
);
// 20 km up: held at 600 m.
await overAustin(h, r, 20000);
ok(
await until(() => covers(550) && !covers(700)),
'held at its largest',
); );
shapes.upsert([ring(200)]);
ok(await until(() => covers(150) && !covers(260)), 'back at 200 m');
shapes.dispose(); shapes.dispose();
await drawn(h, r); await drawn(h, r);
ok(!covers(0), 'gone with its set'); ok(!covers(0), 'gone with its set');
@@ -1961,7 +1956,7 @@ export function portChecks() {
widthPx: 3, widthPx: 3,
mode: '3d', mode: '3d',
style: { kind: 'solid', color: '#ff00ff' }, style: { kind: 'solid', color: '#ff00ff' },
depthFailColor: [1, 0, 1, 0.45], depthFail: { kind: 'solid', color: [1, 0, 1, 0.45] },
}); });
lines.set([ lines.set([
{ {
+48 -48
View File
@@ -1117,29 +1117,29 @@
"kind": "pose", "kind": "pose",
"value": { "value": {
"position": { "position": {
"x": -744971.9139187913, "x": -744481.3426810508,
"y": -5464375.678277303, "y": -5464789.733339174,
"z": 3195735.7092693974 "z": 3195145.9335938734
}, },
"direction": { "direction": {
"x": 0.8577979868850266, "x": 0.3312543721140628,
"y": 0.50373228948861, "y": 0.7819390858650948,
"z": 0.10215867179324013 "z": 0.5280547385941896
}, },
"up": { "up": {
"x": 0.33601932677210566, "x": 0.22881921132251012,
"y": -0.6999992672201266, "y": -0.6095195427272047,
"z": 0.6301523926217426 "z": 0.7590307606173572
}, },
"right": { "right": {
"x": 0.38893910285752537, "x": 0.915375501903488,
"y": -0.5062161657018166, "y": -0.13060318920332545,
"z": -0.7697217470297525 "z": -0.38082869834724636
}, },
"heading": 1.099821436536688, "heading": 0.25083973344668564,
"pitch": -0.5003437292588502, "pitch": -0.45766939657173955,
"roll": 6.283185070682873, "roll": 0.20978125179289364,
"height": 1198.9411841126202, "height": 1198.941902759726,
"frameIsIdentity": false "frameIsIdentity": false
} }
}, },
@@ -1148,29 +1148,29 @@
"kind": "pose", "kind": "pose",
"value": { "value": {
"position": { "position": {
"x": -745829.7119056764, "x": -744812.5970531654,
"y": -5464879.410566793, "y": -5465571.672425042,
"z": 3195633.5505976044 "z": 3194617.878855279
}, },
"direction": { "direction": {
"x": 0.8577979868850265, "x": 0.33125437211406306,
"y": 0.5037322894886102, "y": 0.7819390858650948,
"z": 0.10215867179324012 "z": 0.5280547385941895
}, },
"up": { "up": {
"x": 0.33601932677210533, "x": 0.22881921132251018,
"y": -0.6999992672201268, "y": -0.6095195427272047,
"z": 0.6301523926217425 "z": 0.7590307606173573
}, },
"right": { "right": {
"x": 0.3889391028575255, "x": 0.9153755019034878,
"y": -0.5062161657018166, "y": -0.1306031892033257,
"z": -0.7697217470297526 "z": -0.38082869834724653
}, },
"heading": 1.0997500524431754, "heading": 0.2508194571959139,
"pitch": -0.5004811848386681, "pitch": -0.45781035725623687,
"roll": 6.283184976084162, "roll": 0.20978111856887782,
"height": 1678.7289113419563, "height": 1640.8642564622487,
"frameIsIdentity": false "frameIsIdentity": false
} }
}, },
@@ -1179,29 +1179,29 @@
"kind": "pose", "kind": "pose",
"value": { "value": {
"position": { "position": {
"x": -745829.7119056764, "x": -744812.5970531654,
"y": -5464879.410566793, "y": -5465571.672425042,
"z": 3195633.5505976044 "z": 3194617.878855279
}, },
"direction": { "direction": {
"x": 0.8577979868850266, "x": 0.3312543721140633,
"y": 0.5037322894886103, "y": 0.7819390858650948,
"z": 0.1021586717932402 "z": 0.5280547385941896
}, },
"up": { "up": {
"x": 0.33601932677210533, "x": 0.22881921132251018,
"y": -0.6999992672201268, "y": -0.6095195427272047,
"z": 0.6301523926217425 "z": 0.7590307606173573
}, },
"right": { "right": {
"x": 0.3889391028575255, "x": 0.9153755019034878,
"y": -0.5062161657018165, "y": -0.13060318920332578,
"z": -0.7697217470297525 "z": -0.3808286983472466
}, },
"heading": 1.0997500524431754, "heading": 0.2508194571959148,
"pitch": -0.5004811848386681, "pitch": -0.4578103572562373,
"roll": 6.283184976084162, "roll": 0.20978111856887693,
"height": 1678.7289113419563, "height": 1640.8642564622487,
"frameIsIdentity": true "frameIsIdentity": true
} }
} }
+7 -7
View File
@@ -208,6 +208,13 @@ export type CameraEvent =
export interface CameraPort { export interface CameraPort {
pose(): CameraPose; pose(): CameraPose;
/**
* Place the eye. A position with a `{direction, up}` orientation is placed
* exactly as given (`up` made square to `direction`), never rounded
* through heading, pitch and roll: the application's step moves (pans, turns, the
* globe turned under the eye, zooms; `geo/eyeMoves`) are such views,
* sent many times over.
*/
setView(view: ViewSpec): void; setView(view: ViewSpec): void;
setFov(fov: { vertical: number }): void; setFov(fov: { vertical: number }): void;
/** /**
@@ -236,13 +243,6 @@ export interface CameraPort {
lookAt(target: Ecef, offset: HeadingPitchRange): void; lookAt(target: Ecef, offset: HeadingPitchRange): void;
/** Leave `lookAt` for the world frame. */ /** Leave `lookAt` for the world frame. */
release(): void; release(): void;
move(
direction: 'forward' | 'back' | 'left' | 'right' | 'up' | 'down',
metres: number,
): void;
look(direction: 'left' | 'right' | 'up' | 'down', radians: number): void;
rotateAround(axis: Vec3, radians: number): void;
zoom(metres: number): void;
/** /**
* Follow `target`, or stop following with null; `followChanged` fires * Follow `target`, or stop following with null; `followChanged` fires
* whenever `followed` changes, and only then. * whenever `followed` changes, and only then.
+1 -1
View File
@@ -183,7 +183,7 @@ test('members added to version 0 later are optional, each behind its capability'
Object.fromEntries( Object.fromEntries(
members(checker.getTypeAtLocation(declared(shape).name)), members(checker.getTypeAtLocation(declared(shape).name)),
)[field]; )[field];
assert.equal(optional('LineItem', 'depthFailDash'), true); assert.equal(optional('LineItem', 'depthFail'), true);
// And on one kind of a union: the rectangle's rotation. // And on one kind of a union: the rectangle's rotation.
const rectangle = checker const rectangle = checker
.getTypeAtLocation(declared('ShapeGeometry').name) .getTypeAtLocation(declared('ShapeGeometry').name)
+18 -27
View File
@@ -212,15 +212,11 @@ export interface LineItem {
mode: '3d' | 'geodesic' | 'draped'; mode: '3d' | 'geodesic' | 'draped';
clampTo?: ClampTarget; clampTo?: ClampTarget;
style: LineStyle; style: LineStyle;
/** Colour where the line is behind the surface; `null` hides those parts. */
depthFailColor?: Color | null;
/** /**
* Dash the parts behind the surface, in `depthFailColor`, as a `dash` * How the parts behind the surface draw, solid or dashed; omitted or
* style's `length` and `pattern16` dash a line. Omitted, they are solid; a * `null` hides them. Ignored on draped lines, which are never behind it.
* renderer that predates it draws them solid too. Ignored without a
* `depthFailColor`, and on draped lines, which are never behind it.
*/ */
depthFailDash?: { length: number; pattern16?: number }; depthFail?: Extract<LineStyle, { kind: 'solid' | 'dash' }> | null;
/** Per-segment colours; changing them does not rebuild the line. */ /** Per-segment colours; changing them does not rebuild the line. */
segmentColors?: Color[]; segmentColors?: Color[];
segmentShow?: boolean[]; segmentShow?: boolean[];
@@ -233,25 +229,23 @@ export interface LineItem {
pickable?: boolean; pickable?: boolean;
} }
/** A shape's fill. */ /**
export type Fill = * A shape's fill: a colour, or an image stretched over the shape's extent
| Color * (`repeat` times across and up). A canvas image sent again with a new
| { image: ImageRef; repeat?: [number, number] } * `key` is new content.
| { preset: 'radialRim'; color: Color; rimColor: Color; rimWidth: number }; */
export type Fill = Color | { image: ImageRef; repeat?: [number, number] };
/** Declarative animation the renderer runs (no per-frame callbacks). */ /**
* Declarative animation the renderer runs (no per-frame callbacks): the
* fill's and outline's alpha swings between `from` and `to` and back every
* `periodMs`, forever.
*/
export interface Pulse { export interface Pulse {
property: 'radius' | 'alpha'; property: 'alpha';
from: number; from: number;
to: number; to: number;
periodMs: number; periodMs: number;
/** Repeat count; omitted repeats forever. */
repeat?: number;
}
/** A radius that follows the camera's height above the ground. */
export interface RadiusByCameraHeight {
byCameraHeight: { factor: number; min: number; max: number };
} }
export type ShapeGeometry = export type ShapeGeometry =
@@ -259,12 +253,11 @@ export type ShapeGeometry =
| { | {
kind: 'ellipse'; kind: 'ellipse';
center: Position; center: Position;
semiMajor: number | RadiusByCameraHeight; /** Metres. */
semiMinor: number | RadiusByCameraHeight; semiMajor: number;
semiMinor: number;
/** Radians counter-clockwise from north to the semi-major axis. */ /** Radians counter-clockwise from north to the semi-major axis. */
rotation?: number; rotation?: number;
/** Only part of the ellipse, radians from north. */
arc?: { start: number; end: number };
} }
/** /**
* `height`: metres above the ellipsoid, for a rectangle not clamped. * `height`: metres above the ellipsoid, for a rectangle not clamped.
@@ -292,8 +285,6 @@ export interface ShapeItem {
extrudeHeight?: number; extrudeHeight?: number;
height?: 'absolute' | 'clampGround'; height?: 'absolute' | 'clampGround';
clampTo?: ClampTarget; clampTo?: ClampTarget;
/** Pull toward the eye, metres, to win depth against coplanar surfaces. */
depthBias?: number;
/** /**
* Shaded by the renderer's fixed light (true) or flat colour (false). * Shaded by the renderer's fixed light (true) or flat colour (false).
* Omitted: lit for extruded shapes, flat otherwise. A renderer * Omitted: lit for extruded shapes, flat otherwise. A renderer
+2 -2
View File
@@ -46,8 +46,8 @@ export interface StyleDefinition extends StyleDescriptor {
* full inside the band, each by where its anchor is on screen; the map, * full inside the band, each by where its anchor is on screen; the map,
* lines and shapes draw as they are, and picks are unchanged. A radius of 0 * lines and shapes draw as they are, and picks are unchanged. A radius of 0
* dims every marker to `floor` (the theme on, the sweep off). Setting a * dims every marker to `floor` (the theme on, the sweep off). Setting a
* sector, or clearing it, asks for one frame; the app sets it again at * sector, or clearing it, asks for one frame; the application moves it about every
* `sonarCadenceHz`. * 80 ms while it sweeps.
* `diagnostics().passes` lists `'screenModulation'` while it draws, so a * `diagnostics().passes` lists `'screenModulation'` while it draws, so a
* sector set but not listed is unsupported. * sector set but not listed is unsupported.
*/ */
-5
View File
@@ -74,7 +74,6 @@ export const QUALITY_KEYS = Object.freeze([
'particles', 'particles',
'models', 'models',
'postFx', 'postFx',
'sonarCadenceHz',
'targetFps', 'targetFps',
]); ]);
@@ -174,10 +173,6 @@ export const PORTS = deepFreeze({
'flying', 'flying',
'lookAt', 'lookAt',
'release', 'release',
'move',
'look',
'rotateAround',
'zoom',
'follow', 'follow',
'followed', 'followed',
'followFramed', 'followFramed',
-2
View File
@@ -26,8 +26,6 @@ export interface QualitySettings {
models: { maxInstances: number; maxDistance: number }; models: { maxInstances: number; maxDistance: number };
/** Detail of the post-processing passes; bloom and sharpen are switched in `effects`. */ /** Detail of the post-processing passes; bloom and sharpen are switched in `effects`. */
postFx: 'low' | 'high'; postFx: 'low' | 'high';
/** Updates per second of a screen modulation sweep. */
sonarCadenceHz: number;
targetFps: number; targetFps: number;
} }
-46
View File
@@ -607,48 +607,6 @@ export function createStubCamera({
finishFlight('cancelled'); finishFlight('cancelled');
} }
function move(dir, metres) {
const axis = {
forward: direction,
back: negate(direction),
right,
left: negate(right),
up,
down: negate(up),
}[dir];
position = add(position, scale(axis, metres));
requestRender('camera');
}
function look(dir, radians) {
const [axis, sign] = {
left: [up, -1],
right: [up, 1],
up: [right, -1],
down: [right, 1],
}[dir];
const a = clone(axis);
const angle = -(sign * radians);
direction = rotate(direction, a, angle);
up = rotate(up, a, angle);
right = rotate(right, a, angle);
requestRender('camera');
}
function rotateAround(axis, radians) {
const a = normalize(axis);
position = rotate(position, a, -radians);
direction = rotate(direction, a, -radians);
up = rotate(up, a, -radians);
right = cross(direction, up);
up = cross(right, direction);
requestRender('camera');
}
function zoom(metres) {
move('forward', metres);
}
// --- Follow ---------------------------------------------------------------- // --- Follow ----------------------------------------------------------------
/** Where the target is drawn, for a drawn item; otherwise its own answer. */ /** Where the target is drawn, for a drawn item; otherwise its own answer. */
@@ -797,10 +755,6 @@ export function createStubCamera({
}, },
lookAt, lookAt,
release, release,
move,
look,
rotateAround,
zoom,
follow, follow,
get followed() { get followed() {
return followed; return followed;
+3 -19
View File
@@ -707,23 +707,11 @@ export function createStubRenderer(options = {}) {
); );
} }
/** The eye's height above the ellipsoid, for radii by camera height. */
const eyeHeight = () => toCartographicRadians(eye().position)?.height ?? 0;
/** /**
* Whether `lon`, `lat` (degrees) is in an ellipse geometry, its radii by * Whether `lon`, `lat` (degrees) is in an ellipse geometry, measured in
* camera height at the eye's height, measured in the plane tangent at its * the plane tangent at its centre.
* centre.
*/ */
function inEllipse(g, lon, lat) { function inEllipse(g, lon, lat) {
const height = eyeHeight();
const radius = (r) =>
typeof r === 'number'
? r
: Math.max(
r.byCameraHeight.min,
Math.min(r.byCameraHeight.max, height * r.byCameraHeight.factor),
);
const centre = toCartographicRadians(toEcef(g.center)); const centre = toCartographicRadians(toEcef(g.center));
const metresPerRadian = 6378137; const metresPerRadian = 6378137;
const east = const east =
@@ -735,11 +723,7 @@ export function createStubRenderer(options = {}) {
const turn = g.rotation ?? 0; const turn = g.rotation ?? 0;
const along = north * Math.cos(turn) - east * Math.sin(turn); const along = north * Math.cos(turn) - east * Math.sin(turn);
const across = north * Math.sin(turn) + east * Math.cos(turn); const across = north * Math.sin(turn) + east * Math.cos(turn);
return ( return (along / g.semiMajor) ** 2 + (across / g.semiMinor) ** 2 <= 1;
(along / radius(g.semiMajor)) ** 2 +
(across / radius(g.semiMinor)) ** 2 <=
1
);
} }
/** /**
+22
View File
@@ -107,8 +107,16 @@ export function bindFakeCesiumCamera(viewer, ports = {}) {
return fly.apply(this, args); return fly.apply(this, args);
}; };
const keepsFlight = '_currentFlight' in fake; const keepsFlight = '_currentFlight' in fake;
// The port places a view by direction and up on the camera's own vectors;
// a fake without them gets scratch ones, and the view is handed to its
// `setView` as Cesium's setView would have had it.
const placesOnSetView = !('position' in fake) && Boolean(fake.setView);
const placed = placesOnSetView
? { position: {}, direction: {}, up: {}, right: {} }
: null;
const camera = new Proxy(fake, { const camera = new Proxy(fake, {
get(target, key, receiver) { get(target, key, receiver) {
if (placed && Object.hasOwn(placed, key)) return placed[key];
if ((key === 'moveStart' || key === 'moveEnd') && !target[key]) if ((key === 'moveStart' || key === 'moveEnd') && !target[key])
return noEvent; return noEvent;
if (!keepsFlight) { if (!keepsFlight) {
@@ -175,6 +183,20 @@ export function bindFakeCesiumCamera(viewer, ports = {}) {
}; };
}, },
}, },
setView: {
value(spec) {
real.setView(spec);
const o = spec?.orientation;
if (placed && spec?.destination && o && 'direction' in o)
fake.setView({
destination: { ...placed.position },
orientation: {
direction: { ...placed.direction },
up: { ...placed.up },
},
});
},
},
// A fake that computes a view rectangle answers with it, as the // A fake that computes a view rectangle answers with it, as the
// renderer does; one that does not has none. // renderer does; one that does not has none.
viewRectangle: { viewRectangle: {
+12 -9
View File
@@ -76,17 +76,20 @@ export function nativeIntegrationFixture(t) {
positionCartographic: { height: state.height }, positionCartographic: { height: state.height },
moveEnd: { addEventListener() {} }, moveEnd: { addEventListener() {} },
cancelFlight() {}, cancelFlight() {},
zoomIn(metres) { // Looking straight down at the surface along -x.
position.x -= metres; directionWC: { x: -1, y: 0, z: 0 },
upWC: { x: 0, y: 0, z: 1 },
rightWC: { x: 0, y: 1, z: 0 },
setView({ destination }) {
const metres = position.x - destination.x;
position.x = destination.x;
state.height -= metres; state.height -= metres;
this.positionCartographic.height = state.height; this.positionCartographic.height = state.height;
state.zooms.push({ direction: 'in', metres }); state.zooms.push(
}, metres < 0
zoomOut(metres) { ? { direction: 'out', metres: -metres }
position.x += metres; : { direction: 'in', metres },
state.height += metres; );
this.positionCartographic.height = state.height;
state.zooms.push({ direction: 'out', metres });
}, },
}, },
scene: { scene: {
+7 -8
View File
@@ -55,14 +55,13 @@ function fixture({ holdFirst = false } = {}) {
positionCartographic: { height: 1000 }, positionCartographic: { height: 1000 },
moveEnd: { addEventListener() {} }, moveEnd: { addEventListener() {} },
cancelFlight() {}, cancelFlight() {},
zoomIn(n) { // Looking straight down at the surface along -x.
position.x -= n; directionWC: { x: -1, y: 0, z: 0 },
state.height -= n; upWC: { x: 0, y: 0, z: 1 },
this.positionCartographic.height = state.height; rightWC: { x: 0, y: 1, z: 0 },
}, setView({ destination }) {
zoomOut(n) { state.height -= position.x - destination.x;
position.x += n; position.x = destination.x;
state.height += n;
this.positionCartographic.height = state.height; this.positionCartographic.height = state.height;
}, },
}, },
+3 -2
View File
@@ -21,6 +21,7 @@ import {
toRadians, toRadians,
} from '../geo/index.js'; } from '../geo/index.js';
import { sphereFromPoints } from '../geo/sphere.js'; import { sphereFromPoints } from '../geo/sphere.js';
import { eyeZoomed } from '../geo/eyeMoves.js';
import { import {
cameraOf, cameraOf,
findCamera, findCamera,
@@ -3429,7 +3430,7 @@ function adjustCameraZoom(viewer, args) {
camera.cancelFlight(); camera.cancelFlight();
if (direction === 'out') { if (direction === 'out') {
camera.zoom(-movementM); camera.setView(eyeZoomed(before, -movementM));
} else { } else {
const safeMovementM = Math.min( const safeMovementM = Math.min(
movementM, movementM,
@@ -3444,7 +3445,7 @@ function adjustCameraZoom(viewer, args) {
error: 'Camera is already at the minimum target distance', error: 'Camera is already at the minimum target distance',
}; };
} }
camera.zoom(safeMovementM); camera.setView(eyeZoomed(before, safeMovementM));
} }
const after = camera.pose(); const after = camera.pose();
+7 -9
View File
@@ -184,15 +184,13 @@ function compositionFixture(
positionCartographic: { height: state.height }, positionCartographic: { height: state.height },
moveEnd: { addEventListener() {} }, moveEnd: { addEventListener() {} },
cancelFlight() {}, cancelFlight() {},
zoomIn(metres) { // Looking straight down at the surface along -x.
position.x -= metres; directionWC: { x: -1, y: 0, z: 0 },
state.height -= metres; upWC: { x: 0, y: 0, z: 1 },
this.positionCartographic.height = state.height; rightWC: { x: 0, y: 1, z: 0 },
state.zooms++; setView({ destination }) {
}, state.height -= position.x - destination.x;
zoomOut(metres) { position.x = destination.x;
position.x += metres;
state.height += metres;
this.positionCartographic.height = state.height; this.positionCartographic.height = state.height;
state.zooms++; state.zooms++;
}, },