From c8346c9fdadf6a35e6c08f330fe7b1dd1315279b Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 10 Nov 2026 04:08:41 -0800 Subject: [PATCH] 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. --- docs/CURRENT-STATE.md | 61 ++-- docs/RENDERER-CONTRACT.md | 12 +- scripts/package-boundaries.json | 3 + src/annotations/drawTool.js | 7 +- src/annotations/drawToolBehaviour.test.mjs | 7 +- src/annotations/worldAnnotationRenderer.js | 125 +++++++- .../worldAnnotationRenderer.test.mjs | 86 +++++- src/cameraVerbs.js | 9 +- src/cyberSonarScene.js | 26 +- src/cyberSonarScene.test.mjs | 24 +- src/data/cctvGizmo.js | 2 +- src/data/cctvGizmo.test.mjs | 2 +- src/data/trailRenderer.js | 2 +- src/data/trailRenderer.test.mjs | 7 +- src/geo/eyeMoves.js | 104 +++++++ src/layers/cctv/drawSets.js | 6 +- src/layers/cctv/drawSets.test.mjs | 4 +- src/layers/launches/launchPad.js | 78 ++++- src/layers/localAdsb/index.test.mjs | 4 +- src/layers/satellites/cockpitSubject.test.mjs | 11 +- src/layers/satellites/offCesium.test.mjs | 2 +- src/layers/satellites/rendering.js | 17 +- src/render/cesium/camera.js | 89 +++--- src/render/cesium/draw.js | 277 ++++-------------- src/render/cesium/draw.test.mjs | 241 +++++---------- src/render/cesium/harness.js | 4 +- src/render/conformance/cameraRunner.js | 20 ++ src/render/conformance/cameraScripts.js | 2 +- src/render/conformance/checks/camera.js | 3 +- src/render/conformance/checks/ports.js | 59 ++-- src/render/conformance/goldens/camera.json | 96 +++--- src/render/contract/camera.d.ts | 14 +- src/render/contract/contract.test.mjs | 2 +- src/render/contract/draw.d.ts | 45 ++- src/render/contract/effects.d.ts | 4 +- src/render/contract/index.js | 5 - src/render/contract/quality.d.ts | 2 - src/render/stub/camera.js | 46 --- src/render/stub/index.js | 22 +- src/testSupport/fakeCameraPort.mjs | 22 ++ src/testSupport/geminiIntegrationFixture.mjs | 21 +- src/voice/geminiNativeRecovery.test.mjs | 15 +- src/voice/gevActions.js | 5 +- src/voice/providerCommands.test.mjs | 16 +- 44 files changed, 810 insertions(+), 799 deletions(-) create mode 100644 src/geo/eyeMoves.js diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 81b77491d..a4a117c3b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1806,7 +1806,7 @@ time. TRACK ACQUIRED stays first. Then: left out (the satellites layer's bounded `getNearestPositions`, measured 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 - 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 one before. Riding stays in orbit: the satellites layer tracks the new 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. Gate: src/data/cctvTaiwan.test.mjs and src/data/cctvProxy.test.mjs. + ## DriveBC CCTV source pack 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 its criteria cannot be silently ignored. -| Layer | Source | File | Proxy | Update Interval | -| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| 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 | -| 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 | -| 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 | -| 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 | -| 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 | +| Layer | Source | File | Proxy | Update Interval | +| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| 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 | +| 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 | +| 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 | +| 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 | +| 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) | -| 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) | -| 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 | -| Datacenters ▣ | 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 | -| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×2 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | -| Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) | -| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | -| GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) | -| S2 GhostMaps 👻 (`s2-ghostmaps`) | S2 Underground's public GhostMaps repository on GitHub (KMZ intel products, keyless, CC BY-NC-SA 4.0) | `src/layers/ghostMaps/` via `src/app/layers/ghostMaps.js` | `/api/ghostmaps/catalog`, `/api/ghostmaps/events` (server-sent events), `/api/ghostmaps/file/{product}` | branch head checked every 15 s; new commits pushed to the page; 5 min catalog backstop | -| Sea Marks ⚓ (`sea-marks`) | OpenSeaMap seamark raster tiles (keyless; CC BY-SA 2.0 tiles, OSM data ODbL) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | -| Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | -| 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) | -| 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) | +| 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) | +| 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 | +| Datacenters ▣ | 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 | +| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×2 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | +| Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) | +| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | +| GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) | +| S2 GhostMaps 👻 (`s2-ghostmaps`) | S2 Underground's public GhostMaps repository on GitHub (KMZ intel products, keyless, CC BY-NC-SA 4.0) | `src/layers/ghostMaps/` via `src/app/layers/ghostMaps.js` | `/api/ghostmaps/catalog`, `/api/ghostmaps/events` (server-sent events), `/api/ghostmaps/file/{product}` | branch head checked every 15 s; new commits pushed to the page; 5 min catalog backstop | +| Sea Marks ⚓ (`sea-marks`) | OpenSeaMap seamark raster tiles (keyless; CC BY-SA 2.0 tiles, OSM data ODbL) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | +| Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) | +| 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) | +| 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 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. - **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. - **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. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index a22a9799f..f84b3fc96 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -78,9 +78,9 @@ optional, so a renderer written before it still conforms: - `camera.on('changed', cb, { threshold })` measures each listener by its own threshold under the capability `cameraChangeThreshold`; a renderer without it fires every `changed` listener at 0.5. -- A line item's `depthFailDash` (`{ length, pattern16? }`) dashes the parts - behind the surface in `depthFailColor`, as the Draw tool's rubber band is. - A renderer that predates it draws those parts solid. +- A line item's `depthFail` style, solid or dashed, draws the parts behind + the surface (the Draw tool's rubber band is dashed there too); without one + they are hidden. - A 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 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 `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 -and never batched), and `radialRim` fills on clamped ellipses (`rimWidth` a -fraction of the radius; `depthBias` pulls the fill toward the eye). A hidden +and never batched), and image fills on clamped ellipses, cut finely so a +round image (the launch pad zone's rim) runs round. A clamped colour fill +whose geometry alone changes (an annotation's target ring, resized as the +camera climbs) is drawn alone where it now is, in the same frame. A hidden line that cannot settle into a static batch leaves its polyline collection until it shows again, since the collection draws every line it holds. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 7489575b0..338c7ac5a 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3414,6 +3414,7 @@ "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", + "src/geo/eyeMoves.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/layers/flights/icons.js", @@ -4994,6 +4995,7 @@ "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", + "src/geo/eyeMoves.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/layers/flights/records.js", @@ -6900,6 +6902,7 @@ "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", + "src/geo/eyeMoves.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/render/stub/camera.js", diff --git a/src/annotations/drawTool.js b/src/annotations/drawTool.js index f4d3c16c8..ae0cdc9f5 100644 --- a/src/annotations/drawTool.js +++ b/src/annotations/drawTool.js @@ -217,8 +217,11 @@ export function initDrawTool({ length: 16, }, // Dashed behind the surface too, as the band in front of it is. - depthFailColor: withAlpha(cssColor(PREVIEW.primary), 0.35), - depthFailDash: { length: 16 }, + depthFail: { + kind: 'dash', + color: withAlpha(cssColor(PREVIEW.primary), 0.35), + length: 16, + }, }, ]); }; diff --git a/src/annotations/drawToolBehaviour.test.mjs b/src/annotations/drawToolBehaviour.test.mjs index d798242cc..d92850304 100644 --- a/src/annotations/drawToolBehaviour.test.mjs +++ b/src/annotations/drawToolBehaviour.test.mjs @@ -503,11 +503,10 @@ test('the rubber band follows the pointer, closes an area and takes the chosen c 'the band takes the colour', ); assert.deepEqual( - band().depthFailColor, - [139 / 255, 233 / 255, 1, 0.35], - 'behind the surface it stays the primary colour, as before', + band().depthFail, + { kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 }, + 'behind the surface it stays the primary colour, dashed, as before', ); - assert.deepEqual(band().depthFailDash, { length: 16 }, 'and dashed there'); assert.equal(band().style.kind, 'dash'); assert.equal(band().style.length, 16); assert.equal(band().widthPx, 3); diff --git a/src/annotations/worldAnnotationRenderer.js b/src/annotations/worldAnnotationRenderer.js index 1d73b05b5..dd4d802ae 100644 --- a/src/annotations/worldAnnotationRenderer.js +++ b/src/annotations/worldAnnotationRenderer.js @@ -2,7 +2,12 @@ import { recordWorkSlice } from '../sources/phaseTiming.js'; import { ringCentroid } from '../sources/featureGeometry.js'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.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'; /** @@ -22,7 +27,8 @@ import { heightsOf } from '../queries/heights.js'; * Fades follow the mark's alpha: the engine calls `sync` as it changes, and * each mark's items take their new colours where they are. Pulsing fills * are a declarative pulse the renderer runs; target rings follow the - * camera's height, 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 * the others' geometry alone. @@ -57,9 +63,23 @@ const PULSE_MS = (2 * Math.PI) / 0.005; const PULSE_LOW = 0.6; /** Target rings: 3% of the camera's height, between 14 m and 170 m. */ -const RING_RADIUS = Object.freeze({ - byCameraHeight: Object.freeze({ factor: 0.03, min: 14, max: 170 }), -}); +const RING_RADIUS = Object.freeze({ factor: 0.03, min: 14, max: 170 }); + +/** Relative change of the ring radius under which rings are not redrawn. */ +const RING_RESIZE = 1e-3; + +/** + * A target ring's radius, metres, for a camera `height` metres above the + * ellipsoid; 1000 m stands in for a height the camera cannot give. + * @param {number} height + */ +export function ringRadiusAt(height) { + const h = Number.isFinite(height) ? height : 1000; + return Math.max( + RING_RADIUS.min, + Math.min(RING_RADIUS.max, h * RING_RADIUS.factor), + ); +} /** * Each renderer's sets have ids of their own, unique across copies of this @@ -79,6 +99,56 @@ export function createWorldAnnotationRenderer(viewer) { const groundQueue = []; let offGroundFrame = null; let destroyed = false; + // Marks with a target ring, and the radius they are drawn at. + const ringed = new Set(); + let offRingFrame = null; + let ringRadius = ringRadiusAt(cameraHeight()); + + /** The camera's height above the ellipsoid, or NaN when it has none. */ + function cameraHeight() { + try { + return findCamera(viewer)?.pose().height ?? Number.NaN; + } catch { + return Number.NaN; + } + } + + /** The current ring radius, for the items that draw rings. */ + const ringRadiusNow = () => ringRadius; + + /** + * Before each frame: when the camera's height gives the rings another + * radius, every shown mark's ring is sent again at it. A hidden mark's + * ring catches up when it shows (`sync`). + */ + function followRings() { + const radius = ringRadiusAt(cameraHeight()); + if (Math.abs(radius - ringRadius) <= RING_RESIZE * ringRadius) return; + ringRadius = radius; + for (const anno of ringed) if (!anno.hidden) resizeRing(anno); + } + + /** Send a mark's ring again at the current radius, when it differs. */ + function resizeRing(anno) { + const was = anno._drawn; + const set = anno._draw?.shapes; + if (!was?.ring || !set || was.ringRadius === ringRadius) return; + was.ringRadius = ringRadius; + set.upsert([was.ring(was.alpha)]); + } + + /** + * Keep the ring frame listener while any mark has a ring. A host with no + * frame port draws its rings at the radius they were added with. + */ + function watchRings() { + if (ringed.size && !offRingFrame) + offRingFrame = findFrame(viewer)?.on('preRender', followRings) ?? null; + else if (!ringed.size && offRingFrame) { + offRingFrame(); + offRingFrame = null; + } + } const requestRender = () => frameOf(viewer).requestRender('annotations'); @@ -338,8 +408,18 @@ export function createWorldAnnotationRenderer(viewer) { return sampleBuilding(anno, options); } - const items = itemsOf(anno, options); - anno._drawn = { alpha: alphaOf(anno), items }; + // Rings not yet followed take the camera's height now. + if (!offRingFrame) ringRadius = ringRadiusAt(cameraHeight()); + const items = itemsOf(anno, options, ringRadiusNow); + anno._drawn = { + alpha: alphaOf(anno), + items, + ring: items.ring, + ringRadius, + }; + if (items.ring) ringed.add(anno); + else ringed.delete(anno); + watchRings(); const current = () => options.isCurrent?.() ?? true; const building = anno.footprintKind === 'building'; for (const kind of ['shapes', 'lines', 'points']) { @@ -394,6 +474,8 @@ export function createWorldAnnotationRenderer(viewer) { hideOsmCredit(viewer, anno); osmAnnotations.delete(anno); drawn.delete(anno); + ringed.delete(anno); + watchRings(); clearSets(anno); if (anno) { anno._draw = null; @@ -415,8 +497,13 @@ export function createWorldAnnotationRenderer(viewer) { if (sets[kind] && sets[kind].show !== show) sets[kind].show = show; const was = anno._drawn; 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.ringRadius = ringRadius; for (const kind of ['shapes', 'lines', 'points']) if (sets[kind] && was.items[kind].length) sets[kind].upsert(was.items[kind].map((item) => item(alpha))); @@ -428,6 +515,8 @@ export function createWorldAnnotationRenderer(viewer) { for (const task of [...pendingGround.values()]) task.finish('cancelled'); for (const anno of osmAnnotations) hideOsmCredit(viewer, anno); osmAnnotations.clear(); + ringed.clear(); + watchRings(); for (const anno of drawn) { clearSets(anno); 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: - * 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 shapes = []; const lines = []; const points = []; const meta = { annotation: anno.id }; + let ring = null; const draped = (id, positions, widthPx, style) => (alpha) => ({ id, positions, @@ -612,21 +703,23 @@ function itemsOf(anno, options) { } else { // pin / highlight / label — a camera-proportional target ring + a marker. const pos = { lon: anno.anchor.lon, lat: anno.anchor.lat }; - if (anno.type !== 'label') - shapes.push((alpha) => ({ + if (anno.type !== 'label') { + ring = (alpha) => ({ id: 'ring', geometry: { kind: 'ellipse', center: pos, - semiMajor: RING_RADIUS, - semiMinor: RING_RADIUS, + semiMajor: ringRadiusNow(), + semiMinor: ringRadiusNow(), }, fill: colour(base, 0.38 * alpha), animate: pulse(0.38 * alpha), height: 'clampGround', clampTo: CLAMP_TO, meta, - })); + }); + shapes.push(ring); + } // Captions belong to the hybrid renderer's screen-space callouts. points.push((alpha) => ({ id: 'marker', @@ -640,7 +733,7 @@ function itemsOf(anno, options) { meta, })); } - return { shapes, lines, points }; + return { shapes, lines, points, ring }; } /** `[lon, lat]` pairs as ECEF positions on the ellipsoid. */ diff --git a/src/annotations/worldAnnotationRenderer.test.mjs b/src/annotations/worldAnnotationRenderer.test.mjs index efefbf7b4..62e0b6574 100644 --- a/src/annotations/worldAnnotationRenderer.test.mjs +++ b/src/annotations/worldAnnotationRenderer.test.mjs @@ -8,29 +8,40 @@ import { bindRenderer } from '../render/rendererOf.js'; import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; 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 } = {}) { const draw = fakeDrawPort(); const frames = new Set(); + const before = new Set(); const v = { requests: 0 }; const frame = { on(phase, cb) { - if (phase !== 'postRender') return () => {}; - frames.add(cb); - return () => frames.delete(cb); + const listeners = + phase === 'postRender' ? frames : phase === 'preRender' ? before : null; + if (!listeners) return () => {}; + listeners.add(cb); + return () => listeners.delete(cb); }, requestRender() { v.requests += 1; }, }; + const camera = { height: 2000, pose: () => ({ height: camera.height }) }; const query = { sampleHeightNow: (point) => heights(point) }; - const unbind = bindRenderer(v, { draw, frame, query }); + const unbind = bindRenderer(v, { draw, frame, query, camera }); t.after(unbind); return { v, draw, frames, + before, + camera, 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'); - assert.deepEqual(ring.geometry.semiMajor, { - byCameraHeight: { factor: 0.03, min: 14, max: 170 }, - }); + assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height'); assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor); const [marker] = items(pin, 'points'); assert.deepEqual( @@ -232,6 +241,67 @@ test('every kind draws as it did: draped on terrain and tiles alike, rings by ca renderer.destroy(); }); +test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => { + const { v, draw, camera, preRender, before } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [, , pin] = marks(); + const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } }; + renderer.add(pin); + renderer.add(other); + const ringOf = (anno) => + setsOf(draw, anno) + .find((r) => r.kind === 'shapes') + .items.get('ring'); + // Writes to the rings' sets since they were drawn. + const shapeSets = [pin, other].map((anno) => + setsOf(draw, anno).find((r) => r.kind === 'shapes'), + ); + const upserts = { + get length() { + return shapeSets.reduce((n, record) => n + record.writes - 1, 0); + }, + }; + assert.equal(ringOf(pin).geometry.semiMajor, 60); + assert.equal(before.size, 1, 'one listener for every ring'); + // The camera has not moved: nothing is sent. + preRender(); + assert.equal(upserts.length, 0); + // It climbs: both rings are sent at the new radius, once. + camera.height = 4000; + preRender(); + preRender(); + assert.equal(upserts.length, 2); + assert.equal(ringOf(pin).geometry.semiMajor, 120); + assert.equal(ringOf(pin).geometry.semiMinor, 120); + assert.equal(ringOf(other).geometry.semiMajor, 120); + // A change under 0.1% sends nothing. + camera.height = 4002; + preRender(); + assert.equal(upserts.length, 2); + // Held within 14 m and 170 m. + camera.height = 1e6; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 170); + camera.height = 10; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 14); + // A hidden mark waits, and catches up when shown. + other.hidden = true; + renderer.sync(); + camera.height = 3000; + preRender(); + assert.equal(ringOf(pin).geometry.semiMajor, 90); + assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent'); + other.hidden = false; + renderer.sync(); + assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up'); + // The last ring gone, the listener goes with it. + renderer.remove(pin); + renderer.remove(other); + assert.equal(before.size, 0); + renderer.destroy(); +}); + test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => { const { v, draw, emit, frames } = viewer(t, { heights: () => 150 }); const renderer = createWorldAnnotationRenderer(v); diff --git a/src/cameraVerbs.js b/src/cameraVerbs.js index a8acdbb81..20a9d413d 100644 --- a/src/cameraVerbs.js +++ b/src/cameraVerbs.js @@ -67,6 +67,7 @@ import { toRadians, vec, } from './geo/index.js'; +import { eyeMoved, eyeRotatedAbout, eyeTurned } from './geo/eyeMoves.js'; import { heightsOf } from './queries/heights.js'; import { cameraOf, @@ -1083,7 +1084,7 @@ function lookWithinFrame(camera, m, look, angle) { if (allowed < owed) allowed = owed; 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. if (_lookBaseline) _lookBaseline.direction = camera.pose().direction; if (allowed < angle) interruptCameraMotion('globe-out-of-frame'); @@ -1343,7 +1344,9 @@ function onTick() { ? heightM * ONCE.panViewFraction * (scale - (m.lastScale || 0)) : heightM * PAN_VIEW_FRACTION_S[m.speed] * dt; 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') { tickTilt(camera, m, scale, dt); } else if (m.kind === 'rotate' || m.kind === 'rotate_globe') { @@ -1377,7 +1380,7 @@ function onTick() { interruptCameraMotion('globe-surface-limit'); return; } - camera.rotateAround(m.rotationAxis, angle); + camera.setView(eyeRotatedAbout(pose, m.rotationAxis, angle)); } else { lookWithinFrame( camera, diff --git a/src/cyberSonarScene.js b/src/cyberSonarScene.js index 68a80f997..75b21e78e 100644 --- a/src/cyberSonarScene.js +++ b/src/cyberSonarScene.js @@ -6,8 +6,8 @@ * 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; * 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 - * asks for a frame). Out of the theme the sector is cleared. + * draws anyway, and at least every `CYBER_SONAR_RENDER_INTERVAL_MS` (which + * 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 * once a sector is set, leaves markers as they are: the document's @@ -25,16 +25,8 @@ import { readCyberSonarSettings, syncCyberSonarAnimation, } from './cyberSonar.js'; -import { - canvasOf, - findEffects, - findFrame, - rendererOf, -} from './render/rendererOf.js'; +import { canvasOf, findEffects, findFrame } 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 = 'Contact GPU unavailable. Native contacts remain visible.'; @@ -54,14 +46,8 @@ export function createCyberSonarScene(viewer, manager) { let current = null; let key = null; let lastSetAt = Number.NEGATIVE_INFINITY; - let interval = CYBER_SONAR_RENDER_INTERVAL_MS; 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 support = failed ? 'unsupported' : 'supported'; if (root?.dataset && root.dataset.cyberSonarGpu !== support) @@ -120,11 +106,13 @@ export function createCyberSonarScene(viewer, manager) { const now = performance.now(); if ( next === key && - !(sweeping && (now - lastSetAt >= interval || t.rendering)) + !( + sweeping && + (now - lastSetAt >= CYBER_SONAR_RENDER_INTERVAL_MS || t.rendering) + ) ) return; key = next; - readCadence(); set(cyberSonarSector(width, height, now, { sweeping, root }), now); }); diff --git a/src/cyberSonarScene.test.mjs b/src/cyberSonarScene.test.mjs index 38b2da3f3..595964554 100644 --- a/src/cyberSonarScene.test.mjs +++ b/src/cyberSonarScene.test.mjs @@ -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 * each sector. */ -function fixture({ modulation = true, lists = true, cadenceHz } = {}) { +function fixture({ modulation = true, lists = true } = {}) { const previous = { document: globalThis.document, matchMedia: globalThis.matchMedia, @@ -137,7 +137,6 @@ function fixture({ modulation = true, lists = true, cadenceHz } = {}) { const unbind = bindRenderer(viewer, { canvas, effects, - quality: { get: () => (cadenceHz ? { sonarCadenceHz: cadenceHz } : {}) }, frame: { on(phase, cb) { 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', () => { const f = fixture({ lists: false }); try { diff --git a/src/data/cctvGizmo.js b/src/data/cctvGizmo.js index 0d9734932..1a865c873 100644 --- a/src/data/cctvGizmo.js +++ b/src/data/cctvGizmo.js @@ -294,7 +294,7 @@ export function createCalibrationGizmo({ // Standard gizmo convention: parts behind geometry stay clearly // visible, just dimmed (a street-level mount buries half the heading // 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, }); } diff --git a/src/data/cctvGizmo.test.mjs b/src/data/cctvGizmo.test.mjs index 200972499..8ea8976ef 100644 --- a/src/data/cctvGizmo.test.mjs +++ b/src/data/cctvGizmo.test.mjs @@ -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.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.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`); assert.equal(arrow.style.kind, 'arrow'); assert.equal(arrow.widthPx, 12); diff --git a/src/data/trailRenderer.js b/src/data/trailRenderer.js index f5eeb5a6d..af3e8e186 100644 --- a/src/data/trailRenderer.js +++ b/src/data/trailRenderer.js @@ -126,7 +126,7 @@ export function createTrail(viewer, { color, width = 2.5 }) { style: { kind: 'solid', color: colorAt(color, alpha) }, // The owner-locked rule (round 6): a segment below the photoreal // 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 }); lines.upsert([item]); diff --git a/src/data/trailRenderer.test.mjs b/src/data/trailRenderer.test.mjs index b89ecf242..917969a19 100644 --- a/src/data/trailRenderer.test.mjs +++ b/src/data/trailRenderer.test.mjs @@ -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.style.kind, 'solid'); 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. 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(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'); // No head: hidden once, then nothing more to write. trail.setHead(null); diff --git a/src/geo/eyeMoves.js b/src/geo/eyeMoves.js new file mode 100644 index 000000000..5b6eac8a3 --- /dev/null +++ b/src/geo/eyeMoves.js @@ -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); diff --git a/src/layers/cctv/drawSets.js b/src/layers/cctv/drawSets.js index c199d1d83..875ac1a07 100644 --- a/src/layers/cctv/drawSets.js +++ b/src/layers/cctv/drawSets.js @@ -32,7 +32,9 @@ function lineItemOf(handle) { style: handle.dashed ? { kind: 'dash', color, length: 16, pattern16: 255 } : { kind: 'solid', color }, - depthFailColor: handle.depthFailColor ?? null, + depthFail: handle.depthFailColor + ? { kind: 'solid', color: handle.depthFailColor } + : null, meta: { cameraId: handle.cameraId }, show: handle.show !== false, }; @@ -45,7 +47,7 @@ const lineKey = (item) => item.widthPx, item.style.kind, item.style.color.join(','), - item.depthFailColor ? item.depthFailColor.join(',') : '', + item.depthFail ? item.depthFail.color.join(',') : '', item.show, ].join('|'); diff --git a/src/layers/cctv/drawSets.test.mjs b/src/layers/cctv/drawSets.test.mjs index d17dc92d1..f4425957e 100644 --- a/src/layers/cctv/drawSets.test.mjs +++ b/src/layers/cctv/drawSets.test.mjs @@ -39,7 +39,7 @@ test('lines are written as they change, and drawn as their handles say', () => { widthPx: 1.2, mode: 'geodesic', style: { kind: 'solid', color: a.color }, - depthFailColor: null, + depthFail: null, meta: { cameraId: 'cam' }, show: true, }); @@ -58,7 +58,7 @@ test('lines are written as they change, and drawn as their handles say', () => { length: 16, 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('other:1:lines'), null); diff --git a/src/layers/launches/launchPad.js b/src/layers/launches/launchPad.js index a0afe0568..800f76930 100644 --- a/src/layers/launches/launchPad.js +++ b/src/layers/launches/launchPad.js @@ -10,11 +10,69 @@ const ZONE_FILL_ALPHA = 0.105; const ZONE_RIM_ALPHA = 0.72; /** The rim's width, a fraction of the zone's radius. */ 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 - * mesh at oblique angles, without a height that would float it. + * The zone's colour and alpha at `r`, a fraction of its radius from its + * 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({ state: layerState, @@ -39,9 +97,13 @@ export function createLaunchPad({ 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) { removeLaunchPadZonePrimitive(); + const image = launchPadZoneImage(); const item = { id: `rocket-pad-zone:${launch.id}`, geometry: { @@ -50,15 +112,9 @@ export function createLaunchPad({ semiMajor: LAUNCH_PAD_ZONE_RADIUS_M, semiMinor: LAUNCH_PAD_ZONE_RADIUS_M, }, - fill: { - preset: 'radialRim', - color: hexColor(ZONE_COLOR, ZONE_FILL_ALPHA), - rimColor: hexColor(ZONE_COLOR, ZONE_RIM_ALPHA), - rimWidth: ZONE_RIM_WIDTH, - }, + fill: image ? { image } : hexColor(ZONE_COLOR, ZONE_FILL_ALPHA), height: 'clampGround', clampTo: 'both', - depthBias: ZONE_DEPTH_BIAS_M, show: true, }; layerState._launchPadZoneItem = item; diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 5fa0fb2db..adec8a36d 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -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), }); assert.deepEqual( - head.depthFailColor, - hexColor('#ff4fd8', 0.45), + head.depthFail, + { kind: 'solid', color: hexColor('#ff4fd8', 0.45) }, 'dimmed, not hidden, behind the surface', ); assert.equal(head.positions.length, 2); diff --git a/src/layers/satellites/cockpitSubject.test.mjs b/src/layers/satellites/cockpitSubject.test.mjs index 00ad3223c..43c33230e 100644 --- a/src/layers/satellites/cockpitSubject.test.mjs +++ b/src/layers/satellites/cockpitSubject.test.mjs @@ -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. */ function ringColors(f, 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) => { @@ -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(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. assert.equal(f.state._points.get(COMPANION).show, true); diff --git a/src/layers/satellites/offCesium.test.mjs b/src/layers/satellites/offCesium.test.mjs index dd969a40e..5ffdd4575 100644 --- a/src/layers/satellites/offCesium.test.mjs +++ b/src/layers/satellites/offCesium.test.mjs @@ -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'); const ring = rings.items.get('25544'); 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.mode, 'geodesic'); assert.deepEqual([...ring.positions.slice(0, 3)], [7e6, 0, 0]); diff --git a/src/layers/satellites/rendering.js b/src/layers/satellites/rendering.js index 4ee3bc612..c8b658398 100644 --- a/src/layers/satellites/rendering.js +++ b/src/layers/satellites/rendering.js @@ -229,10 +229,10 @@ export function createRendering({ kind: 'solid', color: withAlpha(path.color, RING_ALPHA * factor), }; - path.item.depthFailColor = withAlpha( - path.color, - RING_BEHIND_ALPHA * factor, - ); + path.item.depthFail = { + kind: 'solid', + color: withAlpha(path.color, RING_BEHIND_ALPHA * factor), + }; sets?.rings.upsert([path.item]); return true; } @@ -460,7 +460,7 @@ export function createRendering({ /** * 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 - * behind it (`depthFailColor`), and turned with the Earth each + * behind it (`depthFail`), and turned with the Earth each * `RING_ROTATION_MS` (`_updateOrbitPathRotations`). */ @@ -494,7 +494,10 @@ export function createRendering({ // Along the ellipsoid between samples, as the ring always ran. mode: 'geodesic', 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, }; layerState._orbitPaths.set(noradId, path); @@ -521,7 +524,7 @@ export function createRendering({ * * No SGP4 here: WGS84 is rotationally symmetric about Z, so rotating the * 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. */ diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index 86f7f932c..e1558c9c5 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -38,25 +38,6 @@ export const EASINGS = Object.freeze({ 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. */ export function toDestination(d) { if ('rect' in d) { @@ -219,16 +200,60 @@ export function createCesiumCamera({ 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 = { on: (event, cb, options) => cameraEvents.on(event, cb, options), onCommand: (cb) => commandHooks.on(cb), setView(spec) { command('setView'); const d = spec.destination; - camera.setView({ - ...(d ? { destination: toDestination(d) } : {}), - orientation: toOrientation(spec.orientation), - }); + const o = spec.orientation; + // A view by direction and up at a point is placed as given: Cesium's + // 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(); }, flyTo(destination, options = {}) { @@ -314,24 +339,6 @@ export function createCesiumCamera({ camera.lookAtTransform(Cesium.Matrix4.IDENTITY); 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 }) { // Cesium would take a bad angle and draw a garbage projection. if (!(vertical > 0 && vertical < Math.PI)) diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index b5f33b933..1432993f3 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -189,40 +189,11 @@ czm_material czm_getMaterial(czm_materialInput materialInput) { 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 - * colour, easing into the rim's over `rimWidth` (a fraction of the - * radius) just inside a soft edge; the rim glows a little. + * How finely a clamped ellipse with an image fill is cut, radians, so an + * image's round edge (a zone's rim) runs round. */ -const RADIAL_RIM_SOURCE = ` -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, -}); +const IMAGE_ELLIPSE_GRANULARITY = Cesium.Math.toRadians(0.08); /** * 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; } -/** 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. * 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)); } -/** 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. */ 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])); /** - * A line not draped that has a `depthFailColor`: a primitive of its own, - * drawn in that colour where the surface hides it. Built at once, so one + * A line not draped that has a `depthFail` style: a primitive of its own, + * 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. * Null when its positions make no line. */ @@ -1961,18 +1899,7 @@ export function createCesiumDraw({ }), appearance: new Cesium.PolylineMaterialAppearance({ material }), depthFailAppearance: new Cesium.PolylineMaterialAppearance({ - material: lineMaterial( - record, - item.depthFailDash - ? { - kind: 'dash', - color: item.depthFailColor, - length: item.depthFailDash.length, - pattern16: item.depthFailDash.pattern16, - } - : { kind: 'solid', color: item.depthFailColor }, - reveal, - ), + material: lineMaterial(record, item.depthFail, reveal), }), show: item.show !== false, asynchronous: false, @@ -2080,7 +2007,7 @@ export function createCesiumDraw({ const line = { ...rest, mode: '3d', - depthFailColor: item.style.color, + depthFail: { kind: 'solid', color: item.style.color }, overlaid: true, }; if (segmentShow?.length) { @@ -2113,10 +2040,9 @@ export function createCesiumDraw({ 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). */ - const overlayShape = (item) => - lineLook({ ...item, depthFailColor: null }, true); + const overlayShape = (item) => lineLook({ ...item, depthFail: null }, true); /** Stop tracking a line no longer drawn over the surface for a draped * one. */ @@ -2191,11 +2117,20 @@ export function createCesiumDraw({ ); else if ( item.frame === 'inertial' && - (item.mode === 'draped' || item.depthFailColor) + (item.mode === 'draped' || item.depthFail) ) throw new Error( '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 ( segmented(item) && (item.mode !== 'draped' || @@ -2274,7 +2209,7 @@ export function createCesiumDraw({ draped.get(clampTo).push(drapedInstance(item, part, true)); continue; } - if (item.depthFailColor) { + if (item.depthFail) { deep ??= new Cesium.PrimitiveCollection(); const id = pickId(record, item); const primitive = depthFailLine(record, item, id); @@ -2418,10 +2353,14 @@ export function createCesiumDraw({ item.widthPx, item.clampTo, colourless ? { ...item.style, color: undefined } : item.style, - item.depthFailColor, - // A dash is drawn only with a depth-fail colour, the same in any key order. - item.depthFailColor && item.depthFailDash - ? [item.depthFailDash.length, item.depthFailDash.pattern16] + // The same depth-fail style in any key order. + item.depthFail + ? [ + item.depthFail.kind, + item.depthFail.color, + item.depthFail.length, + item.depthFail.pattern16, + ] : null, // Segment colours and shows change in place. item.segmentColors != null, @@ -2439,7 +2378,7 @@ export function createCesiumDraw({ Object.is(a.widthPx, b.widthPx) && a.clampTo === b.clampTo && a.style === b.style && - a.depthFailColor === b.depthFailColor && + a.depthFail === b.depthFail && (a.segmentColors != null) === (b.segmentColors != null) && (a.segmentShow != null) === (b.segmentShow != null) && revealed(a) === revealed(b) && @@ -2756,7 +2695,7 @@ export function createCesiumDraw({ const settles = (item) => item.mode !== 'draped' && item.frame !== 'inertial' && - !item.depthFailColor && + !item.depthFail && item.style.kind === 'solid' && !revealed(item) && // The collection draws no line under half a pixel wide; a batch @@ -3219,10 +3158,6 @@ export function createCesiumDraw({ }; } case 'ellipse': { - if (byCameraHeight(item)) - throw new Error( - 'the Cesium renderer takes radii by camera height on clamped ellipses only', - ); const ellipse = { center: toCartesian(g.center), 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 - * 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; switch (g.kind) { case 'polygon': { @@ -3373,21 +3229,19 @@ export function createCesiumDraw({ }); } case 'ellipse': { - // Radii by camera height are the ones it has at this frame's height. - const height = cameraHeight(); - const major = radiusAt(g.semiMajor, height); - const minor = radiusAt(g.semiMinor, height); - // Radii that follow the camera apart may cross: the longer is then - // drawn as Cesium's semi-major axis, a quarter turn on. + const major = g.semiMajor; + const minor = g.semiMinor; + // A semi-minor axis longer than the semi-major one is drawn as + // Cesium's semi-major axis, a quarter turn on. const crossed = minor > major; return new Cesium.EllipseGeometry({ center: toCartesian(g.center), semiMajorAxis: crossed ? minor : major, semiMinorAxis: crossed ? major : minor, rotation: (g.rotation ?? 0) + (crossed ? Math.PI / 2 : 0), - ...(rimFill + ...(imageFill ? { - granularity: RIM_GRANULARITY, + granularity: IMAGE_ELLIPSE_GRANULARITY, vertexFormat: Cesium.MaterialAppearance.MaterialSupport.TEXTURED .vertexFormat, @@ -3436,11 +3290,7 @@ export function createCesiumDraw({ typeof item.fill === 'object' && !Array.isArray(item.fill) ? item.fill : null; - const rimFill = - objectFill?.preset === 'radialRim' && item.geometry.kind === 'ellipse' - ? objectFill - : null; - const imageFill = rimFill ? null : objectFill; + const imageFill = objectFill; if (imageFill && !imageFill.image) throw new Error('the Cesium renderer fills shapes with colours only'); if (item.extrudeHeight !== undefined) @@ -3457,7 +3307,7 @@ export function createCesiumDraw({ // load when they show. let geometry; try { - geometry = groundGeometry(item, rimFill); + geometry = groundGeometry(item, Boolean(imageFill)); } catch (error) { if (item.show === false) continue; throw error; @@ -3466,8 +3316,6 @@ export function createCesiumDraw({ look: lookOf(item), id: pickId(record, item), ground: null, - // Radii by camera height as drawn (`followCameraHeight`). - radii: radiiOf(item), pulse: pulseOf(item), show: item.show !== false, }; @@ -3477,29 +3325,17 @@ export function createCesiumDraw({ ); const instance = new Cesium.GeometryInstance({ geometry, - attributes: - imageFill || rimFill - ? { show } - : { - color: Cesium.ColorGeometryInstanceAttribute.fromColor( - toColor(item.fill), - ), - show, - }, + attributes: imageFill + ? { show } + : { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.fill), + ), + show, + }, id: part.id, }); 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) { // An image fill is a ground primitive of its own, with its material. // (Cesium turns its texture wrongly across the antimeridian: its @@ -3540,9 +3376,7 @@ export function createCesiumDraw({ const grounds = batches.map((batch) => { const material = batch.imageFill ? imageMaterial(batch.image, batch.imageFill.repeat) - : batch.rimFill - ? radialRimMaterial(batch.rimFill) - : null; + : null; const ground = new Ground({ geometryInstances: batch.instances, classificationType: classificationOf(batch.clampTo), @@ -3555,15 +3389,6 @@ export function createCesiumDraw({ Cesium.MaterialAppearance.MaterialSupport.TEXTURED, translucent: 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.pendingShow = undefined; part.look = lookOf(item); - part.radii = radiiOf(item); part.pulse = pulseOf(item); part.show = item.show !== false; part.pendingColour = undefined; @@ -4344,7 +4168,6 @@ export function createCesiumDraw({ building: () => [...sets.values()].some((record) => record.pending), /** Each frame, before it draws: the horizon cull. */ beforeRender() { - followCameraHeight(); pulsing = runPulses(); cullHorizon(); runFlows(); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 6609b2e63..8e12a44b0 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -508,7 +508,7 @@ test('hidden clamped fills wait for nothing, and the hidden ones it cannot build set.set([ fill('a', 0, false, { outline: '#000' }), 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); @@ -596,57 +596,22 @@ test('clamped shapes refuse what they cannot draw', () => { fill: '#fff', height: 'clampGround', }; - // A rim fill is drawn on ellipses alone. + // A fill that is neither a colour nor an image. assert.throws( - () => - 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, - }, - }, - ]), + () => set.set([{ ...disc, fill: { gradient: 'radial' } }]), /colours only/, ); 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(() => { const scene = fakeScene(); - let height = 2000; - Object.defineProperty(scene.camera, 'positionCartographic', { - get: () => ({ height }), - }); const { draw, frame } = drawOver(scene); const set = draw.shapes({ id: 'rings' }); - const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; - const ring = (show = true) => ({ + // The app follows the camera's height and sends the radius it wants, as + // annotation target rings do. + const ring = (radius, show = true) => ({ id: 'ring', geometry: { kind: 'ellipse', @@ -658,115 +623,65 @@ test('a clamped ellipse with radii by camera height draws at the camera height a height: 'clampGround', show, }); - set.set([ring()]); + set.set([ring(60)]); const host = scene.added[0]; const radiusIn = (ground) => ground.geometryInstances[0].geometry._semiMajorAxis; const last = () => host.get(host.length - 1); - assert.equal(radiusIn(last()), 60, '3% of 2000 m'); - // The camera has not moved: nothing is built. + assert.equal(radiusIn(last()), 60); const built = last(); frame(); - assert.equal(last(), built); - // It climbs: the ring is drawn wider in the frame that draws it, alone. - height = 4000; - frame(); + assert.equal(last(), built, 'nothing built while nothing changes'); + // Wider: drawn alone, built in this frame, under its own pick id. + set.upsert([ring(120)]); const wider = last(); assert.notEqual(wider, built); assert.equal(wider.asynchronous, false); assert.equal(radiusIn(wider), 120); assert.equal(wider.geometryInstances[0].id.id, 'ring', 'its own pick id'); - // Held within its bounds. - height = 1e6; - frame(); - assert.equal(radiusIn(last()), 170); - height = 10; - frame(); + set.upsert([ring(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'); set.dispose(); 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(() => { const scene = fakeScene(); - let height = 1000; - Object.defineProperty(scene.camera, 'positionCartographic', { - get: () => ({ height }), - }); - const { draw, frame } = drawOver(scene); + const { draw } = drawOver(scene); const set = draw.shapes({ id: 'crossing' }); - const ring = (id, lon) => ({ - id, - geometry: { - kind: 'ellipse', - center: { lon, lat: 0 }, - semiMajor: { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }, - semiMinor: { byCameraHeight: { factor: 0.05, min: 20, max: 100 } }, - rotation: 0.25, + set.set([ + { + id: 'r', + geometry: { + kind: 'ellipse', + center: { lon: 0, lat: 0 }, + semiMajor: 30, + 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 rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => - ring(`r${i}`, i * 0.1), - ); - assert.doesNotThrow(() => set.set(rings)); - 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'); + ]); + const host = scene.added[0]; + let ground = null; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) ground = host.get(i); + const geometry = ground.geometryInstances[0].geometry; + assert.equal(geometry._semiMajorAxis, 50); assert.equal(geometry._semiMinorAxis, 30); 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(); })); -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(() => { const scene = fakeScene(); - let height = 1000; - Object.defineProperty(scene.camera, 'positionCartographic', { - get: () => ({ height }), - }); const { draw, frame } = drawOver(scene); const set = draw.shapes({ id: 'climbing' }); - const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; - const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => ({ + const ring = (i, radius) => ({ id: `r${i}`, geometry: { 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], height: 'clampGround', - })); + }); + const all = (radius, from = 0, to = MOVING_SHAPES + 4) => + Array.from({ length: to - from }, (_, k) => ring(from + k, radius)); const ready = (host) => { for (let i = 0; i < host.length; i++) 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; }; - set.set(rings); + set.set(all(30)); const first = scene.added[0]; ready(first); frame(); - // A climb: the cap drawn alone, and a rebuild for the rest. - height = 1500; - frame(); + // The cap moves alone. + set.upsert(all(45, 0, 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); assert.notEqual(second, first, 'rebuilding, the old host retiring'); ready(second); - // Climbing on while the old host retires: its rings drawn alone still - // count, so none more are drawn alone. - height = 2500; - frame(); + // While the old host retires, its rings drawn alone still count, so + // none more are drawn alone. + set.upsert([ring(0, 75)]); assert.equal(solo(second), 0, 'nothing more drawn alone'); set.dispose(); })); @@ -4224,12 +4142,7 @@ test('an unclamped shape filled with an image draws a textured primitive and fre kind: 'rectangle', rect: { west: 0, south: 0, east: 1, north: 1 }, }, - fill: { - preset: 'radialRim', - color: '#fff', - rimColor: '#000', - rimWidth: 1, - }, + fill: { gradient: 'radial' }, }, ]), /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, mode: 'geodesic', 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, ...extra, }); @@ -4579,7 +4492,7 @@ test('a line with a depth-fail colour draws it behind the surface, and moves in widthPx: 1, mode: '3d', style: { kind: 'solid', color: '#fff' }, - depthFailColor: null, + depthFail: null, }, ]); 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.get(0).show, false, 'hidden as asked'); // 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); set.dispose(); 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(() => { const { scene, draw } = drawOver(); 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, mode: 'geodesic', style: { kind: 'dash', color: [1, 1, 0, 0.9], length: 16 }, - depthFailColor: [0, 1, 1, 0.35], - depthFailDash: { length: 16 }, + depthFail: { kind: 'dash', color: [0, 1, 1, 0.35], length: 16 }, ...extra, }); 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.dashPattern, 255, 'the default pattern'); // 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( host.get(1).get(0).depthFailAppearance.material.type, '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; assert.equal(patterned.uniforms.dashPattern, 0xf0f0); assert.equal(patterned.uniforms.dashLength, 8); 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'); - // Without it the hidden parts are solid; the change is a new look. - set.upsert([band({ depthFailDash: undefined })]); + // Solid behind the surface: a new look. + set.upsert([ + band({ depthFail: { kind: 'solid', color: [0, 1, 1, 0.35] } }), + ]); assert.notEqual(scene.added[0], host, 'rebuilt'); const solid = scene.added[0].get(1).get(0).depthFailAppearance.material; 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, mode: '3d', - depthFailColor: [1, 0, 0, 1], + depthFail: { 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, mode: '3d', style: { kind: 'solid', color: '#f0f' }, - depthFailColor: [1, 0, 1, 0.45], + depthFail: { kind: 'solid', color: [1, 0, 1, 0.45] }, 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); })); -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(() => { const { scene, draw } = drawOver(); 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, semiMinor: 500, }, - fill: { - preset: 'radialRim', - color: [0.13, 0.9, 0.9, 0.105], - rimColor: [0.13, 0.9, 0.9, 0.72], - rimWidth: 0.033, - }, + fill: { image: 'zone.png' }, height: 'clampGround', - depthBias: 1, }; set.set([zone]); 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); const { appearance } = ground; assert.ok(appearance instanceof Cesium.MaterialAppearance); - assert.equal(appearance.material.type, 'DrawRadialRimFill'); - const { color, rimColor, rimWidth } = appearance.material.uniforms; - 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(appearance.material.type, 'Image'); + assert.equal(appearance.material.uniforms.image, 'zone.png'); assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); const [instance] = ground.geometryInstances; assert.ok(instance.geometry instanceof Cesium.EllipseGeometry); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index af5101530..6c25bfffc 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -44,7 +44,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.field.windStreamlines', 'draw.icons.distance', 'draw.icons.update', - 'draw.lines.depthFailDash', + 'draw.lines.depthFail', 'draw.lines.settled', 'draw.lines.styles', 'draw.lines.drape', @@ -65,7 +65,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.displayRange', 'draw.sets', 'draw.shapes.drapedRotation', - 'draw.shapes.radiusByCameraHeight', + 'draw.shapes.resize', 'effects.crossfade', 'effects.defineStyle', 'effects.screenModulation', diff --git a/src/render/conformance/cameraRunner.js b/src/render/conformance/cameraRunner.js index 400c9d74b..a5b9a1d69 100644 --- a/src/render/conformance/cameraRunner.js +++ b/src/render/conformance/cameraRunner.js @@ -6,6 +6,12 @@ * reference recorder's own. */ import { wheelLines } from '../input/wheel.js'; +import { + eyeMoved, + eyeRotatedAbout, + eyeTurned, + eyeZoomed, +} from '../../geo/eyeMoves.js'; const NO_MODIFIERS = Object.freeze({ shift: false, @@ -187,6 +193,18 @@ function resolveArgs(driver, name, 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. * @param {import('../contract/renderer').Renderer} renderer @@ -200,6 +218,8 @@ export function contractDriver(renderer, hooks) { const camera = renderer.camera; return { command(name, args) { + if (Object.hasOwn(EYE_STEPS, name)) + return camera.setView(EYE_STEPS[name](camera.pose(), ...args)); return camera[name](...args); }, frame: hooks.frame, diff --git a/src/render/conformance/cameraScripts.js b/src/render/conformance/cameraScripts.js index 8aa408c61..14dfa1f5f 100644 --- a/src/render/conformance/cameraScripts.js +++ b/src/render/conformance/cameraScripts.js @@ -253,7 +253,7 @@ export const CAMERA_SCRIPTS = Object.freeze([ }, { do: 'move', args: ['forward', 500] }, { record: 'pose' }, - { do: 'rotateAround', args: [{ x: 0, y: 0, z: 1 }, 0.4] }, + { do: 'look', args: ['left', 0.4] }, { record: 'pose' }, { do: 'zoom', args: [-1000] }, { record: 'pose' }, diff --git a/src/render/conformance/checks/camera.js b/src/render/conformance/checks/camera.js index 6a14d5dd7..ffd4787af 100644 --- a/src/render/conformance/checks/camera.js +++ b/src/render/conformance/checks/camera.js @@ -10,6 +10,7 @@ import { } from '../cameraScripts.js'; import { contractDriver, runCameraScript } from '../cameraRunner.js'; import { deepEqual, equal, near, nearAngle, nearVec, ok } from '../expect.js'; +import { eyeMoved } from '../../../geo/eyeMoves.js'; const lonLatToEcef = (h) => h.toEcef; @@ -389,7 +390,7 @@ export function cameraChecks() { r.camera.on('moveEnd', () => events.push(['end', h.now(r)])); await h.frame(r); const movingAt = h.now(r); - r.camera.move('forward', 1000); + r.camera.setView(eyeMoved(r.camera.pose(), 'forward', 1000)); await h.frame(r); equal(events[0]?.[0], 'start', 'moveStart after the move'); const movedAt = h.now(r); diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index cad4a3c53..2cb758031 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -1714,7 +1714,7 @@ export function portChecks() { }, ), check( - 'draw.lines.depthFailDash', + 'draw.lines.depthFail', 'a line dashed behind the surface draws, moves in place and changes back to solid', async (h, r) => { await overAustin(h, r); @@ -1727,8 +1727,7 @@ export function portChecks() { widthPx: 3, mode: 'geodesic', style: { kind: 'dash', color: [1, 1, 0, 0.9], length: 16 }, - depthFailColor: [0, 1, 1, 0.35], - depthFailDash: { length: 16 }, + depthFail: { kind: 'dash', color: [0, 1, 1, 0.35], length: 16 }, ...extra, }); lines.set([band(-200)]); @@ -1737,7 +1736,9 @@ export function portChecks() { lines.upsert([band(-100)]); await drawn(h, r); 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); equal(lines.size(), 1, 'solid behind the surface again'); lines.dispose(); @@ -1877,24 +1878,21 @@ export function portChecks() { }, ), check( - 'draw.shapes.radiusByCameraHeight', - 'a clamped ellipse with radii by camera height draws at the radius the camera height gives, held within its bounds, and follows the camera', + 'draw.shapes.resize', + 'a clamped ellipse whose radius alone is upserted draws at the new radius, growing and shrinking', async (h, r) => { const shapes = r.draw.shapes({ id: 'conf:rings' }); - const radius = { byCameraHeight: { factor: 0.1, min: 50, max: 600 } }; - shapes.set([ - { - id: 'ring', - geometry: { - kind: 'ellipse', - center: { lon: AUSTIN.lon, lat: AUSTIN.lat }, - semiMajor: radius, - semiMinor: radius, - }, - fill: [0.5, 0.9, 1, 0.6], - height: 'clampGround', + const ring = (radius) => ({ + id: 'ring', + geometry: { + kind: 'ellipse', + center: { lon: AUSTIN.lon, lat: AUSTIN.lat }, + semiMajor: radius, + semiMinor: radius, }, - ]); + fill: [0.5, 0.9, 1, 0.6], + height: 'clampGround', + }); // Metres east of the centre, at its latitude. const east = (m) => h.toEcef({ @@ -1919,22 +1917,19 @@ export function portChecks() { } 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); + 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( await until(() => covers(300) && !covers(460)), - 'at 4000 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', + 'at 400 m it reaches 300 m, not 460 m', ); + shapes.upsert([ring(200)]); + ok(await until(() => covers(150) && !covers(260)), 'back at 200 m'); shapes.dispose(); await drawn(h, r); ok(!covers(0), 'gone with its set'); @@ -1961,7 +1956,7 @@ export function portChecks() { widthPx: 3, mode: '3d', style: { kind: 'solid', color: '#ff00ff' }, - depthFailColor: [1, 0, 1, 0.45], + depthFail: { kind: 'solid', color: [1, 0, 1, 0.45] }, }); lines.set([ { diff --git a/src/render/conformance/goldens/camera.json b/src/render/conformance/goldens/camera.json index 3c14b6a32..de092ece2 100644 --- a/src/render/conformance/goldens/camera.json +++ b/src/render/conformance/goldens/camera.json @@ -1117,29 +1117,29 @@ "kind": "pose", "value": { "position": { - "x": -744971.9139187913, - "y": -5464375.678277303, - "z": 3195735.7092693974 + "x": -744481.3426810508, + "y": -5464789.733339174, + "z": 3195145.9335938734 }, "direction": { - "x": 0.8577979868850266, - "y": 0.50373228948861, - "z": 0.10215867179324013 + "x": 0.3312543721140628, + "y": 0.7819390858650948, + "z": 0.5280547385941896 }, "up": { - "x": 0.33601932677210566, - "y": -0.6999992672201266, - "z": 0.6301523926217426 + "x": 0.22881921132251012, + "y": -0.6095195427272047, + "z": 0.7590307606173572 }, "right": { - "x": 0.38893910285752537, - "y": -0.5062161657018166, - "z": -0.7697217470297525 + "x": 0.915375501903488, + "y": -0.13060318920332545, + "z": -0.38082869834724636 }, - "heading": 1.099821436536688, - "pitch": -0.5003437292588502, - "roll": 6.283185070682873, - "height": 1198.9411841126202, + "heading": 0.25083973344668564, + "pitch": -0.45766939657173955, + "roll": 0.20978125179289364, + "height": 1198.941902759726, "frameIsIdentity": false } }, @@ -1148,29 +1148,29 @@ "kind": "pose", "value": { "position": { - "x": -745829.7119056764, - "y": -5464879.410566793, - "z": 3195633.5505976044 + "x": -744812.5970531654, + "y": -5465571.672425042, + "z": 3194617.878855279 }, "direction": { - "x": 0.8577979868850265, - "y": 0.5037322894886102, - "z": 0.10215867179324012 + "x": 0.33125437211406306, + "y": 0.7819390858650948, + "z": 0.5280547385941895 }, "up": { - "x": 0.33601932677210533, - "y": -0.6999992672201268, - "z": 0.6301523926217425 + "x": 0.22881921132251018, + "y": -0.6095195427272047, + "z": 0.7590307606173573 }, "right": { - "x": 0.3889391028575255, - "y": -0.5062161657018166, - "z": -0.7697217470297526 + "x": 0.9153755019034878, + "y": -0.1306031892033257, + "z": -0.38082869834724653 }, - "heading": 1.0997500524431754, - "pitch": -0.5004811848386681, - "roll": 6.283184976084162, - "height": 1678.7289113419563, + "heading": 0.2508194571959139, + "pitch": -0.45781035725623687, + "roll": 0.20978111856887782, + "height": 1640.8642564622487, "frameIsIdentity": false } }, @@ -1179,29 +1179,29 @@ "kind": "pose", "value": { "position": { - "x": -745829.7119056764, - "y": -5464879.410566793, - "z": 3195633.5505976044 + "x": -744812.5970531654, + "y": -5465571.672425042, + "z": 3194617.878855279 }, "direction": { - "x": 0.8577979868850266, - "y": 0.5037322894886103, - "z": 0.1021586717932402 + "x": 0.3312543721140633, + "y": 0.7819390858650948, + "z": 0.5280547385941896 }, "up": { - "x": 0.33601932677210533, - "y": -0.6999992672201268, - "z": 0.6301523926217425 + "x": 0.22881921132251018, + "y": -0.6095195427272047, + "z": 0.7590307606173573 }, "right": { - "x": 0.3889391028575255, - "y": -0.5062161657018165, - "z": -0.7697217470297525 + "x": 0.9153755019034878, + "y": -0.13060318920332578, + "z": -0.3808286983472466 }, - "heading": 1.0997500524431754, - "pitch": -0.5004811848386681, - "roll": 6.283184976084162, - "height": 1678.7289113419563, + "heading": 0.2508194571959148, + "pitch": -0.4578103572562373, + "roll": 0.20978111856887693, + "height": 1640.8642564622487, "frameIsIdentity": true } } diff --git a/src/render/contract/camera.d.ts b/src/render/contract/camera.d.ts index 8a11ff7ef..2e3956a6c 100644 --- a/src/render/contract/camera.d.ts +++ b/src/render/contract/camera.d.ts @@ -208,6 +208,13 @@ export type CameraEvent = export interface CameraPort { 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; setFov(fov: { vertical: number }): void; /** @@ -236,13 +243,6 @@ export interface CameraPort { lookAt(target: Ecef, offset: HeadingPitchRange): void; /** Leave `lookAt` for the world frame. */ 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 * whenever `followed` changes, and only then. diff --git a/src/render/contract/contract.test.mjs b/src/render/contract/contract.test.mjs index e0b9f5bb5..f4fa9d700 100644 --- a/src/render/contract/contract.test.mjs +++ b/src/render/contract/contract.test.mjs @@ -183,7 +183,7 @@ test('members added to version 0 later are optional, each behind its capability' Object.fromEntries( members(checker.getTypeAtLocation(declared(shape).name)), )[field]; - assert.equal(optional('LineItem', 'depthFailDash'), true); + assert.equal(optional('LineItem', 'depthFail'), true); // And on one kind of a union: the rectangle's rotation. const rectangle = checker .getTypeAtLocation(declared('ShapeGeometry').name) diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index 4e82ab32f..89fd671e9 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -212,15 +212,11 @@ export interface LineItem { mode: '3d' | 'geodesic' | 'draped'; clampTo?: ClampTarget; 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` - * style's `length` and `pattern16` dash a line. Omitted, they are solid; a - * renderer that predates it draws them solid too. Ignored without a - * `depthFailColor`, and on draped lines, which are never behind it. + * How the parts behind the surface draw, solid or dashed; omitted or + * `null` hides them. Ignored on draped lines, which are never behind it. */ - depthFailDash?: { length: number; pattern16?: number }; + depthFail?: Extract | null; /** Per-segment colours; changing them does not rebuild the line. */ segmentColors?: Color[]; segmentShow?: boolean[]; @@ -233,25 +229,23 @@ export interface LineItem { pickable?: boolean; } -/** A shape's fill. */ -export type Fill = - | Color - | { image: ImageRef; repeat?: [number, number] } - | { preset: 'radialRim'; color: Color; rimColor: Color; rimWidth: number }; +/** + * A shape's fill: a colour, or an image stretched over the shape's extent + * (`repeat` times across and up). A canvas image sent again with a new + * `key` is new content. + */ +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 { - property: 'radius' | 'alpha'; + property: 'alpha'; from: number; to: 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 = @@ -259,12 +253,11 @@ export type ShapeGeometry = | { kind: 'ellipse'; center: Position; - semiMajor: number | RadiusByCameraHeight; - semiMinor: number | RadiusByCameraHeight; + /** Metres. */ + semiMajor: number; + semiMinor: number; /** Radians counter-clockwise from north to the semi-major axis. */ 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. @@ -292,8 +285,6 @@ export interface ShapeItem { extrudeHeight?: number; height?: 'absolute' | 'clampGround'; 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). * Omitted: lit for extruded shapes, flat otherwise. A renderer diff --git a/src/render/contract/effects.d.ts b/src/render/contract/effects.d.ts index 0795e2d5e..b5037f85f 100644 --- a/src/render/contract/effects.d.ts +++ b/src/render/contract/effects.d.ts @@ -46,8 +46,8 @@ export interface StyleDefinition extends StyleDescriptor { * 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 * 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 - * `sonarCadenceHz`. + * sector, or clearing it, asks for one frame; the application moves it about every + * 80 ms while it sweeps. * `diagnostics().passes` lists `'screenModulation'` while it draws, so a * sector set but not listed is unsupported. */ diff --git a/src/render/contract/index.js b/src/render/contract/index.js index 76c36b507..84c69b9d1 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -74,7 +74,6 @@ export const QUALITY_KEYS = Object.freeze([ 'particles', 'models', 'postFx', - 'sonarCadenceHz', 'targetFps', ]); @@ -174,10 +173,6 @@ export const PORTS = deepFreeze({ 'flying', 'lookAt', 'release', - 'move', - 'look', - 'rotateAround', - 'zoom', 'follow', 'followed', 'followFramed', diff --git a/src/render/contract/quality.d.ts b/src/render/contract/quality.d.ts index 0582a4076..25be02638 100644 --- a/src/render/contract/quality.d.ts +++ b/src/render/contract/quality.d.ts @@ -26,8 +26,6 @@ export interface QualitySettings { models: { maxInstances: number; maxDistance: number }; /** Detail of the post-processing passes; bloom and sharpen are switched in `effects`. */ postFx: 'low' | 'high'; - /** Updates per second of a screen modulation sweep. */ - sonarCadenceHz: number; targetFps: number; } diff --git a/src/render/stub/camera.js b/src/render/stub/camera.js index d887cba99..b28a14622 100644 --- a/src/render/stub/camera.js +++ b/src/render/stub/camera.js @@ -607,48 +607,6 @@ export function createStubCamera({ 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 ---------------------------------------------------------------- /** Where the target is drawn, for a drawn item; otherwise its own answer. */ @@ -797,10 +755,6 @@ export function createStubCamera({ }, lookAt, release, - move, - look, - rotateAround, - zoom, follow, get followed() { return followed; diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 40bf6821e..e0e0ba0ac 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -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 - * camera height at the eye's height, measured in the plane tangent at its - * centre. + * Whether `lon`, `lat` (degrees) is in an ellipse geometry, measured in + * the plane tangent at its centre. */ 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 metresPerRadian = 6378137; const east = @@ -735,11 +723,7 @@ export function createStubRenderer(options = {}) { const turn = g.rotation ?? 0; const along = north * Math.cos(turn) - east * Math.sin(turn); const across = north * Math.sin(turn) + east * Math.cos(turn); - return ( - (along / radius(g.semiMajor)) ** 2 + - (across / radius(g.semiMinor)) ** 2 <= - 1 - ); + return (along / g.semiMajor) ** 2 + (across / g.semiMinor) ** 2 <= 1; } /** diff --git a/src/testSupport/fakeCameraPort.mjs b/src/testSupport/fakeCameraPort.mjs index 0ec70934c..6e7852e43 100644 --- a/src/testSupport/fakeCameraPort.mjs +++ b/src/testSupport/fakeCameraPort.mjs @@ -107,8 +107,16 @@ export function bindFakeCesiumCamera(viewer, ports = {}) { return fly.apply(this, args); }; 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, { get(target, key, receiver) { + if (placed && Object.hasOwn(placed, key)) return placed[key]; if ((key === 'moveStart' || key === 'moveEnd') && !target[key]) return noEvent; 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 // renderer does; one that does not has none. viewRectangle: { diff --git a/src/testSupport/geminiIntegrationFixture.mjs b/src/testSupport/geminiIntegrationFixture.mjs index 5e18fc811..75c52fdc8 100644 --- a/src/testSupport/geminiIntegrationFixture.mjs +++ b/src/testSupport/geminiIntegrationFixture.mjs @@ -76,17 +76,20 @@ export function nativeIntegrationFixture(t) { positionCartographic: { height: state.height }, moveEnd: { addEventListener() {} }, cancelFlight() {}, - zoomIn(metres) { - position.x -= metres; + // Looking straight down at the surface along -x. + 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; this.positionCartographic.height = state.height; - state.zooms.push({ direction: 'in', metres }); - }, - zoomOut(metres) { - position.x += metres; - state.height += metres; - this.positionCartographic.height = state.height; - state.zooms.push({ direction: 'out', metres }); + state.zooms.push( + metres < 0 + ? { direction: 'out', metres: -metres } + : { direction: 'in', metres }, + ); }, }, scene: { diff --git a/src/voice/geminiNativeRecovery.test.mjs b/src/voice/geminiNativeRecovery.test.mjs index 90685bdc5..37a28cdd7 100644 --- a/src/voice/geminiNativeRecovery.test.mjs +++ b/src/voice/geminiNativeRecovery.test.mjs @@ -55,14 +55,13 @@ function fixture({ holdFirst = false } = {}) { positionCartographic: { height: 1000 }, moveEnd: { addEventListener() {} }, cancelFlight() {}, - zoomIn(n) { - position.x -= n; - state.height -= n; - this.positionCartographic.height = state.height; - }, - zoomOut(n) { - position.x += n; - state.height += n; + // Looking straight down at the surface along -x. + directionWC: { x: -1, y: 0, z: 0 }, + upWC: { x: 0, y: 0, z: 1 }, + rightWC: { x: 0, y: 1, z: 0 }, + setView({ destination }) { + state.height -= position.x - destination.x; + position.x = destination.x; this.positionCartographic.height = state.height; }, }, diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 3460e8c20..4b8b1a77e 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -21,6 +21,7 @@ import { toRadians, } from '../geo/index.js'; import { sphereFromPoints } from '../geo/sphere.js'; +import { eyeZoomed } from '../geo/eyeMoves.js'; import { cameraOf, findCamera, @@ -3429,7 +3430,7 @@ function adjustCameraZoom(viewer, args) { camera.cancelFlight(); if (direction === 'out') { - camera.zoom(-movementM); + camera.setView(eyeZoomed(before, -movementM)); } else { const safeMovementM = Math.min( movementM, @@ -3444,7 +3445,7 @@ function adjustCameraZoom(viewer, args) { error: 'Camera is already at the minimum target distance', }; } - camera.zoom(safeMovementM); + camera.setView(eyeZoomed(before, safeMovementM)); } const after = camera.pose(); diff --git a/src/voice/providerCommands.test.mjs b/src/voice/providerCommands.test.mjs index 561cfae1c..959dd8a02 100644 --- a/src/voice/providerCommands.test.mjs +++ b/src/voice/providerCommands.test.mjs @@ -184,15 +184,13 @@ function compositionFixture( positionCartographic: { height: state.height }, moveEnd: { addEventListener() {} }, cancelFlight() {}, - zoomIn(metres) { - position.x -= metres; - state.height -= metres; - this.positionCartographic.height = state.height; - state.zooms++; - }, - zoomOut(metres) { - position.x += metres; - state.height += metres; + // Looking straight down at the surface along -x. + directionWC: { x: -1, y: 0, z: 0 }, + upWC: { x: 0, y: 0, z: 1 }, + rightWC: { x: 0, y: 1, z: 0 }, + setView({ destination }) { + state.height -= position.x - destination.x; + position.x = destination.x; this.positionCartographic.height = state.height; state.zooms++; },