Compare commits

..
Author SHA1 Message Date
Said Turksever 48ef645d65 Merge #689 (adsbdb rate limit and cache ceiling) onto current main 2026-11-23 01:20:39 +00:00
daika 28c9c4d730 test(adsbdb): give the Flights retry case the services enrichment now reads 2026-11-10 15:51:42 +07:00
daika ec90e98d61 Merge branch 'main' into fix/adsbdb-cache-and-rate-limit
# Conflicts:
#	src/layers/flights/enrichment.js
2026-11-10 15:46:59 +07:00
daika 94e3d01d75 Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit 2026-11-09 17:55:51 +07:00
daikaginza 9aa71cdfeb Merge upstream main 9d3548c27 into fix/adsbdb-cache-and-rate-limit
# Conflicts:
#	scripts/format-scope.json
2026-10-24 13:19:58 +07:00
daikaginza 80b2ead154 fix(adsbdb): 720/min by default, configurable, and a 429 is not an answer
The cap becomes GEV_RATELIMIT_ADSBDB_PER_MIN with a 720 default, read
through resolvePerMinuteCap like the other cost limiters (0 disables, an
unreadable value takes the default). On a 429 both enrichment queues make
the key askable again after the error's retry-after, so the next request
for that aircraft is dispatched instead of dropped.
2026-10-23 12:39:32 +07:00
daikaginza b83e1a2c98 test(adsbdb): size the limiter for two client queues and retry a 429
Review on #689: one tab runs two enrichment queues (Flights and Local
ADS-B) at 200 ms each, so a real session reaches 600/min, not 300; and a
429 left the aircraft's metadata empty for the session, because both
queues mark a key seen before dispatch and swallow the error. The cases
pin 600/min fitting, the GEV_RATELIMIT_ADSBDB_PER_MIN override (0 off),
and both queues asking again after the refusal. Four fail on the branch
as it stands.
2026-10-23 12:39:32 +07:00
daikaginza ed1e2771a0 Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit 2026-10-23 12:35:03 +07:00
daikaginza 7fa3e5e7bf docs(changelog): move the entry into a changelog.d fragment
Main now takes pending entries as changelog.d/<pr>-<slug>.md
files (#787), so the entry leaves CHANGELOG.md for changelog.d/689-adsbdb-cache-and-rate-limit.md.
2026-10-18 13:36:07 +07:00
daikaginza fbd99dad7c Merge upstream/main 93ea088f4 2026-10-18 13:36:07 +07:00
daikaginza c20af07adb Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit
main now reads adsbdb bodies through readResponseJsonCapped. That capped
payload feeds this branch's bounded store via remember(), so both the size cap
and the entry cap apply.
2026-10-16 09:26:47 +07:00
daikaginza 0bd8e9a62c Merge remote-tracking branch 'upstream/main' into q689
# Conflicts:
#	CHANGELOG.md
#	scripts/format-scope.json
2026-10-05 17:31:29 +07:00
daikaginza 0d5a0cdf49 Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit 2026-09-28 08:50:12 +07:00
daikaginza 03814d8c47 fix(adsbdb): rate-limit /api/adsbdb and cap its enrichment caches
Both keys this route accepts come from the caller — a callsign is 2-8 of
[A-Z0-9], a hex is six of [0-9a-f] — and every distinct key that reached
upstream was cached, 404s included, with nothing ever removing one. A caller
walking the keyspace could therefore drive unlimited live requests at the free
community API and grow `.gev-cache/adsbdb.json` without end.

Admit 360 requests/minute per client address, global backstop 3x, refusing the
rest with 429 and `Retry-After` before any cache, disk or upstream work. The
browser cannot exceed 300/min by construction: ENRICH_DISPATCH_GAP_MS is
200 ms, so the enrichment queue drips at most five lookups a second.

Hold each store to 20,000 entries, dropping least-recently-written first, and
discard entries past the existing 24-hour TTL when the file is read back. A
cache file above 16 MB is skipped rather than parsed. Sized from a real
session's own file: 397 aircraft entries (~100 B) and 3 route entries
(~231 B), so the ceiling is about fifty times an ordinary working set and
bounds the file at roughly 7 MB.

The two stores become Maps: `size` is O(1), so the ceiling can be enforced on
every write, and iteration is true insertion order — an all-digit callsign
like "1234" sorts ahead of everything else as an object key. The on-disk JSON
shape is unchanged.

Refs #261
2026-09-27 22:23:55 +07:00
49 changed files with 680 additions and 3561 deletions

No files matched your search

+6
View File
@@ -51,6 +51,12 @@ GOOGLE_MAPS_SERVER_API_KEY=
# Quotas).
# GEV_RATELIMIT_GOOGLE_PER_MIN=60 # uncomment to tighten from the default 120
# Optional: per-IP requests/minute for the keyless adsbdb aircraft-enrichment
# proxy (/api/adsbdb). DEFAULTS TO 720: one tab's two enrichment queues
# (Flights and Local ADS-B) top out at 600. Same rules as above: 0 disables,
# an unreadable value takes the default.
# GEV_RATELIMIT_ADSBDB_PER_MIN=720
# Optional: Google Photorealistic 3D Tiles through Cesium ion, Bing world
# imagery, and Cesium World Terrain. The free Community plan is for eligible
# personal/non-commercial use and has quotas; check current Cesium terms. A
@@ -1,8 +0,0 @@
- Aircraft on the map are shaded sprites that show the view of the aircraft
from where the camera is, instead of flat top-down silhouettes: each class
(and each helicopter rotor frame) is drawn from a sheet rendered from a
sphere of camera angles, laid flat along its course, so a plane seen at an
oblique angle looks solid. Flights, Military Flights (fleet and tracked
contact) and Local ADS-B use it; the TR-3B, airport vehicles, ground
stations and Cockpit's far pips stay flat, and a renderer without view
sheets draws the flat glyphs as before (Mazeyar Moeini Feizabadi, #1903).
@@ -0,0 +1,13 @@
- Bound the adsbdb enrichment proxy. `/api/adsbdb` had no request limit and no
cache eviction, so a caller cycling through the callsign or hex keyspace
could drive unlimited live requests at the free community API and grow
`.gev-cache/adsbdb.json` without end — every distinct key, 404s included, was
remembered forever. The route now admits 720 requests/minute per client
address (`GEV_RATELIMIT_ADSBDB_PER_MIN`; one tab's two enrichment queues top
out at 600), refusing the rest with 429 and `Retry-After` before any cache,
disk or upstream work. A refused lookup is asked for again once the refusal
has passed instead of leaving that aircraft without metadata for the
session. Each cache holds at most 20,000 entries, dropping the
least-recently-written first, and entries past the existing 24-hour TTL are
discarded when the file is read back. Cached answers and response shapes are
unchanged (daikaginza, #689).
+20 -1
View File
@@ -4350,6 +4350,25 @@ The existing aircraft normalizer is separately available through the portable
`gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache
policy, fallback behavior, response shapes and rendering remain unchanged.
### ADSBDB enrichment bounds
`/api/adsbdb` admits 720 requests/minute per client address
(`GEV_RATELIMIT_ADSBDB_PER_MIN`; `0` disables), with a global backstop of three
times that; a refused request answers 429 with `Retry-After` and reaches
neither the cache nor api.adsbdb.com. Each browser enrichment queue drips at
most 300/minute and one tab runs two (Flights and Local ADS-B), so an ordinary
session never meets the limit. When a lookup is refused anyway, both queues
make that key askable again after the refusal's retry-after rather than
treating the 429 as an answer.
Both enrichment caches hold at most 20,000 entries each, dropping the
least-recently-written first, and entries past their 24-hour TTL are discarded
when `.gev-cache/adsbdb.json` is read back. A cache file above 16 MB is skipped
rather than parsed. An evicted key costs one upstream request the next time it
is asked for; cached answers are otherwise unchanged.
Updated: October 23, 2026
## Control names for assistive technology
Scope, Bloom, Sharpen and location search have explicit accessible names.
@@ -8909,7 +8928,7 @@ pins and share links already supply complete boxes.
30-second backoff ahead of the current clock are ignored. A smaller rollback
can retain a bounded retry delay of up to 30 seconds.
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the emergency red is mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. Tracking never recolours a model or an icon: the tracked contact draws in the colours it has untracked, and only its alpha changes (faded while stale, clear while its model draws it; `trackedIconColor`, `src/data/trackedAircraftIcon.js`). IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Angle-aware aircraft sprites.** On a renderer with the `viewSheets` capability, each aircraft class (and each of the helicopter's three rotor frames) draws from the aircraft view sheet instead of its flat glyph: `/sprites/aircraft-views.webp`, the classes rendered shaded in neutral grey from a sphere of camera angles (`src/data/viewSheet.js`, baked by `scripts/build-aircraft-view-sheet.py`). The icon lies flat on the earth along its course and the renderer draws the view that matches where the eye is, so an aircraft seen obliquely looks solid; the tints (white fleet, cyan tracked, amber military) multiply the grey as before. `src/data/aircraftViews.js` maps an icon kind and rotor frame to its block of the sheet and registers the sheet once per draw port. Only an icon drawn along its course (`rotationMode: 'course'`) takes a view, and it has no near image (`imageLod`), the sheet having one resolution. Flights and Military Flights draw every fleet contact this way, and their tracked billboard too (drawn along the tracked display course instead of turned on screen, so selecting a contact still changes only its colour); Local ADS-B draws its markers along their track. The TR-3B triangle, airport vehicles, ground stations and Cockpit's far-contact pips keep their flat sprites, and on a renderer without the capability every icon is the flat glyph with its near image, as before. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 5Line truncated
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes every contact by the feed's own ICAO type when the feed sends one (a readsb row's `t`, or the `typeByIcao` map an `/api/flights` answer may send beside its state vectors, by ICAO address, as the regional adsb.lol fallback does), and a looked-up type replaces it once the airframe lookup answers (`src/layers/flights/records.js`); a surface emitter category keeps only a ground type (`ZVEH`, `GRND`) from the feed. A feed's `ZVEH` holds only for a contact that drives: one reported airborne, or faster than 40 m/s (`VEHICLE_MAX_SPEED_MPS`; a test transponder, a drone), is classed as any other aircraft. A `GRND` station is fixed and stands on the ground whatever height its reports carry. Flights keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), in the same colour while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo.
- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
-1
View File
@@ -49,7 +49,6 @@
"opensky:import": "./scripts/opensky-import-client.sh",
"build": "vite build",
"build:panel": "node scripts/build-panel.mjs",
"build:aircraft-views": "node scripts/build-aircraft-views.mjs",
"preview": "vite preview",
"test": "node scripts/run-unit-tests.mjs",
"test:perf": "node scripts/run-perf-tests.mjs",
-3
View File
@@ -35,9 +35,6 @@ How the layers use them:
the route or category colour is painted.
- The whole set loads once, up front, when a layer that draws it starts; no
model is fetched while a session runs.
- The aircraft and helicopter models are also rendered from every side into
the aircraft view sheet, the shaded sprites far-away aircraft are drawn
with ([`../sprites/`](../sprites/README.md)).
`src/data/fleetModels.js` reads the set and chooses each vehicle's model;
`src/data/fleetModels.test.mjs` checks that every model `types.json` names is
-71
View File
@@ -1,71 +0,0 @@
# Aircraft View Sheet
`aircraft-views.webp` is the sheet of shaded sprites far-away aircraft are
drawn with in Flights, Military Flights and Local ADS-B, on a renderer with the
`viewSheets` capability. Each aircraft class is rendered from a sphere of
camera angles; the renderer lays a contact flat on the earth along its course
and draws the frame nearest to where the eye is, as a card that tilts as the
eye moves off its direction until the next frame is the nearer (frames are
not blended), so an aircraft seen at an oblique angle looks solid and turns
with the camera. `aircraft-views.json` is its manifest.
The sprites are rendered from the project's own procedural fleet models
([`../models/fleet/`](../models/README.md)), so, like them, they contain no
third-party artwork and are covered by the repository's
[MIT license](../../LICENSE).
| Path | What it holds |
|---|---|
| `aircraft-views.webp` | 4096 × 3648 px, lossless WebP: 64 px cells, 64 a row, 57 rows. Grey: every pixel's red, green and blue are equal. |
| `aircraft-views.json` | The layout (`cellPx`, `columns`, `rows`, `ringStepDeg`, `rings`, `fill`, `grey`) and each subject's first cell, fleet model and bounding radius in metres. |
## Layout
Each subject owns 302 consecutive cells, row-major: subject `i` starts at
cell `i × 302`. The subjects, in order, are `airliner`, `widebody`, `quadjet`,
`turboprop`, `light`, `glider`, `fastjet`, `bizjet`, `uav`, and `helicopter0`
to `helicopter2` (the helicopter's three rotor frames, `src/data/rotorFrames.js`).
Within a block the frames lie in 17 rings 7.5° apart, from straight above
(ring 0, one frame) to 30° below the horizon, of 1, 4, 7, 10, 13, 16, 18, 20,
22, 23, 24, 25, 25, 25, 24, 23 and 22 frames. A ring runs from the eye dead
ahead of the nose, round the starboard side, to dead astern; the renderer
mirrors a starboard frame for an eye on the port side, so the light is
symmetric about the aircraft's centre plane. A frame is an orthographic view
centred on the model's origin, its bounding sphere spanning 0.92 of the cell,
turned so that straight above the nose points up the image.
`src/data/viewSheet.js` holds the same layout and the maths that picks a frame
(`AIRCRAFT_VIEWS`); `src/data/viewSheet.test.mjs` checks the manifest and the
bake script against it.
The sprites are neutral (white paint, grey shading, dark glass, a dark edge)
so each layer's tint multiplies them, as it does the flat glyphs. They are
exactly grey (`"grey": true`): the renderer keeps the sheet as grey and
alpha, reading its red channel, which halves its memory. The bake refuses a
frame that is not grey, and so does the step that writes the WebP. The thin
glider, UAV, light aircraft and helicopter are thickened a little before
their edge so they still read 20 to 30 px wide. Every cell keeps its outer
2 px transparent, so the renderer's mipmaps never pull in a neighbour.
## Rebuilding
```
npm run build:aircraft-views # about 7 minutes
npm run build:aircraft-views -- --only glider,uav --out /tmp/views
```
This needs Blender (`$BLENDER`, else `blender` on the `PATH`, else
`/Applications/Blender.app`). It runs `scripts/build-aircraft-view-sheet.py`
headless, which renders every frame with Cycles and refuses a frame whose
pixels reach within 2 px of its cell's edge, then
`scripts/build-aircraft-views.mjs` writes the PNG as lossless WebP here with
the manifest. With `--only`, the other subjects' cells are left empty, so
ship only a full bake.
To review a bake, write a contact sheet per subject (its rings as rows over a
dark sea, pale land and a mid satellite tone, plus a few frames at 40, 30 and
20 px in the fleet, tracked and military tints):
```
node scripts/qa-aircraft-view-sheet.mjs [--manifest public/sprites/aircraft-views.json] [--out qa-shots/aircraft-views]
```
-90
View File
@@ -1,90 +0,0 @@
{
"image": "aircraft-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 57,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25,
25,
24,
23,
22
],
"fill": 0.92,
"grey": true,
"subjects": {
"airliner": {
"first": 0,
"model": "aircraft/a320.glb",
"radiusM": 18.883
},
"widebody": {
"first": 302,
"model": "aircraft/b789.glb",
"radiusM": 32.121
},
"quadjet": {
"first": 604,
"model": "aircraft/b744.glb",
"radiusM": 37.959
},
"turboprop": {
"first": 906,
"model": "aircraft/at72.glb",
"radiusM": 14.14
},
"light": {
"first": 1208,
"model": "aircraft/c172.glb",
"radiusM": 5.825
},
"glider": {
"first": 1510,
"model": "aircraft/glider.glb",
"radiusM": 7.506
},
"fastjet": {
"first": 1812,
"model": "aircraft/t38.glb",
"radiusM": 7.408
},
"bizjet": {
"first": 2114,
"model": "aircraft/glf4.glb",
"radiusM": 17.211
},
"uav": {
"first": 2416,
"model": "aircraft/mq9.glb",
"radiusM": 9.811
},
"helicopter0": {
"first": 2718,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter1": {
"first": 3020,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
},
"helicopter2": {
"first": 3322,
"model": "helicopters/generic_heli.glb",
"radiusM": 7.556
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 MiB

-561
View File
@@ -1,561 +0,0 @@
"""Bake the aircraft view sheet: every aircraft class seen from a sphere of
directions, as one image of small shaded sprites.
blender -b --factory-startup --python scripts/build-aircraft-view-sheet.py -- \
--out <dir> [--cell 64] [--supersample 4] [--only airliner,light]
[--preview <dir>]
It writes `aircraft-views.png` and its manifest `aircraft-views.json` to
`--out`. The manifest names the shipped image, `aircraft-views.webp`, which
`npm run build:aircraft-views` (scripts/build-aircraft-views.mjs) makes from
the PNG (lossless) and writes to `public/sprites/` with the manifest.
The layers draw a contact with the frame that shows it from where the eye is
(`src/data/viewSheet.js` holds the same layout and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's constants and the shipped
manifest against it). A frame is an orthographic view of the class's
fleet model (`public/models/fleet/`, nose toward -X, +Y starboard, +Z up),
centred on the model's origin, the model's bounding sphere filling
`FILL` of the cell.
Directions. `d` is the unit vector from the aircraft to the eye in the
aircraft's own frame (forward, right, up), the aircraft lying flat on the
earth: up is the ground's normal, forward its course. Rings of frames lie
`RING_STEP_DEG` apart from straight above (ring 0, one frame) down to
`RINGS[-1]` below the horizon. A ring holds the eye's bearings from dead ahead
(first frame) round the starboard side to dead astern (last frame); the port
side is the starboard frame mirrored, which is why the light is symmetric
about the aircraft's centre plane.
Roll. A frame's image up is where the aircraft's forward goes under the
smallest rotation that takes "up" to `d`: straight above, the nose points up
the image, and the roll then changes smoothly all the way round and below
(it has no meaning only from straight below, which no ring reaches).
The sprites are neutral (white paint, grey shading, dark glass and a dark
edge) so a layer's tint multiplies them, as it does the flat glyphs; every
pixel's red, green and blue are equal (`"grey": true` in the manifest), as
the renderer keeps the sheet as grey and alpha, and the bake refuses a frame
that is not. A
helicopter's body and blades are painted light as well (its blades a solid
light grey), and its rotor frames share one scale: each rotor vertex counts
at the farthest point of the circle it sweeps about the rotor's axis. Thin
subjects are thickened before their edge (`BOLD_PX`), and every cell keeps
`CLEAR_EDGE_PX` clear at its edges for the renderer's mipmaps; the bake
refuses a frame that does not.
"""
import json
import math
import os
import struct
import sys
import bpy
import numpy as np
from mathutils import Matrix, Vector
# --- The sheet's layout (mirrored in src/data/viewSheet.js) -----------------
RING_STEP_DEG = 7.5
# Frames in each ring, from dead ahead round starboard to dead astern.
RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22]
FRAMES = sum(RINGS)
COLUMNS = 64
# How much of a cell the model's bounding sphere spans.
FILL = 0.92
# Each class's model, in the order of its block of frames in the sheet. A
# helicopter has one block for each rotor frame (rotorFrames.js).
ROTOR_ANGLES_DEG = [15, 45, 75]
SUBJECTS = [
("airliner", "aircraft/a320.glb", None),
("widebody", "aircraft/b789.glb", None),
("quadjet", "aircraft/b744.glb", None),
("turboprop", "aircraft/at72.glb", None),
("light", "aircraft/c172.glb", None),
("glider", "aircraft/glider.glb", None),
("fastjet", "aircraft/t38.glb", None),
("bizjet", "aircraft/glf4.glb", None),
("uav", "aircraft/mq9.glb", None),
("helicopter0", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[0]),
("helicopter1", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[1]),
("helicopter2", "helicopters/generic_heli.glb", ROTOR_ANGLES_DEG[2]),
]
# Cell pixels each subject is thickened by before its dark edge, so thin
# wings and rotor blades still read when a contact is drawn 20 to 30 px
# wide. The big aircraft read as they are and are not thickened.
BOLD_PX = {
"light": 0.35,
"glider": 1.0,
"uav": 1.0,
"helicopter0": 0.4,
"helicopter1": 0.4,
"helicopter2": 0.4,
}
# Cells keep this many pixels at each edge clear: the renderer samples the
# sheet with mipmaps (to level 1), so a neighbour's pixels must not reach
# into a cell's footprint.
CLEAR_EDGE_PX = 2
FORWARD = Vector((-1.0, 0.0, 0.0))
RIGHT = Vector((0.0, 1.0, 0.0))
UP = Vector((0.0, 0.0, 1.0))
def frame_directions():
"""Every frame's (ring, index, d) with d in the model's axes."""
out = []
for ring, count in enumerate(RINGS):
alpha = math.radians(ring * RING_STEP_DEG)
for i in range(count):
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
d = (
FORWARD * (math.sin(alpha) * math.cos(phi))
+ RIGHT * (math.sin(alpha) * math.sin(phi))
+ UP * math.cos(alpha)
)
out.append((ring, i, d.normalized()))
return out
def frame_up(d):
"""A frame's image up: forward, turned as `UP` turns onto `d`."""
return (UP.rotation_difference(d) @ FORWARD).normalized()
# --- Scene -------------------------------------------------------------------
def args_after_dashes():
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
opts = {
"out": "public/sprites",
"cell": 64,
"supersample": 4,
"only": None,
"preview": None,
"samples": 48,
}
i = 0
while i < len(argv):
key = argv[i].lstrip("-")
if key not in opts:
raise SystemExit(f"unknown option {argv[i]}")
opts[key] = argv[i + 1]
i += 2
opts["cell"] = int(opts["cell"])
opts["supersample"] = int(opts["supersample"])
opts["samples"] = int(opts["samples"])
return opts
def setup_scene(render_px, samples):
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = samples
scene.cycles.use_denoising = False
scene.cycles.max_bounces = 3
scene.cycles.pixel_filter_type = "BOX"
scene.cycles.filter_width = 1.0
scene.render.film_transparent = True
scene.render.resolution_x = render_px
scene.render.resolution_y = render_px
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.image_settings.color_depth = "8"
scene.view_settings.view_transform = "Standard"
scene.view_settings.look = "None"
scene.display_settings.display_device = "sRGB"
# Sky: even light from every side, so the underside is lit and the
# wings shade the fuselage softly where they meet.
world = bpy.data.worlds.new("sky")
world.use_nodes = True
background = world.node_tree.nodes["Background"]
background.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)
background.inputs["Strength"].default_value = SKY_STRENGTH
scene.world = world
# Sun: from above, leaning toward the nose, in the aircraft's centre
# plane (so a mirrored frame is lit as its twin).
sun_data = bpy.data.lights.new("sun", "SUN")
sun_data.energy = SUN_STRENGTH
sun_data.angle = math.radians(18)
sun = bpy.data.objects.new("sun", sun_data)
scene.collection.objects.link(sun)
lean = math.radians(28)
to_sun = (UP * math.cos(lean) + FORWARD * math.sin(lean)).normalized()
sun.rotation_euler = to_sun.to_track_quat("Z", "Y").to_euler()
# Fill: a weak light from the eye, so what faces the viewer is lighter
# than what turns away and a round body reads as round from any side.
fill_data = bpy.data.lights.new("fill", "SUN")
fill_data.energy = FILL_STRENGTH
fill_data.angle = math.radians(30)
fill = bpy.data.objects.new("fill", fill_data)
scene.collection.objects.link(fill)
camera_data = bpy.data.cameras.new("camera")
camera_data.type = "ORTHO"
camera_data.clip_start = 0.1
camera_data.clip_end = 10000
camera = bpy.data.objects.new("camera", camera_data)
scene.collection.objects.link(camera)
scene.camera = camera
return scene, camera, fill
# Paint by the model's own colour value (its largest channel, linear): glass
# and tyres stay dark, a livery's accent becomes mid grey, and every body
# colour a light paint, so a tint reads on any model.
PAINT_RAMP = [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)]
HELICOPTER_PAINT_RAMP = [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)]
SUN_STRENGTH = 1.4
SKY_STRENGTH = 0.38
FILL_STRENGTH = 0.9
def paint_material(paint_ramp=PAINT_RAMP, solid=None):
"""Neutral paint that keeps the model's light and dark parts apart."""
material = bpy.data.materials.new("paint")
material.use_nodes = True
nodes = material.node_tree.nodes
links = material.node_tree.links
bsdf = nodes["Principled BSDF"]
bsdf.inputs["Roughness"].default_value = 0.6
if solid is not None:
bsdf.inputs["Base Color"].default_value = (solid, solid, solid, 1.0)
return material
colour = nodes.new("ShaderNodeVertexColor")
colour.layer_name = "Color"
split = nodes.new("ShaderNodeSeparateColor")
links.new(colour.outputs["Color"], split.inputs["Color"])
red_green = nodes.new("ShaderNodeMath")
red_green.operation = "MAXIMUM"
links.new(split.outputs[0], red_green.inputs[0])
links.new(split.outputs[1], red_green.inputs[1])
value = nodes.new("ShaderNodeMath")
value.operation = "MAXIMUM"
links.new(red_green.outputs[0], value.inputs[0])
links.new(split.outputs[2], value.inputs[1])
ramp = nodes.new("ShaderNodeValToRGB")
elements = ramp.color_ramp.elements
while len(elements) < len(paint_ramp):
elements.new(0.5)
for element, (position, grey) in zip(elements, paint_ramp):
element.position = position
element.color = (grey, grey, grey, 1.0)
links.new(value.outputs[0], ramp.inputs["Fac"])
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
return material
def model_parts(path):
"""The part table in a fleet model's root node (`render/modelParts.js`)."""
with open(path, "rb") as f:
data = f.read()
length = struct.unpack("<I", data[12:16])[0]
document = json.loads(data[20 : 20 + length])
for node in document.get("nodes", []):
parts = (node.get("extras") or {}).get("parts")
if parts:
return parts
return []
def gltf_to_blender(v):
"""A glTF (Y up) vector in Blender's axes (Z up)."""
return Vector((v[0], -v[2], v[1]))
def turn_rotors(mesh, parts, degrees, rotor_material):
"""Pose the rotors and bound each vertex over its entire rotation."""
part_of = mesh.data.attributes.get("_PART")
if part_of is None:
return {}
mesh.data.materials.append(rotor_material)
swept_radii = {}
to_world = mesh.matrix_world
to_local = to_world.inverted()
for index, part in enumerate(parts):
if part.get("kind") != "spin" or not part["name"].startswith("rotor"):
continue
pivot = gltf_to_blender(part["pivot"])
axis = gltf_to_blender(part["axis"]).normalized()
turn = Matrix.Rotation(math.radians(degrees), 4, axis)
move = to_local @ Matrix.Translation(pivot) @ turn @ Matrix.Translation(-pivot) @ to_world
if part_of.domain == "POINT":
members = [i for i, item in enumerate(part_of.data) if item.value == index]
else:
members = sorted(
{
mesh.data.loops[i].vertex_index
for i, item in enumerate(part_of.data)
if item.value == index
}
)
for i in members:
vertex = mesh.data.vertices[i]
relative = to_world @ vertex.co - pivot
axial = relative.dot(axis)
center = pivot + axial * axis
# The sweep lies in a plane perpendicular to the axis. Its
# farthest point adds the circle radius to the projected center.
radial = (relative - axial * axis).length
offset = (center - center.dot(axis) * axis).length
swept_radii[i] = math.hypot(center.dot(axis), offset + radial)
vertex.co = move @ vertex.co
for polygon in mesh.data.polygons:
if all(i in swept_radii for i in polygon.vertices):
polygon.material_index = 1
return swept_radii
def load_model(path, material, rotor_deg, rotor_material):
before = set(bpy.data.objects)
bpy.ops.import_scene.gltf(filepath=path)
objects = [o for o in bpy.data.objects if o not in before]
meshes = [o for o in objects if o.type == "MESH"]
bpy.context.view_layer.update()
parts = model_parts(path) if rotor_deg is not None else []
radius = 0.0
for mesh in meshes:
mesh.data.materials.clear()
mesh.data.materials.append(material)
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
for vertex in mesh.data.vertices:
distance = swept_radii.get(vertex.index)
if distance is None:
distance = (mesh.matrix_world @ vertex.co).length
radius = max(radius, distance)
return objects, radius
def aim(camera, fill, d, radius):
fill.rotation_euler = d.to_track_quat("Z", "Y").to_euler()
up = frame_up(d)
right = up.cross(d).normalized()
rotation = Matrix((right, up, d)).transposed()
camera.matrix_world = Matrix.Translation(d * (radius * 4 + 10)) @ rotation.to_4x4()
camera.data.ortho_scale = 2 * radius / FILL
# --- Pixels ------------------------------------------------------------------
def read_pixels(path):
image = bpy.data.images.load(path)
width, height = image.size
pixels = np.array(image.pixels[:], dtype=np.float32).reshape(height, width, 4)
bpy.data.images.remove(image)
return pixels[::-1] # top row first
def dilate(alpha, radius):
out = alpha.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
shifted = np.zeros_like(alpha)
ys = slice(max(dy, 0), alpha.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), alpha.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), alpha.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), alpha.shape[1] + min(-dx, 0))
shifted[ys, xs] = alpha[yd, xd]
np.maximum(out, shifted, out=out)
return out
def disk_sum(values, radius):
"""Each pixel's sum of `values` over a disk of `radius` around it."""
out = values.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dy * dy > radius * radius or (dx == 0 and dy == 0):
continue
ys = slice(max(dy, 0), values.shape[0] + min(dy, 0))
xs = slice(max(dx, 0), values.shape[1] + min(dx, 0))
yd = slice(max(-dy, 0), values.shape[0] + min(-dy, 0))
xd = slice(max(-dx, 0), values.shape[1] + min(-dx, 0))
out[ys, xs] += values[yd, xd]
return out
# Neutral, as the whole sheet is: the renderer keeps it as grey + alpha.
EDGE_RGB = np.array([0.045, 0.045, 0.045], dtype=np.float32)
EDGE_ALPHA = 0.62
def inside_mask(size, supersample):
"""1 within the disk that keeps CLEAR_EDGE_PX of the cell clear, fading
to 0 over half a cell pixel inside its rim. Only what the bake adds round
the model (its thickening and dark edge) is faded by it: the model's own
bounding sphere ends at FILL, inside it."""
cell = size / supersample
centre = size / 2
y, x = np.mgrid[0:size, 0:size] + 0.5
r = np.hypot(x - centre, y - centre) / supersample
outer = cell / 2 - CLEAR_EDGE_PX
return np.clip((outer - r) / 0.5, 0, 1).astype(np.float32)
def finish(pixels, supersample, bold_px=0.0):
"""Thicken the sprite by `bold_px` cell pixels, put a dark edge round it,
then bring it down to the cell by area."""
rgb = pixels[..., :3]
alpha = pixels[..., 3]
premultiplied = rgb * alpha[..., None]
mask = inside_mask(pixels.shape[0], supersample)
radius = round(supersample * bold_px)
if radius > 0:
# Under the model, its own colour spread outward: each new pixel the
# mean colour of the model round it.
grown = dilate(alpha, radius) * mask
weight = disk_sum(alpha, radius)
spread = disk_sum(premultiplied, radius) / np.maximum(weight, 1e-6)[..., None]
under = grown * (1 - alpha)
premultiplied = premultiplied + spread * under[..., None]
alpha = alpha + under
# About 0.9 cell pixels of edge.
halo = dilate(alpha, max(1, round(supersample * 0.9))) * EDGE_ALPHA * mask
out_alpha = alpha + halo * (1 - alpha)
premultiplied = premultiplied + EDGE_RGB * (halo * (1 - alpha))[..., None]
size = pixels.shape[0] // supersample
def area(a):
return a.reshape(size, supersample, size, supersample, -1).mean(axis=(1, 3))
small_alpha = area(out_alpha[..., None])[..., 0]
small = area(premultiplied)
colour = np.where(
small_alpha[..., None] > 1e-4, small / np.maximum(small_alpha[..., None], 1e-4), 0
)
return np.dstack([np.clip(colour, 0, 1), np.clip(small_alpha, 0, 1)])
# How far a frame's red, green and blue may differ (in 0..1) before the bake
# refuses it as not grey: rendering noise, never a colour.
GREY_TOLERANCE = 1.5 / 255
def to_grey(frame, name, n):
"""The frame with equal red, green and blue (their mean), refusing one
whose channels differ by more than rendering noise: the sheet ships as
grey (`"grey": true`), its red channel read as the grey."""
rgb = frame[..., :3]
lit = frame[..., 3] > 0
spread = (rgb.max(axis=2) - rgb.min(axis=2))[lit]
if spread.size and spread.max() > GREY_TOLERANCE:
raise SystemExit(
f"{name} frame {n}: not grey (its channels differ by "
f"{spread.max() * 255:.1f}/255); the sheet ships as grey"
)
grey = rgb.mean(axis=2, keepdims=True)
return np.dstack([np.repeat(grey, 3, axis=2), frame[..., 3:]])
def check_clear_edge(frame, name, n):
"""Refuse a frame with anything but transparent pixels near its edge."""
e = CLEAR_EDGE_PX
alpha = frame[..., 3]
band = np.concatenate(
[alpha[:e].ravel(), alpha[-e:].ravel(), alpha[:, :e].ravel(), alpha[:, -e:].ravel()]
)
if band.max() >= 0.5 / 255:
raise SystemExit(
f"{name} frame {n}: pixels within {e} px of the cell edge "
f"(alpha {band.max():.3f}); the fill leaves them no room"
)
def save_png(path, pixels):
height, width = pixels.shape[:2]
image = bpy.data.images.new("out", width, height, alpha=True)
image.alpha_mode = "STRAIGHT"
image.pixels.foreach_set(pixels[::-1].astype(np.float32).ravel())
image.filepath_raw = path
image.file_format = "PNG"
image.save()
bpy.data.images.remove(image)
# --- Bake --------------------------------------------------------------------
def main():
opts = args_after_dashes()
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
models = os.path.join(root, "public", "models", "fleet")
cell = opts["cell"]
supersample = opts["supersample"]
only = set(opts["only"].split(",")) if opts["only"] else None
scene, camera, fill = setup_scene(cell * supersample, opts["samples"])
material = paint_material()
helicopter_material = paint_material(HELICOPTER_PAINT_RAMP)
rotor_material = paint_material(solid=0.82)
directions = frame_directions()
tmp = os.path.join(bpy.app.tempdir, "view-frame.png")
rows = math.ceil(len(SUBJECTS) * FRAMES / COLUMNS)
sheet = np.zeros((rows * cell, COLUMNS * cell, 4), dtype=np.float32)
manifest = {
"image": "aircraft-views.webp",
"cellPx": cell,
"columns": COLUMNS,
"rows": rows,
"ringStepDeg": RING_STEP_DEG,
"rings": RINGS,
"fill": FILL,
# Every pixel's red, green and blue are equal.
"grey": True,
"subjects": {},
}
for index, (name, model, rotor_deg) in enumerate(SUBJECTS):
first = index * FRAMES
manifest["subjects"][name] = {"first": first, "model": model}
if only and name not in only:
continue
objects, radius = load_model(
os.path.join(models, model),
material if rotor_deg is None else helicopter_material,
rotor_deg,
rotor_material,
)
manifest["subjects"][name]["radiusM"] = round(radius, 3)
for n, (ring, i, d) in enumerate(directions):
aim(camera, fill, d, radius)
scene.render.filepath = tmp
bpy.ops.render.render(write_still=True)
frame = finish(read_pixels(tmp), supersample, BOLD_PX.get(name, 0.0))
check_clear_edge(frame, name, n)
frame = to_grey(frame, name, n)
at = first + n
y = (at // COLUMNS) * cell
x = (at % COLUMNS) * cell
sheet[y : y + cell, x : x + cell] = frame
if opts["preview"]:
os.makedirs(opts["preview"], exist_ok=True)
save_png(
os.path.join(opts["preview"], f"{name}-r{ring}-{i:02d}.png"), frame
)
for obj in objects:
bpy.data.objects.remove(obj, do_unlink=True)
print(f"baked {name}: {FRAMES} frames, radius {radius:.2f} m", flush=True)
out = os.path.join(root, opts["out"]) if not os.path.isabs(opts["out"]) else opts["out"]
os.makedirs(out, exist_ok=True)
save_png(os.path.join(out, "aircraft-views.png"), sheet)
with open(os.path.join(out, "aircraft-views.json"), "w") as f:
json.dump(manifest, f, indent=1)
f.write("\n")
print(f"wrote {out}/aircraft-views.png ({COLUMNS * cell}x{rows * cell})")
main()
-96
View File
@@ -1,96 +0,0 @@
#!/usr/bin/env node
/**
* build-aircraft-views.mjs: bake the aircraft view sheet and ship it.
*
* Runs `scripts/build-aircraft-view-sheet.py` in Blender (headless) into a
* scratch directory, then writes `public/sprites/aircraft-views.webp`
* (lossless WebP of the baked PNG) and `public/sprites/aircraft-views.json`
* (its manifest). See `public/sprites/README.md`.
*
* Run: npm run build:aircraft-views [-- --only airliner,light] [--out public/sprites]
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
const ONLY = opt('--only', null);
function blender() {
if (process.env.BLENDER) return process.env.BLENDER;
const which = spawnSync('which', ['blender'], { encoding: 'utf8' });
if (which.status === 0 && which.stdout.trim()) return which.stdout.trim();
const mac = '/Applications/Blender.app/Contents/MacOS/Blender';
if (fs.existsSync(mac)) return mac;
throw new Error('no Blender: set BLENDER to its executable');
}
/**
* Refuse a sheet the manifest calls grey whose red, green and blue differ
* anywhere: the renderer reads its red channel as the grey.
*/
async function assertGrey(file) {
const { data, info } = await sharp(file)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
for (let i = 0; i < data.length; i += info.channels)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
const pixel = i / info.channels;
throw new Error(
`the sheet is not grey at (${pixel % info.width}, ${Math.floor(pixel / info.width)})`,
);
}
}
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'aircraft-views-'));
try {
const bake = spawnSync(
blender(),
[
'-b',
'--factory-startup',
'--python',
path.join(root, 'scripts', 'build-aircraft-view-sheet.py'),
'--',
'--out',
scratch,
...(ONLY ? ['--only', ONLY] : []),
],
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8' },
);
for (const line of bake.stdout.split('\n'))
if (/^(baked|wrote)\b/.test(line)) console.log(line);
if (bake.status !== 0) {
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
throw new Error(`the bake failed (exit ${bake.status})`);
}
const manifest = JSON.parse(
fs.readFileSync(path.join(scratch, 'aircraft-views.json'), 'utf8'),
);
const png = path.join(scratch, 'aircraft-views.png');
if (manifest.grey) await assertGrey(png);
fs.mkdirSync(OUT, { recursive: true });
const webp = path.join(OUT, manifest.image);
await sharp(png)
.webp({ lossless: true, effort: 6, exact: true })
.toFile(webp);
fs.copyFileSync(
path.join(scratch, 'aircraft-views.json'),
path.join(OUT, 'aircraft-views.json'),
);
const kb = Math.round(fs.statSync(webp).size / 1024);
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
} finally {
fs.rmSync(scratch, { recursive: true, force: true });
}
+3 -1
View File
@@ -1703,5 +1703,7 @@
"src/ui/livePanel.test.mjs",
"src/ui/stationPanel.test.mjs",
"src/ui/styles/live.css",
"src/ui/styles/station.css"
"src/ui/styles/station.css",
"src/adsbdbCacheGovernor.test.mjs",
"src/layers/enrichmentRateLimitRetry.test.mjs"
]
+31 -62
View File
@@ -68,8 +68,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -393,6 +392,8 @@
"server/providers/common/compress.js",
"server/providers/common/http.js",
"server/providers/common/query.js",
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js",
"server/providers/aircraft/opensky.js",
"server/providers/aircraft/adsb-lol.js",
"server/providers/aircraft/enrichment.js",
@@ -1304,8 +1305,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/data/viewSheet.js"
"src/layers/satellites/tiangongMounts.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1717,8 +1717,7 @@
"src/data/liveStreams.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js",
"src/data/viewSheet.js"
"src/ui/liveControls.js"
],
"external": [
"cesium",
@@ -1922,8 +1921,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/scenes/storyTags.js",
"src/scenes/storyThumb.js",
"src/data/viewSheet.js"
"src/scenes/storyThumb.js"
],
"external": ["cesium", "vue", "pinia", "vue-i18n", "kdbush"]
},
@@ -2090,9 +2088,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/courseFromFixes.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2238,9 +2234,7 @@
"src/data/detectionOcclusion.js",
"src/layers/flights/placed.js",
"src/data/courseFromFixes.js",
"src/data/approxDistance.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/approxDistance.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2398,8 +2392,7 @@
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js",
"src/data/viewSheet.js"
"src/data/openVesselPhoto.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2530,8 +2523,7 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/sky/assets.js",
"src/render/cesium/cardPreviews.js",
"src/data/viewSheet.js"
"src/render/cesium/cardPreviews.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2629,8 +2621,7 @@
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/time/frameWait.js",
"src/data/viewSheet.js"
"src/time/frameWait.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2782,8 +2773,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -2906,8 +2896,7 @@
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/data/viewSheet.js"
"src/layers/satellites/tiangongArticulation.js"
],
"external": ["cesium", "satellite.js", "kdbush"]
},
@@ -3011,8 +3000,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3124,8 +3112,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3207,8 +3194,7 @@
"src/data/installationFeedback.js",
"src/ui/layerNames.js",
"src/render/cesium/zoomOutGuard.js",
"src/ui/statusText.js",
"src/data/viewSheet.js"
"src/ui/statusText.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3334,8 +3320,7 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
"src/render/vectorBase/expressions.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3529,8 +3514,7 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
"src/render/vectorBase/expressions.js"
],
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -3660,8 +3644,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": [
"cesium",
@@ -3754,8 +3737,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "@mapbox/vector-tile", "pbf", "kdbush"]
},
@@ -3867,8 +3849,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -3943,8 +3924,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -4085,8 +4065,7 @@
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/data/viewSheet.js"
"src/render/vectorBase/expressions.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -5620,9 +5599,7 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/layers/satellites/tiangongArticulation.js"
],
"external": [
"hls.js",
@@ -6478,9 +6455,7 @@
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/layers/satellites/tiangongModel.js"
],
"external": [
"hls.js",
@@ -6629,8 +6604,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": [
"cesium",
@@ -6744,8 +6718,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -7580,8 +7553,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "egm96-universal", "pbf", "kdbush"]
},
@@ -7711,8 +7683,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "pbf", "kdbush"]
},
@@ -8024,8 +7995,7 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/data/viewSheet.js"
"src/data/detectionOcclusion.js"
],
"external": ["cesium", "kdbush"]
},
@@ -8474,8 +8444,7 @@
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/render/recession.js",
"src/render/modelParts.js",
"src/data/viewSheet.js"
"src/render/modelParts.js"
],
"external": ["pbf", "@mapbox/vector-tile", "kdbush"]
},
-163
View File
@@ -1,163 +0,0 @@
#!/usr/bin/env node
/**
* qa-aircraft-view-sheet.mjs: contact sheets of a baked aircraft view sheet,
* for reviewing a bake (`scripts/build-aircraft-view-sheet.py`) before it
* ships.
*
* For each subject it writes one image: its frames with the rings as rows
* (straight above at the top, 30° below the horizon at the bottom, each ring
* from dead ahead to dead astern), over a dark sea colour, a pale land colour
* and a mid satellite tone, each tinted as the layers tint it. Under them, a
* few frames (above, oblique, abeam, below) shrunk to the sizes a contact is
* drawn at, to judge whether thin wings still read.
*
* Run: node scripts/qa-aircraft-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/aircraft-views] [--zoom 2] [--sizes 40,30,20]
* [--only airliner,glider]
* `--sheet` defaults to the manifest's `image`, next to it.
*/
import fs from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const MANIFEST = path.resolve(
opt('--manifest', 'public/sprites/aircraft-views.json'),
);
const OUT = path.resolve(opt('--out', 'qa-shots/aircraft-views'));
const ZOOM = Number(opt('--zoom', '2'));
const SIZES = opt('--sizes', '40,30,20').split(',').map(Number);
const ONLY = opt('--only', '').split(',').filter(Boolean);
/** Grounds a contact is seen over: a dark sea, pale land, a mid satellite tone. */
const GROUNDS = [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The layers' tints, multiplied into the neutral sprite. */
const TINTS = [
{ name: 'fleet', rgb: [1, 1, 1] },
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const GAP = 8;
const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
const sheetPath = path.resolve(
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
);
const { cellPx: cell, columns, rings } = manifest;
const firsts = [];
rings.reduce((at, count) => (firsts.push(at), at + count), 0);
const widest = Math.max(...rings);
/** The ring nearest `offDeg` from straight above. */
const ringAt = (offDeg) =>
Math.min(rings.length - 1, Math.round(offDeg / manifest.ringStepDeg));
/** Frames shown shrunk, as ring and index: straight above, oblique from
* ahead and to the right, abeam on the horizon, and from below, abeam. */
const PICKS = [
[0, 0],
[ringAt(45), Math.floor((rings[ringAt(45)] - 1) / 3)],
[ringAt(90), Math.round((rings[ringAt(90)] - 1) / 2)],
[rings.length - 1, Math.round((rings[rings.length - 1] - 1) / 2)],
];
const sheet = sharp(sheetPath, { limitInputPixels: false });
const { data: pixels, info } = await sheet
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
/** One cell as raw RGBA, tinted. */
function cellPixels(index, tint) {
const out = Buffer.alloc(cell * cell * 4);
const left = (index % columns) * cell;
const top = Math.floor(index / columns) * cell;
for (let y = 0; y < cell; y++)
for (let x = 0; x < cell; x++) {
const from = ((top + y) * info.width + left + x) * 4;
const to = (y * cell + x) * 4;
for (let c = 0; c < 3; c++)
out[to + c] = Math.round(pixels[from + c] * tint.rgb[c]);
out[to + 3] = pixels[from + 3];
}
return out;
}
async function cellImage(index, tint, size) {
let image = sharp(cellPixels(index, tint), {
raw: { width: cell, height: cell, channels: 4 },
});
if (size !== cell) image = image.resize(size, size, { kernel: 'lanczos3' });
else if (ZOOM !== 1)
image = image.resize(cell * ZOOM, cell * ZOOM, { kernel: 'nearest' });
return image.png().toBuffer();
}
async function subjectSheet(name, first) {
const tile = cell * ZOOM;
const panelW = widest * tile;
const panelH = rings.length * tile;
const stripH = Math.max(...SIZES) + GAP;
const blockH = panelH + GAP + TINTS.length * stripH;
const width = GROUNDS.length * (panelW + GAP) + GAP;
const height = blockH + 2 * GAP;
const layers = [];
for (const [g, ground] of GROUNDS.entries()) {
const x0 = GAP + g * (panelW + GAP);
layers.push({
input: {
create: {
width: panelW,
height: blockH,
channels: 4,
background: ground.css,
},
},
left: x0,
top: GAP,
});
// Rings as rows, fleet white.
for (let ring = 0; ring < rings.length; ring++)
for (let i = 0; i < rings[ring]; i++)
layers.push({
input: await cellImage(first + firsts[ring] + i, TINTS[0], cell),
left: x0 + i * tile,
top: GAP + ring * tile,
});
// The picked frames shrunk to drawn sizes, one row a tint.
for (const [t, tint] of TINTS.entries()) {
let x = x0 + GAP;
const y = GAP + panelH + GAP + t * stripH;
for (const [ring, index] of PICKS)
for (const size of SIZES) {
layers.push({
input: await cellImage(first + firsts[ring] + index, tint, size),
left: x,
top: y + (stripH - GAP - size),
});
x += size + 4;
}
}
}
const file = path.join(OUT, `${name}.png`);
await sharp({
create: { width, height, channels: 4, background: '#111111' },
})
.composite(layers)
.png()
.toFile(file);
return file;
}
fs.mkdirSync(OUT, { recursive: true });
for (const [name, entry] of Object.entries(manifest.subjects)) {
if (ONLY.length && !ONLY.includes(name)) continue;
const first = typeof entry === 'number' ? entry : entry.first;
console.log('wrote', await subjectSheet(name, first));
}
-313
View File
@@ -1,313 +0,0 @@
#!/usr/bin/env node
/**
* qa-aircraft-views.mjs: screenshots of the aircraft view sheet in the app.
*
* Seeds a grid of synthetic military contacts (every icon class down the
* rows, eight courses across) through a fetch shim, then photographs it from
* straight above, tilted from several sides and from below, so a person can
* check that each sprite shows its aircraft from where the camera is: the
* nose along the course, the far wing foreshortened, the underside from
* below.
*
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
* [--layer military|flights] [--block-sheet] [--headful]
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
* Needs the dev server (`npm run dev`).
*/
import fs from 'node:fs';
import path from 'node:path';
import puppeteer from 'puppeteer';
import { stubPlanespotters } from './qa-photo-stub.mjs';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
};
const APP_URL = opt('--url', 'http://localhost:4173');
const OUT = path.resolve(opt('--out', 'qa-shots/views'));
const HEADFUL = argv.includes('--headful');
// `military` (amber, every class by type code) or `flights` (white, the
// classes an ADS-B emitter category gives).
const LAYER = opt('--layer', 'military');
// Fail the sheet's request: the contacts should draw their flat glyphs.
const BLOCK_SHEET = argv.includes('--block-sheet');
const GPU = argv.includes('--gpu');
// A type code for each icon class (aircraftClass.js).
const CLASSES = [
['airliner', 'A320'],
['widebody', 'C17'],
['quadjet', 'B744'],
['turboprop', 'C130'],
['light', 'C172'],
['glider', 'DISC'],
['fastjet', 'F16'],
['bizjet', 'GLF4'],
['uav', 'Q9'],
['helicopter', 'H60'],
];
// The classes a flight's emitter category gives (OpenSky has no type code).
const CATEGORIES = [
['airliner', 4],
['widebody', 6],
['light', 2],
['fastjet', 7],
['glider', 9],
['helicopter', 8],
];
const ROWS = LAYER === 'flights' ? CATEGORIES : CLASSES;
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
const CENTRE = { lon: -97.74, lat: 30.3 };
const STEP_DEG = 0.03;
const ALT_FT = 12000;
const contacts = [];
ROWS.forEach(([klass, type], row) =>
COURSES.forEach((courseDeg, column) =>
contacts.push({
hex: `ee${row.toString(16)}${column.toString(16)}00`.slice(0, 6),
flight: `${klass.slice(0, 4).toUpperCase()}${courseDeg}`,
t: type,
klass,
courseDeg,
lon: CENTRE.lon + (column - (COURSES.length - 1) / 2) * STEP_DEG,
lat: CENTRE.lat - (row - (ROWS.length - 1) / 2) * STEP_DEG,
altFt: ALT_FT,
}),
),
);
// Each shot: where the camera looks from. `heading` is the way it looks
// (degrees clockwise from north), `pitch` down from level, `rangeKm` from
// the grid's centre at the contacts' height.
const SHOTS = [
{ name: '1-above', heading: 0, pitch: -90, rangeKm: 44 },
{ name: '2-tilt30-north', heading: 0, pitch: -60, rangeKm: 46 },
{ name: '3-tilt55-north', heading: 0, pitch: -35, rangeKm: 50 },
{ name: '4-tilt55-east', heading: 90, pitch: -35, rangeKm: 50 },
{ name: '5-tilt55-southwest', heading: 225, pitch: -35, rangeKm: 50 },
{ name: '6-tilt75-north', heading: 0, pitch: -15, rangeKm: 52 },
{ name: '7-below-north', heading: 0, pitch: 12, rangeKm: 15.5 },
];
// `--orbit`: the camera swung round the grid a little at a time, a frame
// each step, to watch the sprites turn from one view to the next.
const ORBIT_STEP_DEG = Number(opt('--orbit-step', 2));
const ORBIT_SHOTS = Array.from(
{ length: Math.floor(90 / ORBIT_STEP_DEG) + 1 },
(_, i) => ({
name: `orbit-${String(i).padStart(3, '0')}`,
heading: i * ORBIT_STEP_DEG,
pitch: Number(opt('--orbit-pitch', -35)),
rangeKm: 50,
settleMs: i === 0 ? 6000 : 900,
}),
);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
fs.mkdirSync(OUT, { recursive: true });
const browser = await puppeteer.launch({
headless: HEADFUL ? false : 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
...(GPU ? [] : ['--use-gl=angle', '--use-angle=swiftshader']),
'--disable-web-security',
'--disable-background-timer-throttling',
'--disable-renderer-backgrounding',
'--window-size=1500,1000',
],
});
const errors = [];
try {
const page = await browser.newPage();
await stubPlanespotters(page);
await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 2 });
page.on('console', (msg) => {
if (
msg.type() === 'error' &&
!/Failed to load resource/i.test(msg.text())
)
errors.push(msg.text());
});
page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
if (BLOCK_SHEET) {
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.isInterceptResolutionHandled()) return;
if (/\/sprites\/aircraft-views\./.test(request.url())) request.abort();
else request.continue();
});
}
await page.evaluateOnNewDocument(
(seed) => {
const realFetch = window.fetch.bind(window);
// Each contact flies its course, slowly: a feed whose fixes stand
// still while claiming a track makes the layers work a heading out
// of no movement, and the contacts turn north over a run.
const SPEED_MPS = 6;
const started = Date.now();
const at = (c) => {
const flown = (SPEED_MPS * (Date.now() - started)) / 1000;
const course = (c.courseDeg * Math.PI) / 180;
return {
lat: c.lat + (flown * Math.cos(course)) / 111320,
lon:
c.lon +
(flown * Math.sin(course)) /
(111320 * Math.cos((c.lat * Math.PI) / 180)),
};
};
const json = (body) =>
new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
window.fetch = (input, init) => {
const url =
typeof input === 'string' ? input : (input && input.url) || '';
if (url.includes('/api/openai/hud-summary'))
return Promise.resolve(json({ summary: 'view QA' }));
if (url.includes('/api/military/track'))
return Promise.resolve(
json({ timestamp: Math.floor(Date.now() / 1000), trace: [] }),
);
if (url.includes('/api/military'))
return Promise.resolve(
json({
msg: 'No error',
now: Date.now(),
ac: (seed.layer === 'military' ? seed.contacts : []).map(
(c) => ({
hex: c.hex,
flight: c.flight,
...at(c),
alt_baro: c.altFt,
track: c.courseDeg,
gs: SPEED_MPS * 1.9438,
t: c.t,
r: `QA-${c.hex.slice(-3)}`,
ownOp: 'QA',
seen_pos: 0,
}),
),
}),
);
if (url.includes('/api/flights/track'))
return Promise.resolve(json({ path: [] }));
if (url.includes('/api/flights') && seed.layer === 'flights') {
const now = Math.floor(Date.now() / 1000);
return Promise.resolve(
json({
time: now,
states: seed.contacts.map((c) => [
c.hex,
c.flight,
'QA',
now,
now,
at(c).lon,
at(c).lat,
c.altFt * 0.3048,
false,
SPEED_MPS,
c.courseDeg,
0,
null,
null,
null,
false,
0,
c.t,
]),
}),
);
}
if (url.includes('/api/adsbdb/'))
return Promise.resolve(json({ found: false }));
return realFetch(input, init);
};
},
{ layer: LAYER, contacts },
);
console.log(`Loading ${APP_URL} ...`);
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForFunction(
() => window.__godsEyeView?.viewer && window.__godsEyeView?.dataManager,
{ timeout: 60000, polling: 200 },
);
const seeded = await page.evaluate(async (name) => {
const { dataManager, viewer } = window.__godsEyeView;
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) await layer.update(viewer);
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
}, LAYER);
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
if (seeded !== contacts.length)
throw new Error(
`the ${LAYER} layer took ${seeded} of ${contacts.length} contacts`,
);
// Past the layer's render delay, so every contact is drawn.
await sleep(20000);
for (const shot of argv.includes('--orbit') ? ORBIT_SHOTS : SHOTS) {
await page.evaluate(
({ shot, centre, altM }) => {
const { viewer } = window.__godsEyeView;
const Cartesian3 = viewer.camera.position.constructor;
const heading = (shot.heading * Math.PI) / 180;
const pitch = (shot.pitch * Math.PI) / 180;
const range = shot.rangeKm * 1000;
// The eye sits `range` back along the way it looks.
const east = -range * Math.sin(heading) * Math.cos(pitch);
const north = -range * Math.cos(heading) * Math.cos(pitch);
const up = -range * Math.sin(pitch);
const lat = centre.lat + north / 111320;
const lon =
centre.lon +
east / (111320 * Math.cos((centre.lat * Math.PI) / 180));
viewer.camera.setView({
destination: Cartesian3.fromDegrees(
lon,
lat,
Math.max(50, altM + up),
),
orientation: { heading, pitch, roll: 0 },
});
viewer.scene.requestRender();
},
{ shot, centre: CENTRE, altM: ALT_FT * 0.3048 },
);
await sleep(shot.settleMs ?? 6000);
// The globe's own canvas, read right after a render: no HUD, dialogs
// or label overlays in the way.
const png = await page.evaluate(() => {
const { viewer } = window.__godsEyeView;
viewer.scene.render();
return viewer.scene.canvas.toDataURL('image/png');
});
const file = path.join(OUT, `${shot.name}.png`);
fs.writeFileSync(file, Buffer.from(png.split(',')[1], 'base64'));
console.log(` wrote ${file}`);
}
} finally {
await browser.close();
}
if (errors.length) {
console.log(`\nConsole errors (${errors.length}):`);
for (const error of errors.slice(0, 20)) console.log(` ${error}`);
process.exitCode = 1;
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
+133 -17
View File
@@ -1,5 +1,10 @@
import path from 'node:path';
import { promises as fsp } from 'node:fs';
import {
makeRateLimiter,
clientKey,
resolvePerMinuteCap,
} from '../common/rate-limit.js';
import { readResponseJsonCapped } from '../common/http.js';
/** Route and aircraft lookups are a few hundred bytes; 1 MiB is a hard bound. */
@@ -12,29 +17,126 @@ const ADSBDB_MAX_RESPONSE_BYTES = 1024 * 1024;
* cached. Adapted from skylight
* (MIT) server/src/enrich/routes.ts.
*/
export function adsbdbProxy() {
export function adsbdbProxy(options = {}) {
// Destructured in the body, not the signature: `proxyErrorResponses.test.mjs`
// extracts these proxies by slicing to the first closing brace in column zero.
const {
cacheMaxEntries = 20_000,
cacheMaxDiskBytes = 16 * 1024 * 1024,
cachePath,
} = options;
const TTL_MS = 24 * 3600_000;
const CACHE_PATH = path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
let cache = { routes: {}, aircraft: {} };
const CACHE_PATH =
cachePath || path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
/**
* Entry ceiling per store.
*
* Both keyspaces are enumerable by the caller — a callsign is 2-8 of
* `[A-Z0-9]`, a hex is six of `[0-9a-f]` — and every distinct key that
* reaches upstream is cached, 404s included. Without a ceiling the maps, and
* the file they are written to, grow for as long as a caller keeps asking.
* Sized from a real session's own file: `.gev-cache/adsbdb.json` held 397
* aircraft entries (~100 B each) and 3 route entries (~231 B each), so
* 20,000 per store is roughly fifty times an ordinary working set and still
* bounds the file at about 7 MB.
*/
const CACHE_MAX_ENTRIES = cacheMaxEntries;
const CACHE_MAX_DISK_BYTES = cacheMaxDiskBytes;
/**
* Requests/minute/IP (`GEV_RATELIMIT_ADSBDB_PER_MIN`; unset takes the
* default, `0` disables). Each browser queue drips at most five lookups a
* second (`ENRICH_DISPATCH_GAP_MS`, 200 ms), and one tab can run two — the
* Flights layer's and Local ADS-B's — so a real session tops out at 600.
* The assistant's aviation tools look up through the same source, unqueued
* but one at a time per tool call. 720 leaves all of that untouched while
* still capping an enumerating caller. The global backstop is the usual
* generous multiple.
*/
const RATE_PER_MIN = resolvePerMinuteCap(
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN,
720,
);
const allow =
RATE_PER_MIN > 0
? makeRateLimiter({
windowMs: 60_000,
max: RATE_PER_MIN,
globalMax: RATE_PER_MIN * 3,
})
: () => true;
// Maps, not plain objects: `size` is O(1), so the ceiling can be enforced on
// every write, and iteration is true insertion order (an all-digit callsign
// like "1234" would sort ahead of everything else as an object key).
let cache = { routes: new Map(), aircraft: new Map() };
let dirty = false;
let loaded = false;
const inflight = new Map();
/** Rehydrate one store, dropping entries that expired while we were down. */
function toStore(raw) {
const store = new Map();
const now = Date.now();
for (const [key, entry] of Object.entries(raw ?? {})) {
const at = Number(entry?.at);
if (!Number.isFinite(at) || now - at >= TTL_MS) continue;
store.set(key, entry);
}
prune(store);
return store;
}
/** Hold the store at its ceiling, dropping least-recently-written first. */
function prune(store) {
while (store.size > CACHE_MAX_ENTRIES) {
const oldest = store.keys().next().value;
if (oldest === undefined) break;
store.delete(oldest);
}
}
/** Write `key` as the newest entry, then restore the ceiling. */
function remember(store, key, entry) {
store.delete(key); // re-insert so insertion order tracks last write
store.set(key, entry);
prune(store);
dirty = true;
}
async function loadOnce() {
if (loaded) return;
loaded = true;
let sizeBytes = null;
try {
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
cache = { routes: parsed.routes ?? {}, aircraft: parsed.aircraft ?? {} };
sizeBytes = (await fsp.stat(CACHE_PATH)).size;
} catch {
/* first run */
sizeBytes = null; // cannot measure it — let the read below decide
}
if (sizeBytes !== null && sizeBytes > CACHE_MAX_DISK_BYTES) {
console.warn('[adsbdb-proxy] cache file above ceiling — starting empty');
} else {
try {
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
cache = {
routes: toStore(parsed.routes),
aircraft: toStore(parsed.aircraft),
};
} catch {
/* first run */
}
}
setInterval(async () => {
if (!dirty) return;
dirty = false;
try {
await fsp.mkdir(path.dirname(CACHE_PATH), { recursive: true });
await fsp.writeFile(CACHE_PATH, JSON.stringify(cache), 'utf8');
await fsp.writeFile(
CACHE_PATH,
JSON.stringify({
routes: Object.fromEntries(cache.routes),
aircraft: Object.fromEntries(cache.aircraft),
}),
'utf8',
);
} catch {
dirty = true;
} // retry next tick
@@ -74,7 +176,7 @@ export function adsbdbProxy() {
function lookup(kind, key) {
const store = kind === 'route' ? cache.routes : cache.aircraft;
if (fresh(store[key])) return Promise.resolve(store[key].data);
if (fresh(store.get(key))) return Promise.resolve(store.get(key).data);
const ik = `${kind}:${key}`;
if (!inflight.has(ik)) {
inflight.set(
@@ -95,18 +197,19 @@ export function adsbdbProxy() {
);
const data =
kind === 'route' ? parseRoute(payload) : parseAircraft(payload);
store[key] = { at: Date.now(), data }; // data may be null — negative cache
dirty = true;
// data may be null — negative cache
remember(store, key, { at: Date.now(), data });
return data;
}
if (res.status === 404) {
store[key] = { at: Date.now(), data: null }; // known-missing — cache the miss
dirty = true;
// known-missing — cache the miss
remember(store, key, { at: Date.now(), data: null });
}
// other statuses: leave uncached so we retry later
return fresh(store[key]) ? store[key].data : null;
return fresh(store.get(key)) ? store.get(key).data : null;
} catch {
return fresh(store[key]) ? store[key].data : null; // network error → stale if any
// network error → stale if any
return fresh(store.get(key)) ? store.get(key).data : null;
} finally {
inflight.delete(ik);
}
@@ -118,11 +221,24 @@ export function adsbdbProxy() {
const installMiddleware = (server) => {
server.middlewares.use('/api/adsbdb', async (req, res) => {
await loadOnce();
const send = (status, obj) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
const send = (status, obj, headers = {}) => {
res.writeHead(status, {
'Content-Type': 'application/json',
...headers,
});
res.end(JSON.stringify(obj));
};
// Before any work: a refused request must not touch the cache, the disk,
// or api.adsbdb.com.
if (!allow(clientKey(req)))
return send(
429,
{ error: 'Rate limit exceeded' },
{
'Retry-After': '10',
},
);
await loadOnce();
try {
const [, kind, rawKey] = String(req.url || '')
.split('?')[0]
+238
View File
@@ -0,0 +1,238 @@
// ADSBDB ENRICHMENT — the keyspace the cache used to remember forever.
//
// `/api/adsbdb` answers `route/<callsign>` and `type/<hex>`. Both keys come
// from the caller: a callsign is 2-8 of [A-Z0-9], a hex is six of [0-9a-f].
// Every distinct key that reached upstream was cached — 404s included — and
// nothing ever removed one, so a caller walking the keyspace grew both the
// in-memory maps and `.gev-cache/adsbdb.json` without bound, at one live
// request to the free community API per new key.
//
// These cases drive the real exported route handler. No network: `fetch` is
// stubbed per test and restored afterwards, so a case that reaches upstream
// fails loudly rather than making a request.
//
// Run with: npm test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import path from 'node:path';
import os from 'node:os';
import { adsbdbProxy } from '../server/providers/aircraft/enrichment.js';
/** Collect a plugin's routes into a path → handler map. */
function install(plugin) {
const routes = new Map();
plugin.configureServer({
middlewares: {
use(routePath, handler) {
routes.set(routePath, handler);
},
},
});
return routes;
}
function request(handler, { url = '/', remoteAddress = '127.0.0.1' } = {}) {
return new Promise((resolve, reject) => {
const headers = new Map();
const req = { method: 'GET', url, headers: {}, socket: { remoteAddress } };
const res = {
statusCode: 200,
writeHead(status, hdrs = {}) {
this.statusCode = status;
for (const [name, value] of Object.entries(hdrs))
headers.set(String(name).toLowerCase(), String(value));
},
end(body = '') {
let parsed = null;
try {
parsed = body ? JSON.parse(String(body)) : null;
} catch {
parsed = String(body);
}
resolve({
statusCode: this.statusCode,
headers: Object.fromEntries(headers),
body: parsed,
});
},
};
Promise.resolve(handler(req, res)).catch(reject);
});
}
/**
* Replace global fetch for the duration of one test, counting the calls the
* cache failed to absorb. Every hex answers with the same aircraft, so a
* second live call for a key we already asked about is a cache miss, nothing
* else.
*/
function stubUpstream(t) {
const asked = [];
const original = globalThis.fetch;
globalThis.fetch = async (url) => {
asked.push(String(url));
return new Response(
JSON.stringify({
response: {
aircraft: {
icao_type: 'B738',
manufacturer: 'Boeing',
type: '737-800',
registration: 'N-FIXTURE',
},
},
}),
{ status: 200 },
);
};
t.after(() => {
globalThis.fetch = original;
});
return asked;
}
/** A cache path inside the OS temp dir: these cases never load or write it. */
const scratchCachePath = () =>
path.join(os.tmpdir(), `gev-adsbdb-fixture-${process.pid}-absent.json`);
const hex = (i) => i.toString(16).padStart(6, '0');
test('an enrichment lookup still answers, and is cached', async (t) => {
const asked = stubUpstream(t);
const routes = install(
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 10 }),
);
const handler = routes.get('/api/adsbdb');
const first = await request(handler, { url: '/type/abc123' });
assert.equal(first.statusCode, 200);
assert.equal(first.body.found, true);
assert.equal(first.body.typeCode, 'B738');
assert.equal(asked.length, 1);
const second = await request(handler, { url: '/type/abc123' });
assert.equal(second.body.typeCode, 'B738');
assert.equal(asked.length, 1, 'a warm key costs no upstream request');
});
test('the cache stops growing, and an evicted key is simply re-fetched', async (t) => {
const asked = stubUpstream(t);
// A ceiling of 3 exercises the same path 20,000 does, in four keys.
const routes = install(
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 3 }),
);
const handler = routes.get('/api/adsbdb');
for (let i = 1; i <= 4; i += 1)
await request(handler, { url: `/type/${hex(i)}` });
assert.equal(asked.length, 4, 'four distinct keys, four upstream requests');
// The newest is still warm...
await request(handler, { url: `/type/${hex(4)}` });
assert.equal(asked.length, 4);
// ...and the oldest was evicted, so it costs exactly one re-fetch, and
// still answers correctly.
const again = await request(handler, { url: `/type/${hex(1)}` });
assert.equal(asked.length, 5);
assert.match(asked[4], new RegExp(`/aircraft/${hex(1)}$`));
assert.equal(again.body.typeCode, 'B738');
});
test('route and aircraft keys are held to the ceiling independently', async (t) => {
const asked = stubUpstream(t);
const routes = install(
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 2 }),
);
const handler = routes.get('/api/adsbdb');
await request(handler, { url: '/type/aaaaaa' });
await request(handler, { url: '/type/bbbbbb' });
// Two callsigns must not push the two hexes out — they are separate stores.
await request(handler, { url: '/route/BAW1' });
await request(handler, { url: '/route/DLH2' });
assert.equal(asked.length, 4);
await request(handler, { url: '/type/aaaaaa' });
assert.equal(asked.length, 4, 'the aircraft store kept its own two keys');
});
test('a caller enumerating the keyspace is refused, and refusal costs nothing', async (t) => {
const asked = stubUpstream(t);
const routes = install(adsbdbProxy({ cachePath: scratchCachePath() }));
const handler = routes.get('/api/adsbdb');
let refused = null;
let served = 0;
// Each client queue drips one lookup per ENRICH_DISPATCH_GAP_MS (200 ms),
// and one tab runs two (Flights and Local ADS-B): 600/min must fit.
for (let i = 0; i < 1000 && !refused; i += 1) {
const res = await request(handler, { url: `/type/${hex(i)}` });
if (res.statusCode === 429) refused = res;
else served += 1;
}
assert.ok(refused, 'an unbounded sweep is eventually refused');
assert.equal(refused.body.error, 'Rate limit exceeded');
assert.equal(refused.headers['retry-after'], '10');
assert.ok(
served >= 600,
`both client queues together (600/min) must fit; served ${served}`,
);
assert.equal(
asked.length,
served,
'a refused request never reaches api.adsbdb.com',
);
});
test('a different client keeps its own budget', async (t) => {
stubUpstream(t);
const routes = install(adsbdbProxy({ cachePath: scratchCachePath() }));
const handler = routes.get('/api/adsbdb');
let noisy = 0;
for (let i = 0; i < 1000; i += 1) {
const res = await request(handler, {
url: `/type/${hex(i)}`,
remoteAddress: '10.0.0.1',
});
if (res.statusCode === 200) noisy += 1;
}
assert.ok(noisy > 0 && noisy < 1000, 'the noisy client was throttled');
const quiet = await request(handler, {
url: '/type/ffffff',
remoteAddress: '10.0.0.2',
});
assert.equal(quiet.statusCode, 200, 'a quiet client is not collateral');
});
test('GEV_RATELIMIT_ADSBDB_PER_MIN sets the cap, and 0 turns it off', async (t) => {
stubUpstream(t);
const original = process.env.GEV_RATELIMIT_ADSBDB_PER_MIN;
t.after(() => {
if (original === undefined) delete process.env.GEV_RATELIMIT_ADSBDB_PER_MIN;
else process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = original;
});
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '5';
const tight = install(adsbdbProxy({ cachePath: scratchCachePath() })).get(
'/api/adsbdb',
);
const statuses = [];
for (let i = 0; i < 6; i += 1)
statuses.push(
(await request(tight, { url: `/type/${hex(i)}` })).statusCode,
);
assert.deepEqual(statuses, [200, 200, 200, 200, 200, 429]);
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '0';
const open = install(adsbdbProxy({ cachePath: scratchCachePath() })).get(
'/api/adsbdb',
);
for (let i = 0; i < 1500; i += 1) {
const res = await request(open, { url: `/type/${hex(i)}` });
assert.equal(res.statusCode, 200, `request ${i} with the limiter off`);
}
});
+12 -42
View File
@@ -33,7 +33,6 @@ import {
} from './aircraftIcons.js';
import { cockpitContactDotImage } from './cockpitContactDot.js';
import { rotorFrame, rotorTurns } from './rotorFrames.js';
import { registerAircraftViews, withAircraftView } from './aircraftViews.js';
import { aircraftRecedeSpec } from './aircraftRecession.js';
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
@@ -437,8 +436,6 @@ function fixedDelay(ms) {
* Where a host-supplied placement draws a live contact at a wall time,
* written into `out` (`placeAircraftAt`), or null when it does not place
* it; none without a placement.
* @param {(url: string) => string} [options.resolveAsset] The layer's asset
* URL resolver, for the aircraft view sheet's image.
*/
export function createAircraftIcons({
state,
@@ -456,14 +453,10 @@ export function createAircraftIcons({
afterSettle = () => {},
onForget = () => {},
placeAt = null,
resolveAsset = (url) => url,
}) {
const { focusPassIsNeeded } = services.focus;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** Whether the renderer draws icons along their course from the aircraft
* view sheet (`aircraftViews.js`), set when the draw set is made. */
let views = false;
/**
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
* frame each was last drawn at, and the frame it was last judged at
@@ -551,9 +544,9 @@ export function createAircraftIcons({
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
const capabilities = rendererOf(viewer)?.capabilities ?? null;
views = registerAircraftViews(drawOf(viewer), capabilities, resolveAsset);
state._icons = createContactIcons(set, { capabilities });
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
});
return set.id;
}
@@ -562,7 +555,6 @@ export function createAircraftIcons({
state._icons?.dispose();
state._icons = null;
liveSet = null;
views = false;
rotors.clear();
planFrom.clear();
easeEnds.clear();
@@ -970,26 +962,19 @@ export function createAircraftIcons({
* How a contact's icon is drawn outside Cockpit: its image (and the sharper
* one it switches to up close), size, scale and scale by distance. The
* tracked contact's own icon is drawn with this too, so selecting a contact
* changes its colour and nothing else. Drawn along its course
* (`alongCourse`) on a renderer that draws view sheets, a kind with
* rendered views draws from the aircraft view sheet, with no near image
* (`aircraftViews.js`); otherwise it is the flat glyph.
* changes its colour and nothing else.
* @param {string} icao24
* @param {object} [info] Its record.
* @param {number} [frame] A helicopter's rotor frame.
* @param {{alongCourse?: boolean}} [options]
* @returns {{image: string|{views: string, first: number},
* imageLod: {near: string, switchPx: number}|undefined,
* @returns {{image: string, imageLod: {near: string, switchPx: number},
* size: [number, number], scale: number, scaleByDistance: object}}
*/
function _fleetLook(
icao24,
info = state.records.data.get(icao24),
frame = _rotorFrameOf(icao24, info, Date.now()),
{ alongCourse = false } = {},
) {
const rendering = parts.rendering;
const look = {
return {
image: aircraftIcon(
rendering._iconKind(icao24, info?.klass),
FLEET_ICON_PX,
@@ -1007,17 +992,6 @@ export function createAircraftIcons({
scale: rendering._fleetBillboardScale(icao24),
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
};
return withAircraftView(look, {
views,
kind: rendering._iconKind(icao24, info?.klass),
frame,
rotationMode: alongCourse ? 'course' : undefined,
});
}
/** Whether contacts drawn along their course draw from the view sheet. */
function _drawsViews() {
return views;
}
/**
@@ -1077,7 +1051,6 @@ export function createAircraftIcons({
id,
state.records.data.get(id),
frame,
{ alongCourse: icons.item(id)?.rotationMode === 'course' },
);
icons.update(id, { image, imageLod });
}
@@ -1091,11 +1064,6 @@ export function createAircraftIcons({
const rendering = parts.rendering;
const info = state.records.data.get(icao24);
const tracked = icao24 === state._trackedIcao;
// A helicopter's rotor frame, chosen once for its look and its rotor.
const heliFrame = _rotorFrameOf(icao24, info, Date.now());
// A ground station's mast stands upright; every other glyph turns
// along its course.
const station = info?.klass === 'station';
const cockpitDot =
state._cockpitContactMode &&
!tracked &&
@@ -1111,18 +1079,21 @@ export function createAircraftIcons({
rotationMode: 'screen',
}
: {
..._fleetLook(icao24, info, heliFrame, { alongCourse: !station }),
..._fleetLook(icao24, info),
color: rgba(rendering._fleetBillboardColor(icao24, info)),
rotationMode: 'course',
};
if (!cockpitDot && station) {
// A ground station's mast stands upright.
if (!cockpitDot && info?.klass === 'station') {
look.rotationMode = 'screen';
look.rotation = 0;
}
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
icons.update(icao24, look);
// An airborne helicopter drawn as its glyph turns its rotor.
const frame = cockpitDot ? undefined : heliFrame;
const frame = cockpitDot
? undefined
: _rotorFrameOf(icao24, info, Date.now());
if (frame === undefined || !rotorTurns(_rotorState(info))) {
// A tracked helicopter that lands shows the still frame at once.
if (rotors.delete(icao24) && tracked)
@@ -1205,7 +1176,6 @@ export function createAircraftIcons({
_focusIcons,
_applyIconPresentation,
_fleetLook,
_drawsViews,
_turnRotors,
_rotorsTurning,
_addIcon,
-180
View File
@@ -481,183 +481,3 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/**
* An icon layer on a renderer that does (or does not) draw view sheets,
* over contacts `records` (by id), all held at one place.
*/
function viewsFixture(
records,
{ viewSheets = true, kinds = {}, resolveAsset } = {},
) {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer, {
capabilities: new Set(viewSheets ? ['viewSheets'] : []),
});
const state = {
_viewer: viewer,
now: () => Date.now(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (id, klass) => kinds[id] ?? klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1.25,
_cockpitContactColor: () => [1, 0, 0, 1],
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
resolveAsset,
});
icons._createIcons(viewer);
const here = fromDegrees(0, 30, 300);
for (const id of records.keys()) {
state._icons.put(
{ id, pos: here, motion: { kind: 'hold', courseDeg: 0 }, size: [20, 20] },
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons, registered: draw.viewSheets, here, unbind };
}
test('with view sheets, every aircraft class draws from the sheet along its course, with no near image', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const records = new Map([
['p1', { klass: 'airliner' }],
['p2', { klass: 'glider' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, icons, registered, unbind } = viewsFixture(records);
t.after(unbind);
assert.deepEqual(registered, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftViewRef('airliner'));
assert.equal(p1.imageLod, undefined);
assert.equal(p1.rotationMode, 'course');
// Everything else is as the flat glyph draws it.
assert.deepEqual(p1.size, [20, 20]);
assert.equal(p1.scale, 1.25);
assert.deepEqual(p1.color, [1, 1, 1, 1]);
assert.equal(p1.scaleByDistance.nearValue, 3);
assert.equal(state._icons.item('p2').image, aircraftViewRef('glider'));
assert.equal(
state._icons.item('h1').image,
aircraftViewRef('helicopter', ROTOR_STILL_FRAME),
);
// The plain fleet look (the tracked icon's sizing, a screen-rotated
// caller) stays the flat glyph.
assert.equal(
icons._fleetLook('p1').image,
aircraftIcon('airliner', FLEET_ICON_PX),
);
assert.equal(
icons._fleetLook('p1', undefined, undefined, { alongCourse: true }).image,
aircraftViewRef('airliner'),
);
assert.equal(icons._drawsViews(), true);
icons._disposeIcons();
assert.equal(icons._drawsViews(), false);
});
test('without view sheets the icons are the flat glyphs with their near image, as before', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['p1', { klass: 'airliner' }]]);
const { state, icons, registered, unbind } = viewsFixture(records, {
viewSheets: false,
});
t.after(unbind);
assert.deepEqual(registered, [], 'no sheet is registered');
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftIcon('airliner', FLEET_ICON_PX));
assert.equal(p1.imageLod.near, aircraftIcon('airliner', 192));
assert.equal(p1.rotationMode, 'course');
assert.equal(icons._drawsViews(), false);
});
test('with view sheets, the TR-3B, airport vehicles and ground stations stay flat', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['x1', { klass: 'airliner' }],
['v1', { klass: 'vehicle' }],
['s1', { klass: 'station' }],
]);
const { state, unbind } = viewsFixture(records, {
kinds: { x1: 'tr3b' },
});
t.after(unbind);
assert.equal(
state._icons.item('x1').image,
aircraftIcon('tr3b', FLEET_ICON_PX),
);
assert.ok(state._icons.item('x1').imageLod);
assert.equal(
state._icons.item('v1').image,
aircraftIcon('vehicle', FLEET_ICON_PX),
);
const mast = state._icons.item('s1');
assert.equal(mast.image, aircraftIcon('station', FLEET_ICON_PX));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('with view sheets, an airborne helicopter turns its rotor through the sheet’s three blocks', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
const { state, icons, unbind } = viewsFixture(records);
t.after(unbind);
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now());
const item = state._icons.item('h1');
assert.equal(item.imageLod, undefined);
seen.add(item.image);
}
assert.deepEqual(
new Set(seen),
new Set([0, 1, 2].map((frame) => aircraftViewRef('helicopter', frame))),
);
});
test('the layer registers the view sheet at its own asset URL', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const { registered, unbind } = viewsFixture(
new Map([['p1', { klass: 'airliner' }]]),
{ resolveAsset: (url) => `/gev/${url.replace(/^\//, '')}` },
);
t.after(unbind);
assert.equal(registered.length, 1);
assert.equal(registered[0][0], AIRCRAFT_VIEWS.id);
assert.equal(registered[0][1].image, '/gev/sprites/aircraft-views.webp');
});
test('a view carries the contact’s flat glyph as its fallback', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['p1', { klass: 'turboprop' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, unbind } = viewsFixture(records);
t.after(unbind);
assert.equal(
state._icons.item('p1').image.fallback,
aircraftIcon('turboprop', FLEET_ICON_PX),
);
assert.equal(
state._icons.item('h1').image.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
-138
View File
@@ -1,138 +0,0 @@
/**
* @module data/aircraftViews
* @description Which block of the aircraft view sheet (`viewSheet.js`) a
* contact's icon draws from. Each aircraft class is rendered there from a
* sphere of camera angles; a renderer with the `viewSheets` capability lays
* the icon flat on the earth along its course and draws the view that
* matches where the eye is, so an oblique contact looks solid instead of
* like a paper cut-out. Only an icon drawn along its course
* (`rotationMode: 'course'`) can do this: a screen-rotated or upright icon
* keeps its flat glyph. Kinds with no rendered views (the TR-3B triangle,
* airport vehicles, ground stations) keep their flat glyph as well.
*/
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import {
aircraftIcon,
FLEET_ICON_PX,
ROTOR_FRAMES,
ROTOR_STILL_FRAME,
} from './aircraftIcons.js';
/** The renderer capability that draws view sheets. */
export const VIEW_SHEETS_CAPABILITY = 'viewSheets';
/** Kinds drawn from the sheet with one block each (helicopters have three). */
const STILL_KINDS = new Set([
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
]);
/** One frozen image ref per block, so equal refs are the same object. */
const refs = new Map();
/**
* The ref of the block at `first`, with the flat glyph of `kind` (and its
* rotor `frame`) as its fallback: what the renderer draws until the sheet
* has loaded, and for good if it cannot load.
*/
function refAt(first, kind, frame) {
let ref = refs.get(first);
if (!ref) {
ref = Object.freeze({
views: AIRCRAFT_VIEWS.id,
first,
fallback: aircraftIcon(kind, FLEET_ICON_PX, frame),
});
refs.set(first, ref);
}
return ref;
}
/**
* The view image of an icon kind: `{views, first, fallback}`, the sheet's
* id, the first cell of the kind's block and its flat glyph (drawn while
* the sheet loads, or if it fails), or null for a kind with no views.
* @param {string} kind An icon kind (`rendering._iconKind`).
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame otherwise, as `aircraftIcon` takes it).
* @returns {{views: string, first: number, fallback: string}|null}
*/
export function aircraftViewRef(kind, frame) {
const subjects = AIRCRAFT_VIEWS.subjects;
if (kind === 'helicopter') {
const f =
Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME;
const first = subjects[`helicopter${f}`];
return Number.isInteger(first) ? refAt(first, kind, f) : null;
}
if (!STILL_KINDS.has(kind)) return null;
const first = subjects[kind];
return Number.isInteger(first) ? refAt(first, kind) : null;
}
/** Whether an icon image is a view-sheet ref. */
export function isAircraftViewRef(image) {
return Boolean(image) && typeof image === 'object' && 'views' in image;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the aircraft view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerAircraftViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.(VIEW_SHEETS_CAPABILITY)) return false;
if (!registered.has(drawPort)) {
const sheet = AIRCRAFT_VIEWS.sheet;
drawPort.views(AIRCRAFT_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
/**
* An icon's look drawn from the view sheet where it can be: with views on,
* the item drawn along its course and the kind rendered, the image is the
* view ref and there is no near image (`imageLod: undefined`, so an update
* clears it); otherwise the look as given, the very same object.
* @template {{image: unknown, imageLod?: unknown}} T
* @param {T} look
* @param {object} options
* @param {boolean} options.views Whether the renderer draws views
* (`registerAircraftViews`).
* @param {string} options.kind The icon kind.
* @param {number} [options.frame] A helicopter's rotor frame.
* @param {string} [options.rotationMode] How the item is rotated.
* @returns {T}
*/
export function withAircraftView(look, { views, kind, frame, rotationMode }) {
if (!views || rotationMode !== 'course') return look;
const ref = aircraftViewRef(kind, frame);
if (!ref) return look;
return { ...look, image: ref, imageLod: undefined };
}
-175
View File
@@ -1,175 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
aircraftViewRef,
isAircraftViewRef,
registerAircraftViews,
VIEW_SHEETS_CAPABILITY,
withAircraftView,
} from './aircraftViews.js';
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './rotorFrames.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
const STILL_KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
];
test('every aircraft class draws its own block of the view sheet', () => {
for (const kind of STILL_KINDS)
assert.deepEqual(
aircraftViewRef(kind),
{
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects[kind],
fallback: aircraftIcon(kind, FLEET_ICON_PX),
},
kind,
);
const firsts = STILL_KINDS.map((kind) => aircraftViewRef(kind).first);
assert.equal(
new Set(firsts).size,
STILL_KINDS.length,
'no two share a block',
);
assert.equal(
aircraftViewRef('airliner'),
aircraftViewRef('airliner'),
'one ref per block, so an unchanged image writes nothing',
);
assert.ok(Object.isFrozen(aircraftViewRef('airliner')));
});
test('a helicopter draws the block of its rotor frame, the still frame by default', () => {
assert.equal(ROTOR_FRAMES, 3);
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
const ref = aircraftViewRef('helicopter', frame);
assert.equal(
ref.first,
AIRCRAFT_VIEWS.subjects[`helicopter${frame}`],
`frame ${frame}`,
);
assert.equal(
ref.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, frame),
`its fallback is the glyph of rotor frame ${frame}`,
);
}
assert.equal(
aircraftViewRef('helicopter').fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const still = AIRCRAFT_VIEWS.subjects[`helicopter${ROTOR_STILL_FRAME}`];
for (const frame of [undefined, -1, 3, 1.5, NaN])
assert.equal(aircraftViewRef('helicopter', frame).first, still, `${frame}`);
});
test('the TR-3B, airport vehicles, ground stations and unknown kinds have no views', () => {
for (const kind of [
'tr3b',
'tr3bHot',
'vehicle',
'station',
'jet',
'',
undefined,
])
assert.equal(aircraftViewRef(kind), null, String(kind));
assert.equal(
aircraftViewRef('airliner', 1).first,
0,
'a frame means nothing to a fixed wing',
);
});
test('a view ref is told apart from flat images', () => {
assert.equal(isAircraftViewRef(aircraftViewRef('glider')), true);
for (const image of [
'data:image/svg+xml;base64,AAA',
null,
undefined,
{ atlas: 'a', slot: 's' },
])
assert.equal(isAircraftViewRef(image), false, String(image));
});
test('the sheet is registered once per draw port, only with the capability', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
assert.equal(VIEW_SHEETS_CAPABILITY, 'viewSheets');
assert.equal(registerAircraftViews(port, new Set()), false);
assert.equal(registerAircraftViews(port, null), false);
assert.equal(calls.length, 0, 'nothing registered without the capability');
assert.equal(registerAircraftViews(port, caps), true);
assert.equal(registerAircraftViews(port, caps), true);
assert.deepEqual(calls, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const other = { views: (id) => calls.push([id]) };
assert.equal(registerAircraftViews(other, caps), true);
assert.equal(calls.length, 2, 'a second port registers its own');
assert.equal(
registerAircraftViews({}, caps),
false,
'a port without views()',
);
assert.equal(registerAircraftViews(null, caps), false);
});
test('a look takes the view only when views are on and it is drawn along its course', () => {
const look = {
image: 'flat',
imageLod: { near: 'near', switchPx: 30 },
size: [20, 20],
scale: 1.5,
};
const on = { views: true, kind: 'airliner', rotationMode: 'course' };
const viewed = withAircraftView(look, on);
assert.deepEqual(viewed, {
image: aircraftViewRef('airliner'),
imageLod: undefined,
size: [20, 20],
scale: 1.5,
});
assert.ok('imageLod' in viewed, 'imageLod is cleared, so an update drops it');
assert.equal(look.image, 'flat', 'the look given is left as it was');
assert.equal(withAircraftView(look, { ...on, views: false }), look);
assert.equal(withAircraftView(look, { ...on, rotationMode: 'screen' }), look);
assert.equal(
withAircraftView(look, { ...on, rotationMode: undefined }),
look,
);
assert.equal(withAircraftView(look, { ...on, kind: 'tr3b' }), look);
assert.equal(withAircraftView(look, { ...on, kind: 'station' }), look);
assert.equal(
withAircraftView(look, { ...on, kind: 'helicopter', frame: 2 }).image,
aircraftViewRef('helicopter', 2),
);
});
test('the sheet is registered with its image resolved as the layer resolves its assets', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
registerAircraftViews(port, caps, (url) => `https://cdn.example/app${url}`);
assert.equal(calls.length, 1);
const [id, sheet] = calls[0];
assert.equal(id, AIRCRAFT_VIEWS.id);
assert.equal(
sheet.image,
'https://cdn.example/app/sprites/aircraft-views.webp',
);
assert.deepEqual(
{ ...sheet, image: AIRCRAFT_VIEWS.sheet.image },
{ ...AIRCRAFT_VIEWS.sheet },
'the layout as it is',
);
assert.equal(AIRCRAFT_VIEWS.sheet.image, '/sprites/aircraft-views.webp');
});
+2 -2
View File
@@ -42,8 +42,8 @@ export const MAX_ICON_SLOTS = 176;
export const MIN_ICON_SLOTS = 64;
/**
* Vertex uniform vectors the icon shader keeps for everything else: its own
* and the renderer's (about 45, the view sheet's layout among them), with
* room for drivers that keep constants in uniforms.
* and the renderer's (about 34), with room for drivers that keep constants
* in uniforms.
*/
const OTHER_VERTEX_UNIFORMS = 80;
-6
View File
@@ -100,12 +100,6 @@ export const ICON_RECEDES = 4;
* −31 m before its floor warms) otherwise reads as beyond the limb.
*/
export const ICON_CULL_LIFT = 8;
/**
* The row's image is a subject of the set's view sheet
* ({@link module:viewSheet}): its far image is the subject's first cell, and
* the renderer draws the frame that shows it from the eye.
*/
export const ICON_VIEWS = 16;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/**
+5 -20
View File
@@ -15,14 +15,8 @@
* pick names the set and the contact's id, as the fleet icons' do.
* `visible` hides the icon while it stays shown (Cockpit flies the
* aircraft from its own seat).
*
* Given a view-sheet image (`aircraftViews.js`) and a course reader, it is
* drawn along that course instead (`rotationMode: 'course'`), as the fleet
* icons are, so the renderer draws the view of the aircraft that matches
* the eye and tracking a contact does not flatten it.
*/
import { findDraw, findFrame } from '../render/rendererOf.js';
import { isAircraftViewRef } from './aircraftViews.js';
/** Uniquifier for the sets' ids. */
let instances = 0;
@@ -111,21 +105,18 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
function draw() {
if (!shown || !set) return;
const pos = shown.position();
const alongCourse =
typeof shown.course === 'function' && isAircraftViewRef(shown.image);
const item = {
id: shown.id,
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
show: Boolean(pos) && visible,
image: shown.image,
...(shown.imageLod && !alongCourse ? { imageLod: shown.imageLod } : {}),
...(shown.imageLod ? { imageLod: shown.imageLod } : {}),
size: [shown.sprite.width, shown.sprite.height],
scale: shown.sprite.scale,
scaleByDistance: shown.sprite.scaleByDistance,
color: shown.color(),
...(alongCourse
? { rotationMode: 'course', course: pos ? shown.course() : 0 }
: { rotationMode: 'screen', rotation: pos ? shown.rotation() : 0 }),
rotationMode: 'screen',
rotation: pos ? shown.rotation() : 0,
disableDepthTest: Number.POSITIVE_INFINITY,
};
if (
@@ -141,9 +132,7 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
written.size[0] === item.size[0] &&
written.size[1] === item.size[1] &&
written.scale === item.scale &&
written.rotationMode === item.rotationMode &&
written.rotation === item.rotation &&
written.course === item.course &&
sameColor(written.color, item.color)
)
return;
@@ -157,17 +146,13 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
* next one on.
* @param {object} target
* @param {string} target.id The contact's id.
* @param {string|{views: string, first: number}} target.image A flat
* glyph, or a view-sheet image (drawn along `course`).
* @param {string} target.image
* @param {{near: string, switchPx: number}} [target.imageLod] The
* sharper image a flat glyph switches to once drawn larger than
* `switchPx`.
* sharper image it switches to once drawn larger than `switchPx`.
* @param {{width: number, height: number, scale: number,
* scaleByDistance: object}} target.sprite Read each frame.
* @param {() => object|null} target.position ECEF this frame; none hides it.
* @param {() => number} target.rotation Screen radians, counter-clockwise.
* @param {() => number} [target.course] Degrees clockwise from north;
* required with a view-sheet image, which only draws along a course.
* @param {() => object} target.color The tint this frame.
*/
show(target) {
-49
View File
@@ -199,52 +199,3 @@ test('the tracked icon keeps its contact\'s colour; only the alpha changes', ()
assert.ok(Object.isFrozen(stale));
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
});
test('given a view-sheet image and a course, the tracked icon is drawn along its course with no near image', async () => {
const { aircraftViewRef } = await import('./aircraftViews.js');
const { viewer, draw, tick } = harness();
const icon = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'flights',
});
let course = 45;
let rotations = 0;
icon.show({
id: 'abc123',
image: aircraftViewRef('airliner'),
imageLod: { near: 'near', switchPx: 30 },
sprite: SPRITE,
position: () => ({ x: 1, y: 2, z: 3 }),
rotation: () => {
rotations++;
return 0.5;
},
course: () => course,
color: () => [0, 1, 1, 1],
});
const set = draw.find('flights-tracked-icon:');
tick();
const item = set.items.get('abc123');
assert.equal(item.image, aircraftViewRef('airliner'));
assert.equal('imageLod' in item, false);
assert.equal(item.rotationMode, 'course');
assert.equal(item.course, 45);
assert.equal('rotation' in item, false);
assert.equal(rotations, 0, 'no screen rotation is projected');
assert.deepEqual(item.size, [28, 28]);
const writes = set.writes;
tick();
assert.equal(set.writes, writes, 'an unchanged frame writes nothing');
course = 50;
tick();
assert.equal(set.items.get('abc123').course, 50);
// A flat image (a TR-3B conversion, a ground station) turns on screen again.
icon.setImage('data:image/svg+xml;base64,AAA', { near: 'near', switchPx: 30 });
tick();
const flat = set.items.get('abc123');
assert.equal(flat.rotationMode, 'screen');
assert.equal(flat.rotation, 0.5);
assert.deepEqual(flat.imageLod, { near: 'near', switchPx: 30 });
assert.equal('course' in flat, false);
icon.dispose();
});
-256
View File
@@ -1,256 +0,0 @@
/**
* @module viewSheet
* @description A view sheet: one image of small sprites showing a subject
* (an aircraft class) from a sphere of directions, and the maths that picks
* the sprite for where the eye is. Plain JavaScript and GLSL: no DOM, no
* engine. `scripts/build-aircraft-view-sheet.py` bakes the aircraft sheet to
* this layout; a renderer with the `viewSheets` capability draws it.
*
* **Frames.** A subject lies flat on the earth: up is the ground's normal,
* forward its course. `d` is the direction from the subject to the eye in
* the subject's own axes `[forward, right, up]`. A sheet holds each subject
* as a block of consecutive cells, row-major: rings of frames `ringStepDeg`
* apart, from straight above (ring 0) downward, ring `k` holding `rings[k]`
* frames from the eye dead ahead, round the right side, to dead astern. The
* left side is the right-side frame mirrored, so a sheet's subjects and
* their light are symmetric about their centre plane.
*
* **Roll.** A frame's image up is {@link frameUp}: forward, turned by the
* smallest rotation that takes up onto the frame's direction. Straight
* above, the nose points up the image; the roll then changes smoothly all
* the way round and below. It has no meaning only from straight below, so a
* sheet's last ring stays short of that.
*
* **Between frames.** The frame nearest the eye's direction is drawn
* ({@link viewFrame}), as a card standing where its subject is, square to
* the frame's own direction: seen from a little to one side it is tilted
* (foreshortened and turned) as the subject itself would be, until the next
* frame is the nearer. Frames are not blended.
*/
/** Rings a sheet may hold (the shader's uniform array); even. */
export const VIEW_RINGS_MAX = 18;
/** The aircraft classes' view sheet (`public/sprites/aircraft-views.json`). */
export const AIRCRAFT_VIEWS = Object.freeze({
id: 'aircraft-views',
sheet: Object.freeze({
image: '/sprites/aircraft-views.webp',
cellPx: 64,
columns: 64,
rows: 57,
ringStepDeg: 7.5,
rings: Object.freeze([
1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22,
]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 302,
/** Each subject's first cell. */
subjects: Object.freeze({
airliner: 0,
widebody: 302,
quadjet: 604,
turboprop: 906,
light: 1208,
glider: 1510,
fastjet: 1812,
bizjet: 2114,
uav: 2416,
helicopter0: 2718,
helicopter1: 3020,
helicopter2: 3322,
}),
});
/**
* Check a sheet's layout, and return it with each ring's first frame.
* @param {{image: string, cellPx: number, columns: number, rows: number,
* ringStepDeg: number, rings: readonly number[], grey?: boolean}} sheet
* @returns {{columns: number, rows: number, ringStepRad: number,
* rings: number[], firsts: number[], frames: number}}
*/
export function viewLayout(sheet) {
const whole = (n) => Number.isInteger(n) && n > 0;
if (!sheet || typeof sheet.image !== 'string' || !sheet.image)
throw new TypeError('a view sheet needs its image URL');
if (!whole(sheet.cellPx) || !whole(sheet.columns) || !whole(sheet.rows))
throw new TypeError(
'a view sheet needs whole cellPx, columns and rows above 0',
);
const { rings, ringStepDeg } = sheet;
if (
!Array.isArray(rings) ||
rings.length < 1 ||
rings.length > VIEW_RINGS_MAX ||
!rings.every(whole)
)
throw new TypeError(
`a view sheet needs 1 to ${VIEW_RINGS_MAX} rings of whole frame counts`,
);
if (rings[0] !== 1)
throw new TypeError("a view sheet's first ring is the one frame above");
if (
!(ringStepDeg > 0) ||
!Number.isFinite(ringStepDeg) ||
(rings.length - 1) * ringStepDeg >= 180
)
throw new TypeError("a view sheet's rings stop short of straight below");
const firsts = [];
let frames = 0;
for (const count of rings) {
firsts.push(frames);
frames += count;
}
return {
columns: sheet.columns,
rows: sheet.rows,
ringStepRad: (ringStepDeg * Math.PI) / 180,
rings: [...rings],
firsts,
frames,
};
}
/**
* The frame that shows a subject from `d`.
* @param {ReturnType<typeof viewLayout>} layout
* @param {readonly [number, number, number]} d Toward the eye, as
* `[forward, right, up]`; any length above 0.
* @returns {{frame: number, ring: number, index: number, mirrored: boolean}}
* `frame` counts from the subject's first cell; `mirrored` draws it flipped
* left to right (the eye on the left side).
*/
export function viewFrame(layout, d) {
const length = Math.hypot(d[0], d[1], d[2]);
const up = length > 0 ? Math.min(1, Math.max(-1, d[2] / length)) : 1;
const ring = Math.min(
layout.rings.length - 1,
Math.floor(Math.acos(up) / layout.ringStepRad + 0.5),
);
const span = layout.rings[ring] - 1;
const side = Math.abs(d[1]);
const bearing = side + Math.abs(d[0]) > 0 ? Math.atan2(side, d[0]) : 0;
const index = span > 0 ? Math.floor((bearing / Math.PI) * span + 0.5) : 0;
return {
frame: layout.firsts[ring] + index,
ring,
index,
mirrored: d[1] < 0,
};
}
/**
* The direction a frame shows its subject from: a unit `[forward, right,
* up]`, on the right side (or the left, mirrored).
*/
export function frameDirection(layout, ring, index, mirrored = false) {
const off = ring * layout.ringStepRad;
const span = layout.rings[ring] - 1;
const turn = span > 0 ? (index / span) * Math.PI : 0;
return [
Math.sin(off) * Math.cos(turn),
Math.sin(off) * Math.sin(turn) * (mirrored ? -1 : 1),
Math.cos(off),
];
}
/**
* A frame's image up, for the unit direction `d` it shows its subject from:
* forward, turned as up turns onto `d`. A unit `[forward, right, up]`,
* perpendicular to `d`.
*/
export function frameUp(d) {
const k = 1 / Math.max(1 + d[2], 1e-6);
return [1 - d[0] * d[0] * k, -d[0] * d[1] * k, -d[0]];
}
/**
* A sheet's layout as the shader's uniforms: `grid`, and `rings` as one
* vector for each two rings (`[frames, first, frames, first]`).
*/
export function viewUniforms(layout) {
const rings = [];
for (let k = 0; k < VIEW_RINGS_MAX; k += 2)
rings.push([
layout.rings[k] ?? 1,
layout.firsts[k] ?? 0,
layout.rings[k + 1] ?? 1,
layout.firsts[k + 1] ?? 0,
]);
return {
grid: [
layout.columns,
layout.rows,
layout.ringStepRad,
layout.rings.length,
],
rings,
};
}
/**
* {@link viewFrame}, {@link frameDirection} and {@link frameUp} in GLSL, over `u_viewGrid` (columns, rows, ring step in radians, rings) and
* `u_viewRings` (each ring's frames and first frame, two rings a vector).
*/
export const VIEW_SHEET_GLSL = /* glsl */ `
uniform vec4 u_viewGrid;
uniform vec4 u_viewRings[${VIEW_RINGS_MAX / 2}];
// A ring's frames and its first frame, from the subject's first cell.
vec2 viewRing(float ring) {
vec4 pair = u_viewRings[int(ring * 0.5)];
return ring - 2.0 * floor(ring * 0.5) < 0.5 ? pair.xy : pair.zw;
}
// The frame that shows a subject from d (unit, toward the eye, as forward,
// right, up): its ring, its index in the ring, and 1 when it is drawn
// mirrored (the eye on the left side).
vec3 viewNearest(vec3 d) {
float ring = clamp(
floor(acos(clamp(d.z, -1.0, 1.0)) / u_viewGrid.z + 0.5),
0.0, u_viewGrid.w - 1.0);
float span = viewRing(ring).x - 1.0;
float side = abs(d.y);
float bearing = side + abs(d.x) > 0.0 ? atan(side, d.x) : 0.0;
return vec3(
ring,
span > 0.0 ? floor(bearing / 3.141592653589793 * span + 0.5) : 0.0,
d.y < 0.0 ? 1.0 : 0.0);
}
// The direction a frame shows its subject from (toward the eye, as forward,
// right, up; flip 1 for the left side) and the frame's image up.
void viewFrameAxes(float ring, float index, float flip, out vec3 toEye, out vec3 up) {
float span = viewRing(ring).x - 1.0;
float off = ring * u_viewGrid.z;
float turn = span > 0.0 ? index / span * 3.141592653589793 : 0.0;
toEye = vec3(
sin(off) * cos(turn),
sin(off) * sin(turn) * (1.0 - 2.0 * flip),
cos(off));
float k = 1.0 / max(1.0 + toEye.z, 1.0e-6);
up = vec3(1.0 - toEye.x * toEye.x * k, -toEye.x * toEye.y * k, -toEye.x);
}
`;
/**
* Reading a view sheet's cells in a fragment shader: `viewCell(cell, uv,
* lod)` is the colour of a cell at `uv` (0..1 across it, v down) and that
* level of detail, nothing outside it, from `u_views` over `u_viewGrid`.
*/
export const VIEW_SHEET_FRAGMENT_GLSL = /* glsl */ `
uniform sampler2D u_views;
uniform vec4 u_viewGrid;
vec4 viewCell(float cell, vec2 uv, float lod) {
float at = floor(cell + 0.5);
float row = floor((at + 0.5) / u_viewGrid.x);
float column = at - row * u_viewGrid.x;
vec2 inside = step(vec2(0.0), uv) * step(uv, vec2(1.0));
vec4 color = textureLod(
u_views, (vec2(column, row) + clamp(uv, 0.0, 1.0)) / u_viewGrid.xy, lod);
return color * (inside.x * inside.y);
}
`;
-379
View File
@@ -1,379 +0,0 @@
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import {
AIRCRAFT_VIEWS,
frameDirection,
frameUp,
viewFrame,
viewLayout,
viewUniforms,
VIEW_RINGS_MAX,
} from './viewSheet.js';
const layout = viewLayout(AIRCRAFT_VIEWS.sheet);
const RAD = Math.PI / 180;
const HORIZON = 12; // the ring at 90° from straight above
/** The pinned layout: rings 7.5° apart, 302 frames a subject. */
const RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22];
const FIRSTS = [
0, 1, 5, 12, 22, 35, 51, 69, 89, 111, 134, 158, 183, 208, 233, 257, 280,
];
/** A unit `[forward, right, up]` `offDeg` from straight above, at `bearingDeg`
* from dead ahead toward the right side. */
function direction(offDeg, bearingDeg) {
const off = offDeg * RAD;
const bearing = bearingDeg * RAD;
return [
Math.sin(off) * Math.cos(bearing),
Math.sin(off) * Math.sin(bearing),
Math.cos(off),
];
}
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const mirror = (v) => [v[0], -v[1], v[2]];
const near = (a, b, eps = 1e-9) =>
a.every((value, i) => Math.abs(value - b[i]) < eps);
/** The smallest rotation taking up onto `d`, applied to forward (Rodrigues). */
function rotatedForward(d) {
const up = [0, 0, 1];
const forward = [1, 0, 0];
const axis = cross(up, d);
const sin = Math.hypot(...axis);
const cos = dot(up, d);
if (sin < 1e-12) return forward;
const k = axis.map((value) => value / sin);
const kxv = cross(k, forward);
const kv = dot(k, forward);
return forward.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
}
test('viewLayout gives the aircraft sheet each ring’s first frame', () => {
assert.deepEqual(layout.rings, RINGS);
assert.deepEqual(layout.firsts, FIRSTS);
assert.equal(layout.frames, 302);
assert.equal(layout.columns, 64);
assert.equal(layout.rows, 57);
assert.equal(layout.ringStepRad, 7.5 * RAD);
assert.notEqual(layout.rings, AIRCRAFT_VIEWS.sheet.rings, 'a copy');
});
test('viewLayout refuses a sheet it cannot draw', () => {
const sheet = AIRCRAFT_VIEWS.sheet;
const bad = [
null,
{ ...sheet, image: '' },
{ ...sheet, image: undefined },
{ ...sheet, cellPx: 63.5 },
{ ...sheet, columns: 0 },
{ ...sheet, rows: -32 },
{ ...sheet, rings: [] },
{ ...sheet, rings: 'many' },
{ ...sheet, rings: Array(VIEW_RINGS_MAX + 1).fill(1) },
{ ...sheet, rings: [3, 5] },
{ ...sheet, rings: [1, 2.5] },
{ ...sheet, rings: [1, 0] },
{ ...sheet, ringStepDeg: 0 },
{ ...sheet, ringStepDeg: -15 },
{ ...sheet, ringStepDeg: Number.NaN },
{ ...sheet, ringStepDeg: Infinity },
// A ring straight below, or past it.
{ ...sheet, rings: [1, 4, 4, 1], ringStepDeg: 60 },
{ ...sheet, rings: Array(13).fill(1), ringStepDeg: 15 },
];
for (const sheetGiven of bad)
assert.throws(
() => viewLayout(sheetGiven),
TypeError,
JSON.stringify(sheetGiven),
);
// Short of straight below, and the most rings there may be, are drawn.
assert.equal(viewLayout({ ...sheet, rings: Array(12).fill(1) }).frames, 12);
assert.equal(
viewLayout({
...sheet,
rings: Array(VIEW_RINGS_MAX).fill(1),
ringStepDeg: 10,
}).rings.length,
VIEW_RINGS_MAX,
);
});
test('straight above is frame 0, whatever the course', () => {
assert.deepEqual(viewFrame(layout, [0, 0, 1]), {
frame: 0,
ring: 0,
index: 0,
mirrored: false,
});
assert.equal(viewFrame(layout, [0, 0, 42]).frame, 0, 'any length');
assert.equal(viewFrame(layout, direction(3.7, 135)).frame, 0);
assert.equal(viewFrame(layout, [0, 0, 0]).frame, 0, 'no direction: above');
});
test('on the horizon, dead ahead, abeam and astern are the first, middle and last frames of ring 12', () => {
const first = layout.firsts[HORIZON];
const ahead = viewFrame(layout, [1, 0, 0]);
assert.deepEqual(ahead, {
frame: first,
ring: 12,
index: 0,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [0, 1, 0]), {
frame: first + 12,
ring: 12,
index: 12,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [-1, 0, 0]), {
frame: first + 24,
ring: 12,
index: 24,
mirrored: false,
});
});
test('the left side draws the right side’s frame mirrored', () => {
for (const [off, bearing] of [
[30, 40],
[90, 90],
[105, 170],
[60, 1],
]) {
const right = viewFrame(layout, direction(off, bearing));
const left = viewFrame(layout, mirror(direction(off, bearing)));
assert.equal(left.frame, right.frame, `${off}/${bearing}`);
assert.equal(right.mirrored, false);
assert.equal(left.mirrored, true);
}
// Exactly on the centre plane it is not mirrored.
assert.equal(viewFrame(layout, [1, 0, 0]).mirrored, false);
assert.equal(viewFrame(layout, [1, -0, 0]).mirrored, false);
});
test('below the last ring the eye takes the last ring', () => {
const last = layout.rings.length - 1;
for (const off of [120, 126, 135, 170, 180]) {
const view = viewFrame(layout, direction(off, 90));
assert.equal(view.ring, last, `${off}°`);
}
assert.equal(viewFrame(layout, [0, 0, -1]).frame, layout.firsts[last]);
});
test('frames round to the nearest, between rings and between bearings', () => {
// Rings are 7.5° apart: 3.75° from straight above is between ring 0 and 1.
assert.equal(viewFrame(layout, direction(3.7, 0)).ring, 0);
assert.equal(viewFrame(layout, direction(3.8, 0)).ring, 1);
assert.equal(viewFrame(layout, direction(86.2, 0)).ring, 11);
assert.equal(viewFrame(layout, direction(86.3, 0)).ring, 12);
// The horizon ring's 25 frames are 7.5° of bearing apart.
assert.equal(viewFrame(layout, direction(90, 3.7)).index, 0);
assert.equal(viewFrame(layout, direction(90, 3.8)).index, 1);
assert.equal(viewFrame(layout, direction(90, 176.2)).index, 23);
assert.equal(viewFrame(layout, direction(90, 176.3)).index, 24);
// Ring 1's 4 frames are 60° apart.
assert.equal(viewFrame(layout, direction(7.5, 29.9)).index, 0);
assert.equal(viewFrame(layout, direction(7.5, 30.1)).index, 1);
});
test('frameDirection is where viewFrame finds each frame of the sheet', () => {
let frames = 0;
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-12, 'unit');
const view = viewFrame(layout, d);
assert.equal(view.ring, ring, `${ring}/${index}`);
assert.equal(view.index, index, `${ring}/${index}`);
assert.equal(view.frame, layout.firsts[ring] + index);
// A frame on the centre plane is its own mirror image: either way
// draws it.
if (Math.abs(d[1]) > 1e-12) assert.equal(view.mirrored, mirrored);
}
frames++;
}
assert.equal(frames, AIRCRAFT_VIEWS.frames);
});
test('frameUp is a unit vector across the view, forward from straight above, and turns as the smallest rotation does', () => {
assert.ok(near(frameUp([0, 0, 1]), [1, 0, 0]), 'nose up the image');
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++)
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
const up = frameUp(d);
const at = `${ring}/${index}${mirrored ? ' mirrored' : ''}`;
assert.ok(Math.abs(Math.hypot(...up) - 1) < 1e-9, `unit at ${at}`);
assert.ok(Math.abs(dot(up, d)) < 1e-9, `across the view at ${at}`);
assert.ok(
near(up, rotatedForward(d)),
`the smallest rotation at ${at}`,
);
// Mirroring the eye mirrors the image's up.
assert.ok(near(frameUp(mirror(d)), mirror(up)), `mirrored at ${at}`);
}
// On the horizon, abeam: the nose still points up the image.
assert.ok(near(frameUp([0, 1, 0]), [1, 0, 0]));
// Dead ahead on the horizon: the image's up is straight down the aircraft.
assert.ok(near(frameUp([1, 0, 0]), [0, 0, -1]));
});
test('viewUniforms packs the layout as the shader reads it', () => {
const { grid, rings } = viewUniforms(layout);
assert.deepEqual(grid, [64, 57, 7.5 * RAD, 17]);
// Two rings a vector: each ring's frames and its first frame.
assert.equal(rings.length, VIEW_RINGS_MAX / 2);
const pairs = [];
for (let k = 0; k < RINGS.length; k += 2)
pairs.push([RINGS[k], FIRSTS[k], RINGS[k + 1] ?? 1, FIRSTS[k + 1] ?? 0]);
assert.deepEqual(rings.slice(0, pairs.length), pairs);
for (const pair of rings.slice(pairs.length))
assert.deepEqual(pair, [1, 0, 1, 0], 'padding');
});
test('AIRCRAFT_VIEWS is consistent: a block a subject, every block on the sheet', () => {
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(
frames,
sheet.rings.reduce((a, b) => a + b, 0),
);
assert.equal(frames, 302);
assert.equal(sheet.cellPx * sheet.columns, 4096);
assert.equal(sheet.cellPx * sheet.rows, 3648);
assert.equal(sheet.grey, true, 'kept as grey and alpha');
const firsts = Object.values(subjects);
firsts.forEach((first, i) => {
assert.equal(first, i * frames, 'in order, one block after another');
assert.equal(first % frames, 0);
assert.ok(first + frames <= sheet.columns * sheet.rows, 'on the sheet');
});
assert.ok(Object.isFrozen(AIRCRAFT_VIEWS));
assert.ok(Object.isFrozen(sheet));
assert.ok(Object.isFrozen(sheet.rings));
assert.ok(Object.isFrozen(subjects));
});
const BAKE = new URL(
'../../scripts/build-aircraft-view-sheet.py',
import.meta.url,
);
const MANIFEST = new URL(
'../../public/sprites/aircraft-views.json',
import.meta.url,
);
test('the bake script lays the sheet out as AIRCRAFT_VIEWS says', () => {
const script = readFileSync(BAKE, 'utf8');
const constant = (name) => {
const match = new RegExp(`^${name} = (.+)$`, 'm').exec(script);
assert.ok(match, `${name} in the bake script`);
return JSON.parse(match[1]);
};
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(constant('RING_STEP_DEG'), sheet.ringStepDeg);
assert.deepEqual(constant('RINGS'), [...sheet.rings]);
assert.equal(constant('COLUMNS'), sheet.columns);
const list = /^SUBJECTS = \[([\s\S]*?)^\]/m.exec(script);
assert.ok(list, 'SUBJECTS in the bake script');
const names = [...list[1].matchAll(/^\s*\("(\w+)",/gm)].map((m) => m[1]);
assert.deepEqual(names, Object.keys(subjects), 'the same subjects in order');
// The script's rows: as many as its subjects' blocks take.
assert.equal(Math.ceil((names.length * frames) / sheet.columns), sheet.rows);
});
test(
'the baked manifest matches AIRCRAFT_VIEWS',
{ skip: !existsSync(MANIFEST) && 'no public/sprites/aircraft-views.json' },
() => {
const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
const { sheet, subjects } = AIRCRAFT_VIEWS;
assert.equal(manifest.cellPx, sheet.cellPx);
assert.equal(manifest.columns, sheet.columns);
assert.equal(manifest.rows, sheet.rows);
assert.equal(manifest.ringStepDeg, sheet.ringStepDeg);
assert.deepEqual(manifest.rings, [...sheet.rings]);
assert.equal(manifest.grey, true);
assert.equal(manifest.image, 'aircraft-views.webp');
assert.deepEqual(Object.keys(manifest.subjects), Object.keys(subjects));
for (const [name, first] of Object.entries(subjects))
assert.equal(manifest.subjects[name].first, first, name);
},
);
const SHEET = new URL(
'../../public/sprites/aircraft-views.webp',
import.meta.url,
);
test(
'the shipped sheet is the size the layout says, grey, and clear at every cell’s edge',
{ skip: !existsSync(SHEET) && 'no public/sprites/aircraft-views.webp' },
async () => {
const { default: sharp } = await import('sharp');
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
const { data, info } = await sharp(fileURLToPath(SHEET))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
assert.equal(info.width, sheet.columns * sheet.cellPx);
assert.equal(info.height, sheet.rows * sheet.cellPx);
const at = (x, y) => (y * info.width + x) * 4;
// Grey: the renderer reads the red channel as the grey.
for (let i = 0; i < data.length; i += 4)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2])
assert.fail(`not grey at pixel ${i / 4}`);
// Each used cell keeps its outer 2 px transparent (the mipmaps).
const used = Object.keys(subjects).length * frames;
const c = sheet.cellPx;
for (let n = 0; n < used; n++) {
const left = (n % sheet.columns) * c;
const top = Math.floor(n / sheet.columns) * c;
for (let y = 0; y < c; y++)
for (let x = 0; x < c; x++) {
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) continue;
if (data[at(left + x, top + y) + 3] !== 0)
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
}
}
},
);
test('in the bake’s axes (nose −X, starboard +Y, up +Z) a frame has the same up and direction', () => {
// The bake turns forward by Blender's rotation_difference(UP, d), in its
// own axes, which are mirrored from [forward, right, up]: the smallest
// rotation is the same rotation in either.
const toBake = (v) => [-v[0], v[1], v[2]];
const minimal = (from, to, v) => {
const axis = cross(from, to);
const sin = Math.hypot(...axis);
const cos = dot(from, to);
if (sin < 1e-12) return v;
const k = axis.map((value) => value / sin);
const kxv = cross(k, v);
const kv = dot(k, v);
return v.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
};
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
const d = frameDirection(layout, ring, index);
const bakeUp = minimal([0, 0, 1], toBake(d), toBake([1, 0, 0]));
assert.ok(near(toBake(frameUp(d)), bakeUp), `${ring}/${index}`);
}
});
/** A blend's weight by frame (a frame listed twice counts once, summed). */
@@ -0,0 +1,120 @@
// A 429 from /api/adsbdb must not leave an aircraft's metadata empty for the
// rest of the session.
//
// Both enrichment queues (Flights and Local ADS-B) mark a key as seen before
// they dispatch it, so a second request for the same aircraft is dropped. That
// is right for an answer or a 404, and wrong for a refusal: the server said
// "later", not "no". These cases drive the real queues against a source that
// refuses once and then answers.
//
// Run with: npm test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { LiveSourceError } from '../sources/live/contract.js';
import { createLocalAdsbEnrichment } from './localAdsb/enrichment.js';
import { createFlightState } from './flights/state.js';
import { createEnrichment } from './flights/enrichment.js';
/** Short real delay, so the case needs no clock control. */
const RETRY_AFTER_MS = 20;
/** A source that refuses the first lookup with a 429, then answers. */
function refusingOnce() {
const calls = [];
return {
calls,
async getEnrichment(query) {
calls.push(query);
if (calls.length === 1)
throw new LiveSourceError('limited', 'Flights rate limited', {
status: 429,
retryAfterMs: RETRY_AFTER_MS,
});
return { found: true, typeCode: 'B738', typeName: 'Boeing 737-800' };
},
};
}
const settle = (ms) => new Promise((done) => setTimeout(done, ms));
/** The services Flights enrichment reads: neither military nor a TR-3B. */
const enrichServices = {
militaryRegistry: { isMilitaryIcao: () => false },
aircraftPresentation: { isTr3b: () => false },
};
test('Local ADS-B asks again after a 429 once the refusal has passed', async (t) => {
const source = refusingOnce();
const enrichment = createLocalAdsbEnrichment({ source, onChange() {} });
t.after(() => enrichment.destroy());
const record = { icao: 'abc123', category: 'A3' };
enrichment.request(record);
await settle(0);
assert.equal(source.calls.length, 1);
enrichment.request(record);
await settle(0);
assert.equal(source.calls.length, 1, 'no retry inside the refusal window');
await settle(RETRY_AFTER_MS + 250); // refusal window, then the 200 ms drip
enrichment.request(record);
await settle(250);
assert.equal(source.calls.length, 2, 'the aircraft is asked for again');
assert.equal(enrichment.get('abc123')?.typeCode, 'B738');
});
test('an answered lookup is still asked for only once', async (t) => {
const calls = [];
const enrichment = createLocalAdsbEnrichment({
source: {
async getEnrichment(query) {
calls.push(query);
return { found: false };
},
},
onChange() {},
});
t.after(() => enrichment.destroy());
enrichment.request({ icao: 'def456' });
await settle(RETRY_AFTER_MS + 250);
enrichment.request({ icao: 'def456' });
await settle(250);
assert.equal(calls.length, 1, 'a 404 is an answer, not a refusal');
});
test('Flights asks again after a 429 once the refusal has passed', async (t) => {
const source = refusingOnce();
const flightState = createFlightState({
source,
services: {
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
},
});
t.after(() => flightState.lifetime.abort());
const enrichment = createEnrichment({
flightState,
services: enrichServices,
parts: {},
});
let applied = null;
const ask = () =>
enrichment._enqueueEnrich(
't:abc123',
{ kind: 'type', id: 'abc123' },
(data) => {
applied = data;
},
);
ask();
await settle(0);
ask();
await settle(0);
assert.equal(source.calls.length, 1, 'no retry inside the refusal window');
await settle(RETRY_AFTER_MS + 250);
ask();
await settle(250);
assert.equal(source.calls.length, 2, 'the aircraft is asked for again');
assert.equal(applied?.typeCode, 'B738');
});
+17 -2
View File
@@ -63,10 +63,25 @@ export function createEnrichment({
);
}
/**
* How long a temporarily failed lookup stays unasked. A rate-limit refusal
* says itself when to ask again (`retryAfterMs`), so that wins; any other
* temporary failure waits ENRICH_RETRY_COOLDOWN_MS.
* @param {*} error The rejection, as `LiveSourceError` carries it.
* @returns {number} Milliseconds.
*/
function _enrichCooldownMs(error) {
const hinted = Number(error?.retryAfterMs);
return error?.code === 'limited' && Number.isFinite(hinted) && hinted > 0
? hinted
: ENRICH_RETRY_COOLDOWN_MS;
}
/**
* Ask each key at most once per session, except that a lookup whose source
* failed temporarily (rejected or threw) may be asked again after
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
* ENRICH_RETRY_COOLDOWN_MS, or after the refusal's own `retryAfterMs` for a
* rate limit (see _enrichCooldownMs); an answer, found or not, and a permanent
* refusal (see _enrichFailureIsFinal) are final.
* @param {string} key Session-unique lookup key.
* @param {object} query The source's enrichment query.
@@ -133,7 +148,7 @@ export function createEnrichment({
flightState._enrichSeen.delete(job.key);
flightState._enrichRetryAfter.set(
job.key,
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
Date.now() + _enrichCooldownMs(error),
);
},
)
+1 -2
View File
@@ -21,12 +21,11 @@ const PIN_TURN_DEG = 0.1;
* the grounded floor: a floor-pinned row holds a CPU position, so it is not
* planned, and settling a grounded contact puts it straight onto the floor.
*/
export function createIcons({ flightState, services, parts, resolveAsset }) {
export function createIcons({ flightState, services, parts }) {
const icons = createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'flights',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+1 -9
View File
@@ -948,12 +948,7 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
return parts.icons._fleetLook(flightState._trackedIcao);
}
/**
@@ -1135,9 +1130,6 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up.
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+18 -4
View File
@@ -35,7 +35,8 @@ export function localAdsbClass(record, meta = null) {
* session, at most four requests are in flight and dispatches are dripped
* 200 ms apart. Only the selected aircraft (type + route) and aircraft that
* are about to render as 3D models (type) are ever looked up — never one
* request per contact per tick.
* request per contact per tick. A rate-limit refusal is not an answer: the key
* becomes askable again once the refusal's retry-after has passed.
* @param {object} options
* @param {{getEnrichment?: Function}|null} options.source Flights source.
* @param {() => void} options.onChange Called when metadata arrives.
@@ -53,6 +54,7 @@ export function createLocalAdsbEnrichment({
let active = 0;
let lastDispatchAt = -Infinity;
let dripTimer = null;
const retryTimers = new Set();
let lifetime = new AbortController();
function entry(icao) {
@@ -68,7 +70,7 @@ export function createLocalAdsbEnrichment({
function enqueue(key, query, apply, priority) {
if (typeof source?.getEnrichment !== 'function' || seen.has(key)) return;
seen.add(key);
const job = { query, apply };
const job = { key, query, apply };
if (priority) queue.unshift(job);
else queue.push(job);
drain();
@@ -97,8 +99,10 @@ export function createLocalAdsbEnrichment({
onChange?.();
}
})
.catch(() => {
/* enrichment never surfaces errors */
.catch((error) => {
// Enrichment never surfaces errors; a 429 only defers the key.
if (error?.code === 'limited')
forgetLater(job.key, error.retryAfterMs);
})
.finally(() => {
if (signal.aborted) return;
@@ -108,6 +112,14 @@ export function createLocalAdsbEnrichment({
}
}
function forgetLater(key, delayMs) {
const timer = setTimeout(() => {
retryTimers.delete(timer);
seen.delete(key);
}, delayMs);
retryTimers.add(timer);
}
return {
/** @param {string} icao @returns {object|null} */
get(icao) {
@@ -160,6 +172,8 @@ export function createLocalAdsbEnrichment({
lifetime = new AbortController();
clearTimeout(dripTimer);
dripTimer = null;
for (const timer of retryTimers) clearTimeout(timer);
retryTimers.clear();
queue.length = 0;
active = 0;
},
+15 -34
View File
@@ -1,9 +1,5 @@
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
aircraftViewRef,
registerAircraftViews,
} from '../../data/aircraftViews.js';
import { rotorFrame } from '../../data/rotorFrames.js';
import { KNOT_MPS } from '../../data/units.js';
import {
@@ -17,7 +13,6 @@ import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
@@ -153,9 +148,6 @@ export function createLocalAdsbLayer({
* @type {{markers: object, rings: object}|null}
*/
let sets = null;
/** Whether the renderer draws markers from the aircraft view sheet
* (`aircraftViews.js`), set at `init`. */
let views = false;
let enabled = false;
let unsubscribe = null;
let unsubscribeFeeds = null;
@@ -363,36 +355,31 @@ export function createLocalAdsbLayer({
/**
* A marker's icon, where and how it now draws: a helicopter's rotor frame
* at `at` (still on the ground), an airport vehicle in its own tint, a
* ground station's mast upright. On a renderer that draws view sheets, a
* kind with rendered views is drawn from the sheet along its course;
* every other marker is its flat glyph turned on screen.
* ground station's mast upright.
*/
function markerItem(marker, basis, at) {
const kind = marker.iconKind ?? 'airliner';
const frame =
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined;
const view = views ? aircraftViewRef(kind, frame) : null;
return {
id: marker.id,
pos: marker.position,
image: view ?? aircraftIcon(kind, undefined, frame),
image: aircraftIcon(
kind,
undefined,
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined,
),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color: kind === 'vehicle' ? vehicleColor : color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
...(view
? { rotationMode: 'course', course: marker.courseDeg ?? 0 }
: {
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
}),
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -786,11 +773,6 @@ export function createLocalAdsbLayer({
init(nextViewer) {
viewer = nextViewer;
const draw = drawOf(viewer);
views = registerAircraftViews(
draw,
rendererOf(viewer)?.capabilities ?? null,
resolveAsset,
);
const prefix = `${LAYER_ID}:${++instances}`;
sets = {
markers: draw.icons({
@@ -890,7 +872,6 @@ export function createLocalAdsbLayer({
models = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
views = false;
viewer = null;
void receiver.destroy?.();
},
-58
View File
@@ -223,7 +223,6 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
feeds,
services: { ...services, ...options.services },
now: () => clock.now,
...(options.resolveAsset ? { resolveAsset: options.resolveAsset } : {}),
});
layer.init(viewer);
await layer.enable();
@@ -320,63 +319,6 @@ test('local aircraft use their class silhouette at one size in magenta', async (
assert.equal(detectable.type, 'AIR');
});
test('on a renderer that draws view sheets, local aircraft draw their view along their track; vehicles and masts stay flat', async (t) => {
const { aircraftViewRef } = await import('../../data/aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
const viewer = { scene: {} };
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, {
camera: camera.port,
query: { drillPick: () => [] },
capabilities: new Set(['viewSheets']),
});
fakeInput(viewer);
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { draw, viewer },
resolveAsset: (url) => `/gev${url}`,
});
t.after(() => layer.destroy());
// Registered once, at the layer's own asset URL.
assert.deepEqual(draw.viewSheets, [
[
AIRCRAFT_VIEWS.id,
{ ...AIRCRAFT_VIEWS.sheet, image: '/gev/sprites/aircraft-views.webp' },
],
]);
receiver.set({
aircraft: [
record({ trackDeg: 0 }),
record({ icao: 'a0b702', category: 'A7' }),
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
],
});
await layer.update();
const icon = iconOf(draw, 'local-adsb:abc123');
assert.equal(icon.image, aircraftViewRef('airliner'));
assert.equal(icon.rotationMode, 'course');
assert.equal(icon.course, 0);
assert.equal('rotation' in icon, false);
assert.deepEqual(icon.size, [20, 20]);
assert.deepEqual(icon.color, MAGENTA);
assert.equal(
iconOf(draw, 'local-adsb:a0b702').image,
aircraftViewRef('helicopter', rotorFrame('local-adsb:a0b702', clock.now)),
'the rotor turns through the sheet',
);
const vehicle = iconOf(draw, 'local-adsb:a0c001');
assert.equal(vehicle.image, aircraftIcon('vehicle'));
assert.equal(vehicle.rotationMode, 'screen');
const mast = iconOf(draw, 'local-adsb:a0c003');
assert.equal(mast.image, aircraftIcon('station'));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
+1 -2
View File
@@ -8,12 +8,11 @@ import {
} from './policy.js';
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
export function createIcons({ flightState, services, parts, resolveAsset }) {
export function createIcons({ flightState, services, parts }) {
return createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'military',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+1 -9
View File
@@ -396,12 +396,7 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
return parts.icons._fleetLook(flightState._trackedIcao);
}
/**
@@ -1092,9 +1087,6 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up (ready + shown).
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+2 -2
View File
@@ -5,7 +5,7 @@ import path from 'node:path';
import { providerCooldownMs } from '../server/providers/space/cooldown.js';
import { parseTerrainPoints } from './data/terrainHeightsProxy.js';
import { readResponseTextCapped, coalesceProxyRequest } from './sources/httpBody.js';
import { makeRateLimiter, clientKey } from '../server/providers/common/rate-limit.js';
import { makeRateLimiter, clientKey, resolvePerMinuteCap } from '../server/providers/common/rate-limit.js';
const source = ['local.js', 'common/http.js', 'aircraft/enrichment.js', 'terrain.js', 'space/celestrak.js', 'space/launch-library.js', '../../src/data/spaceProviderRequests.js']
.map(file => readFileSync(new URL(`../server/providers/${file}`, import.meta.url), 'utf8'))
@@ -27,7 +27,7 @@ function fixture(name, overrides = {}, preview = false) {
readResponseTextCapped, coalesceProxyRequest, providerCooldownMs,
// The rate-limited proxies reach for these; give them the real ones so a
// fixture request is throttled exactly as production would be.
makeRateLimiter, clientKey,
makeRateLimiter, clientKey, resolvePerMinuteCap,
// terrain.js gates cross-site requests first; fixture requests carry no
// browser headers, so admit them like a loopback tool.
admitSameSiteKeyless: () => false,
+5 -40
View File
@@ -37,8 +37,7 @@ import { alongLength } from '../../geo/polyline.js';
import { clusterScreenPoints } from '../../geo/screenCluster.js';
import { provideUnboundDraw } from '../rendererOf.js';
import { blobUrl, listenerList, toCartesian, uncaught } from './common.js';
import { createGpuIcons, gpuIconCapabilities } from './gpuIcons.js';
import { viewLayout } from '../../data/viewSheet.js';
import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { blendHost } from './setBlend.js';
import { createModelSets } from './drawModels.js';
import { materialTexture } from './internals.js';
@@ -715,7 +714,7 @@ const animating = (record) => record.gpu?.animating();
export function createCesiumDraw({
scene,
report,
capabilities = new Set(gpuIconCapabilities(scene)),
capabilities = new Set(GPU_ICON_CAPABILITIES),
requestRender: requestFrame = null,
date = null,
now = () => performance.now(),
@@ -1130,7 +1129,6 @@ export function createCesiumDraw({
toColor,
imageOf: (record, image) => iconImage(record, image),
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
viewsOf: (id) => viewSheets.get(id),
requestRender: (reason) => {
if (!live()) return;
if (requestFrame) requestFrame(reason);
@@ -1148,9 +1146,9 @@ export function createCesiumDraw({
function onGpu(record, list, replacing = false, force = false) {
if (record.kind !== 'icons') return false;
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
gpu.check(list, record.spec, record);
gpu.check(list, record.spec);
if (record.gpu) return true;
if (!replacing) gpu.check(record.items.values(), record.spec, record);
if (!replacing) gpu.check(record.items.values(), record.spec);
record.gpu = gpu.attach(record);
record.billboards = null;
record.billboardHost = null;
@@ -1672,9 +1670,6 @@ export function createCesiumDraw({
// when its icon is drawn, and registering an atlas again swaps the images
// of the icons that drew from it.
const atlases = new Map();
// View sheets icons draw subjects of, by id (`viewSheets`): each as its
// image and checked layout, a new object whenever it is registered.
const viewSheets = new Map();
/** The blob each material or quad draws, held while it lives (`holdImage`). */
const heldBlobs = new WeakMap();
@@ -6029,32 +6024,6 @@ export function createCesiumDraw({
}
if (changed) scene.requestRender();
},
...(capabilities.has('viewSheets')
? {
views(id, sheet) {
viewSheets.set(
id,
Object.freeze({
image: sheet.image,
layout: viewLayout(sheet),
grey: sheet.grey === true,
}),
);
let changed = false;
for (const record of sets.values())
if (
record.kind === 'icons' &&
record.gpu &&
record.views === id
) {
record.gpu.reviews();
setsVersion += 1;
changed = true;
}
if (changed) scene.requestRender();
},
}
: {}),
};
return {
@@ -6179,11 +6148,7 @@ provideUnboundDraw((viewer) => {
const part = createCesiumDraw({
scene,
report: uncaught,
capabilities: new Set([
...gpuIconCapabilities(scene),
'fields',
'modelParts',
]),
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
});
unboundParts.set(part.port, part);
const offs = [
-36
View File
@@ -8873,39 +8873,3 @@ test('a disposed set, and every set once the port is disposed, does nothing on l
restore();
}
});
test('a draw port registers view sheets only with viewSheets, each port its own', async () => {
const { PORTS } = await import('../contract/index.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
assert.equal(PORTS.draw.views, 'viewSheets', 'an optional port method');
const report = (error) => assert.fail(error);
const without = createCesiumDraw({
scene: fakeScene(),
report,
capabilities: new Set(['motionSegments']),
});
assert.equal(typeof without.port.views, 'undefined');
// Two viewers: a sheet registered on one is not drawn by the other.
const one = createCesiumDraw({ scene: fakeScene(), report });
const two = createCesiumDraw({ scene: fakeScene(), report });
assert.equal(typeof one.port.views, 'function');
const view = {
id: 'a',
pos: { ...Cesium.Cartesian3.fromDegrees(4, 52, 1000) },
image: { views: AIRCRAFT_VIEWS.id, first: AIRCRAFT_VIEWS.subjects.uav },
size: [20, 20],
rotationMode: 'course',
course: 0,
};
const setOne = one.port.icons({ id: 'views:one' });
const setTwo = two.port.icons({ id: 'views:two' });
setOne.set([view]);
setTwo.set([view]);
one.port.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const rowsOne = one.sets.get('views:one').gpu.set;
const rowsTwo = two.sets.get('views:two').gpu.set;
assert.equal(rowsOne.imageFar(rowsOne.row('a')), AIRCRAFT_VIEWS.subjects.uav);
assert.equal(rowsTwo.imageFar(rowsTwo.row('a')), -1, 'not on this port');
setOne.dispose();
setTwo.dispose();
});
+13 -122
View File
@@ -31,14 +31,6 @@
* root's larger `width`/`height`, as a billboard rasterises it), any other
* image at the item's larger side.
*
* A view (`{views, first}`, `viewSheets`) is not in that atlas: its sheet is
* a texture of its own, and its row draws the frame that shows its subject
* from the eye (`data/viewSheet.js`), lying flat on the ground along its
* course. Until the sheet is registered and loaded, and if it cannot load,
* the row draws the view's `fallback` image along its course (nothing
* without one). A set draws views from one sheet; a view of another is
* refused.
*
* Choices the contract leaves open, taken conservatively:
* - `horizonCull` judges each row no lower than `ICON_CULL_HEIGHT_M` above
* the ellipsoid, as the layers drawing their own icon sets do for sea
@@ -61,7 +53,6 @@ import {
ICON_GROUND_RELATIVE,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import {
writeArcSegment,
@@ -86,26 +77,6 @@ export const GPU_ICON_CAPABILITIES = Object.freeze([
'courseGlide',
]);
/**
* The capabilities GPU icon sets bring on `scene`: `viewSheets` too, but on
* WebGL 1, where a set that draws views could not also draw what its rows
* read from their extras (a display range, a fade, an offset), and a layer
* that uses those would lose its icons to the sheet.
* @param {object} [scene] A Cesium scene; none (a test's) is taken as WebGL 2.
*/
export function gpuIconCapabilities(scene) {
return scene?.context?.webgl2 === false
? [...GPU_ICON_CAPABILITIES]
: [...GPU_ICON_CAPABILITIES, 'viewSheets'];
}
/** Whether an image is a subject of a view sheet (`{views, first}`). */
const isView = (image) => typeof image?.views === 'string';
/** Whether a subject's block of frames, from its first cell, is in `layout`. */
const blockFits = (first, layout) =>
first + layout.frames <= layout.columns * layout.rows;
const nonZero = (v) =>
Boolean(v) && (v.x !== 0 || v.y !== 0 || (v.z ?? 0) !== 0);
@@ -233,12 +204,10 @@ function rasterPxOf(url, item) {
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* viewsOf?: (id: string) => ({image: string, layout: object}|undefined),
* requestRender: (reason: string) => void}} options `date` is the epoch
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it;
* `viewsOf` reads a registered view sheet (undefined while it is not).
* noting that the set draws from it; `peekImage` only reads it.
*/
export function createGpuIcons({
scene,
@@ -247,15 +216,9 @@ export function createGpuIcons({
toColor,
imageOf,
peekImage,
viewsOf = () => undefined,
requestRender,
}) {
const can = (capability) => capabilities.has(capability);
/** Whether a view's frames are in its sheet (true while not registered). */
const viewFits = (view) => {
const sheet = viewsOf(view.views);
return !sheet || blockFits(view.first, sheet.layout);
};
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
function wants(items, spec = {}) {
@@ -265,10 +228,7 @@ export function createGpuIcons({
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.pickProxy ||
item.imageLod ||
// A view turns along its course: an item that does not is not asked
// for its image here.
(item.rotationMode === 'course' && isView(item.image))
item.imageLod
)
return true;
}
@@ -276,33 +236,13 @@ export function createGpuIcons({
}
/** Refuse what a GPU icon set cannot draw, before anything changes. */
function check(items, spec = {}, record = null) {
function check(items, spec = {}) {
// Atlas slots these items would take anew: they must all fit.
const fresh = new Set();
// The one sheet the set draws views from: its record's, else the first
// of these items'.
let sheet = record?.views ?? null;
for (const item of items) {
const refuse = (what) => {
throw new Error(`the Cesium renderer's GPU icons have no ${what}`);
};
if (isView(item.imageLod?.near)) refuse('views as near images');
if (isView(item.image?.fallback)) refuse('views as fallbacks');
if (isView(item.image)) {
if (!can('viewSheets')) refuse('view sheets');
if (!Number.isInteger(item.image.first) || item.image.first < 0)
throw new TypeError("a view's first cell is a whole number from 0");
if (!viewFits(item.image))
throw new RangeError("a view's frames run past its sheet");
if (item.rotationMode !== 'course')
refuse("views but along a course (rotationMode: 'course')");
if (item.imageLod) refuse('imageLod for a view');
sheet ??= item.image.views;
if (item.image.views !== sheet)
refuse(
`views from two sheets in a set (${sheet}, ${item.image.views})`,
);
}
if (item.offsetScalesByDistance && nonZero(item.pixelOffset))
refuse('pixel offsets scaled by distance');
// What a row reads from its extras texture, which WebGL 1 has not.
@@ -318,12 +258,7 @@ export function createGpuIcons({
if (item.rotationMode === 'screen' && (item.rotation ?? 0) !== 0)
refuse('screen rotation on WebGL 1');
}
for (const given of [
// A view is not in the atlas; the image it falls back to is.
isView(item.image) ? item.image.fallback : item.image,
item.imageLod?.near,
]) {
if (given === undefined) continue;
for (const given of [item.image, item.imageLod?.near]) {
// An atlas slot as what it holds now (none yet draws once it does).
const image =
typeof given?.atlas === 'string' ? peekImage(given) : given;
@@ -381,7 +316,6 @@ export function createGpuIcons({
cull: () => spec.horizonCull === true,
recede: () => spec.recede,
translucent: () => spec.blend === 'translucent',
views: () => (record.views ? (viewsOf(record.views) ?? null) : null),
// Picked as the draw port's other items are: `{set, id, meta}` as
// the item now is, hidden row by row for drill picks.
pickObject: (id, _set, primitive) => ({
@@ -477,34 +411,14 @@ export function createGpuIcons({
const added = row < 0;
if (added) row = set.add(item.id);
const [width = 0, height = 0] = item.size ?? [];
const view = isView(item.image);
if (view) {
// Its subject's first cell, once its sheet is registered, and the
// slot of the image drawn in its place until the sheet has loaded.
// (A subject past the sheet, registered since, draws no cell.)
record.views ??= item.image.views;
const sheet = viewsOf(item.image.views);
const first =
sheet && blockFits(item.image.first, sheet.layout)
? item.image.first
: -1;
const fallback =
item.image.fallback === undefined
? -1
: slotOf(item.image.fallback, item);
set.setImage(row, first, fallback);
set.setImageSwitch(row, 0);
} else {
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
}
set.setFlag(row, ICON_VIEWS, view);
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
set.setSize(row, width, height);
set.setScale(row, item.scale ?? 1);
set.setAlpha(row, item.alpha ?? 1);
@@ -833,21 +747,11 @@ export function createGpuIcons({
reatlas(id) {
const drawing = [];
for (const item of record.items.values())
if (
item.image?.atlas === id ||
item.image?.fallback?.atlas === id ||
item.imageLod?.near?.atlas === id
)
if (item.image?.atlas === id || item.imageLod?.near?.atlas === id)
drawing.push(item);
if (fresh) return sync();
for (const item of drawing) writeRow(item);
},
/** Rewrite the rows drawing views, once their sheet is registered. */
reviews() {
if (fresh) return sync();
for (const item of record.items.values())
if (isView(item.image)) writeRow(item);
},
/**
* After a frame: sample the ground under clamped rows' segment ends,
* from `budget` (`{ends, surface}`, spent). Whether a row's ground
@@ -975,19 +879,6 @@ export function createGpuIcons({
let loading = false;
for (let row = 0; row < set.count; row++) {
if (!set.shown(row)) continue;
if (set.flags(row) & ICON_VIEWS) {
// Its sheet, or while that is not drawn, the image it falls
// back to.
const views = host.viewsState();
if (views === 'ready' && set.imageFar(row) >= 0) continue;
const fallback = set.imageNear(row);
if (fallback < 0) {
if (views === 'failed') return 'failed';
loading = true;
} else if (iconAtlas.failed(fallback)) return 'failed';
else if (!iconAtlas.ready(fallback)) loading = true;
continue;
}
for (const slot of [set.imageFar(row), set.imageNear(row)]) {
if (slot < 0) continue;
if (iconAtlas.failed(slot)) return 'failed';
-259
View File
@@ -3,16 +3,13 @@ import * as Cesium from 'cesium';
import test from 'node:test';
import { createCesiumDraw } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { gpuIconCapabilities } from './gpuIcons.js';
import { IconSetPrimitive } from './iconSetPrimitive.js';
import { MAX_ICON_SLOTS } from '../../data/iconAtlas.js';
import {
ICON_CULL_LIFT,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import { AIRCRAFT_VIEWS, viewLayout } from '../../data/viewSheet.js';
import {
iconCourse,
iconPosition,
@@ -1190,259 +1187,3 @@ test('a live motion clock reads the date the draw port is given', () => {
0.1,
);
});
/** An item drawn from the aircraft view sheet's subject at `first`. */
const viewIcon = (id, first = AIRCRAFT_VIEWS.subjects.widebody, extra = {}) =>
icon(id, {
image: { views: AIRCRAFT_VIEWS.id, first },
rotationMode: 'course',
course: 30,
...extra,
});
test('a view takes its set onto the GPU, its row flagged and drawing its subject’s first cell once the sheet is registered', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:views' });
set.set([viewIcon('a')]);
assert.ok(scene.added[0] instanceof IconSetPrimitive, 'a GPU icon set');
const { set: s } = rows(part, 'gpu:views');
const a = s.row('a');
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
assert.equal(s.flags(a) & ICON_ROTATES, ICON_ROTATES, 'along its course');
assert.equal(s.imageFar(a), -1, 'its sheet not registered yet: not drawn');
const host = part.sets.get('gpu:views').host;
assert.equal(host._views(), null);
const before = part.version();
const renders = scene.renders;
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.widebody);
assert.equal(s.imageNear(a), -1, 'no fallback given');
assert.equal(s.imageSwitch(a), 0, 'one image at any size');
assert.ok(part.version() > before);
assert.ok(scene.renders > renders, 'a frame is asked for');
const sheet = host._views();
assert.equal(sheet.image, AIRCRAFT_VIEWS.sheet.image);
assert.deepEqual(
sheet.layout.firsts,
viewLayout(AIRCRAFT_VIEWS.sheet).firsts,
);
assert.equal(sheet.layout.frames, AIRCRAFT_VIEWS.frames);
// Registered again: a new sheet the host reads afresh.
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.notEqual(host._views(), sheet);
// A row added once it is registered draws at once.
set.upsert([viewIcon('b', AIRCRAFT_VIEWS.subjects.helicopter2)]);
assert.equal(s.imageFar(s.row('b')), AIRCRAFT_VIEWS.subjects.helicopter2);
set.dispose();
});
test('a row switching between a view and a flat image changes its flag and its image', () => {
const { part, draw } = drawOver();
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const set = draw.icons({ id: 'gpu:view-flat' });
set.set([viewIcon('a')]);
const { set: s } = rows(part, 'gpu:view-flat');
const a = s.row('a');
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
set.upsert([
icon('a', {
rotationMode: 'course',
course: 30,
imageLod: { near: 'ship-large.png', switchPx: 60 },
}),
]);
assert.equal(s.row('a'), a, 'the same row');
assert.equal(s.flags(a) & ICON_VIEWS, 0, 'flat');
assert.ok(s.imageFar(a) >= 0, 'an atlas slot');
assert.notEqual(s.imageNear(a), s.imageFar(a));
assert.equal(s.imageSwitch(a), 60);
set.upsert([viewIcon('a', AIRCRAFT_VIEWS.subjects.glider)]);
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS, 'a view again');
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.glider);
assert.equal(s.imageNear(a), -1, 'no fallback given');
assert.equal(s.imageSwitch(a), 0);
set.dispose();
});
test('a view’s fallback is the atlas image its row draws until the sheet is', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-fallback' });
const view = (first) => ({
views: AIRCRAFT_VIEWS.id,
first,
fallback: 'glyph.png',
});
set.set([{ ...viewIcon('a'), image: view(AIRCRAFT_VIEWS.subjects.light) }]);
const { set: s } = rows(part, 'gpu:view-fallback');
const a = s.row('a');
// Not registered: no cell yet, its fallback's slot as its near image.
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
assert.equal(s.imageFar(a), -1);
const slot = s.imageNear(a);
assert.ok(slot >= 0, 'the fallback has an atlas slot');
assert.equal(s.imageSwitch(a), 0);
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.light);
assert.equal(s.imageNear(a), slot, 'kept for a sheet that fails to load');
// A view cannot be what a view falls back to.
assert.throws(
() =>
set.upsert([
{
...viewIcon('b'),
image: {
views: AIRCRAFT_VIEWS.id,
first: 0,
fallback: {
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects.widebody,
},
},
},
]),
/views as fallbacks/,
);
assert.equal(s.row('b'), -1, 'refused, changing nothing');
set.dispose();
});
test('a GPU icon set refuses, changing nothing, views it cannot draw', () => {
const { part, draw } = drawOver();
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
draw.views('other-views', AIRCRAFT_VIEWS.sheet);
const set = draw.icons({ id: 'gpu:view-refuse' });
set.set([viewIcon('a')]);
const refused = [
[viewIcon('b', 1.5), /first cell is a whole number/],
[viewIcon('b', -1), /first cell is a whole number/],
[
viewIcon('b', String(AIRCRAFT_VIEWS.frames)),
/first cell is a whole number/,
],
// The last block that fits ends at the sheet's last cell; one cell on
// runs past.
[
viewIcon(
'b',
AIRCRAFT_VIEWS.sheet.columns * AIRCRAFT_VIEWS.sheet.rows -
AIRCRAFT_VIEWS.frames +
1,
),
/run past its sheet/,
],
[viewIcon('b', 0, { rotationMode: 'screen' }), /views but along a course/],
[viewIcon('b', 0, { rotationMode: undefined }), /views but along a course/],
[
viewIcon('b', 0, { imageLod: { near: 'ship.png', switchPx: 30 } }),
/imageLod for a view/,
],
[
icon('b', {
motion: { kind: 'hold' },
imageLod: {
near: { views: AIRCRAFT_VIEWS.id, first: 0 },
switchPx: 30,
},
}),
/views as near images/,
],
[
icon('b', {
image: { views: 'other-views', first: 0 },
rotationMode: 'course',
}),
/views from two sheets/,
],
];
for (const [item, pattern] of refused)
assert.throws(() => set.upsert([item]), pattern, JSON.stringify(item));
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:view-refuse').set.count, 1);
// Two sheets in one write to a fresh set.
const fresh = draw.icons({ id: 'gpu:view-two' });
assert.throws(
() =>
fresh.set([
viewIcon('a'),
icon('b', {
image: { views: 'other-views', first: 0 },
rotationMode: 'course',
}),
]),
/views from two sheets/,
);
assert.equal(fresh.size(), 0);
});
test('without viewSheets the draw port has no views(), and refuses a view', () => {
const { part, draw } = drawOver({
capabilities: new Set(['motionSegments', 'columns']),
});
assert.equal('views' in draw, false);
const set = draw.icons({ id: 'gpu:no-views' });
set.set([icon('a', { motion: { kind: 'hold' } })]);
assert.throws(() => set.upsert([viewIcon('b')]), /no view sheets/);
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:no-views').set.count, 1);
// A set of billboards refuses one too: it cannot take it onto the GPU.
const billboards = draw.icons({ id: 'gpu:no-views-billboards' });
assert.throws(() => billboards.set([viewIcon('a')]), /no view sheets/);
assert.equal(billboards.size(), 0);
});
test('a view sheet is checked when it is registered', () => {
const { draw } = drawOver();
assert.throws(
() => draw.views('bad', { ...AIRCRAFT_VIEWS.sheet, rings: [2, 3] }),
TypeError,
);
assert.throws(
() => draw.views('bad', { ...AIRCRAFT_VIEWS.sheet, image: '' }),
TypeError,
);
});
test('view rows load with their sheet: loading until it is ready, failed when it cannot load', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-load' });
set.set([viewIcon('a')]);
const record = part.sets.get('gpu:view-load');
assert.equal(record.gpu.imageState(), 'loading', 'no sheet registered');
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(record.host.viewsState(), 'loading', 'registered, not drawn');
assert.equal(record.gpu.imageState(), 'loading');
// Node has no Image: the sheet's texture cannot load on this context.
record.host._syncViews({});
assert.equal(record.host.viewsState(), 'failed');
assert.equal(record.gpu.imageState(), 'failed');
// A hidden view row waits on nothing.
set.upsert([viewIcon('a', undefined, { show: false })]);
assert.equal(record.gpu.imageState(), 'settled');
set.dispose();
});
test('view sheets are offered on WebGL 2, not on WebGL 1', () => {
// A row that draws views is on the GPU, where WebGL 1 has no extras: a
// layer whose icons carry a display range would lose them to the sheet.
assert.ok(
gpuIconCapabilities({ context: { webgl2: true } }).includes('viewSheets'),
);
assert.ok(gpuIconCapabilities().includes('viewSheets'), 'no scene: a test');
const webgl1 = gpuIconCapabilities({ context: { webgl2: false } });
assert.equal(webgl1.includes('viewSheets'), false);
assert.deepEqual(webgl1, ['columns', 'motionSegments', 'courseGlide']);
});
test('a view registered past the sheet after its row was written draws no cell', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-late' });
// Accepted while its sheet is unknown: a block that runs one cell past
// the end of the sheet.
const { columns, rows: sheetRows } = AIRCRAFT_VIEWS.sheet;
set.set([viewIcon('a', columns * sheetRows - AIRCRAFT_VIEWS.frames + 1)]);
const { set: s } = rows(part, 'gpu:view-late');
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(s.row('a')), -1, 'no cell: its fallback, or nothing');
set.dispose();
});
+20 -281
View File
@@ -20,17 +20,6 @@
* above, taken between the heights under its segment's two ends. On WebGL 1
* the extras are not drawn (the draw port refuses rows that need them).
*
* A row flagged `ICON_VIEWS` draws from the set's view sheet
* ({@link module:viewSheet}), a texture of its own, in place of the atlas
* (on WebGL 2; the shader has none of it on WebGL 1): it lies flat on the
* ground, forward along its course, and draws the frame nearest the eye's
* direction, mirrored for the eye on its left. The frame is a card standing
* at the row's anchor, square to the frame's own direction, so between
* frames the sprite is tilted (foreshortened and turned) as its subject is,
* with no blending of frames; the row's quad stays upright on screen. Until the
* sheet has loaded it draws its near image from the atlas, turned along its
* course as any row, if it has one.
*
* This module is the one place the icon sets touch Cesium's renderer internals.
*/
import * as Cesium from 'cesium';
@@ -40,7 +29,6 @@ import {
ICON_CULL_HEIGHT_M,
ICON_CULL_LIFT,
ICON_EXTRA_TEXELS,
ICON_VIEWS,
STYLE_STRIDE,
} from '../../data/iconSet.js';
import {
@@ -51,13 +39,6 @@ import {
NEAR_IMAGE_DEVICE_PX,
} from '../../data/iconAtlas.js';
import { recedeFrame, recedeParams } from '../recession.js';
import { rawTexture, webglContext } from './internals.js';
import {
VIEW_RINGS_MAX,
VIEW_SHEET_FRAGMENT_GLSL,
VIEW_SHEET_GLSL,
viewUniforms,
} from '../../data/viewSheet.js';
/** The parameters the uniforms hold while the set does not recede. */
const NO_RECEDE = recedeParams({});
@@ -103,7 +84,6 @@ uniform vec3 u_recessionFloors; // scale, alpha, combined alpha
uniform vec4 u_slots[ICON_SLOTS]; // ICON_SLOTS: as many as the context addresses
uniform float u_cull; // 1: hide rows past the ellipsoid's horizon
uniform float u_pickPass; // 1 while drawing for a pick
uniform float u_viewsReady; // 1 once the set's view sheet is loaded
#ifdef ICON_EXTRAS
uniform highp sampler2D u_extras; // ICON_EXTRA_TEXELS texels a row, ICON_EXTRA_ROWS rows a line
#endif
@@ -113,42 +93,12 @@ out vec4 v_color;
out vec4 v_pickColor;
out float v_proxy;
out float v_overDepth; // 1 for a row drawn over depth, on the near plane
out float v_views; // 1 for a row drawn from the view sheet
#ifdef ICON_VIEW_SHEETS
// A view row's frame: its cell in the sheet (v_uv is then this corner's
// place in that cell, not in the atlas).
out float v_viewCell;
#endif
// The row's anchor in clip space before screen offsets, for effects that wrap
// main() (sonar) and must not change geometry or picks.
vec4 iconAnchorClip = vec4(0.0, 0.0, 0.0, -1.0);
${ICON_SEGMENT_GLSL}
#ifdef ICON_VIEW_SHEETS
${VIEW_SHEET_GLSL}
// Where a corner of the row's quad falls in a frame's cell (0..1 across it,
// v down). The frame is a card standing at the row's anchor, square to the
// direction it shows its subject from: the corner (offset, in the eye's
// axes) is carried along the eye's ray onto that card, so a frame seen from
// a little off its direction is tilted (foreshortened and turned) as its
// subject is, until the next frame is the nearer.
// axes takes the subject's forward, right and up to the eye's axes; cardHalf
// is the card's half size, in the offset's units.
vec2 viewCardUv(float ring, float index, float flip, mat3 axes, vec3 offset, vec3 ray, vec2 cardHalf) {
vec3 toEye;
vec3 up;
viewFrameAxes(ring, index, flip, toEye, up);
vec3 normal = axes * toEye;
vec3 cardUp = axes * up;
vec3 cardRight = cross(cardUp, normal);
// The ray meets the card head on, or nearly: never edge on.
vec3 on = offset - ray * (dot(offset, normal) / min(dot(ray, normal), -0.2));
vec2 at = vec2(dot(on, cardRight), dot(on, cardUp)) / cardHalf;
return vec2(0.5 + 0.5 * (flip > 0.5 ? -at.x : at.x), 0.5 - 0.5 * at.y);
}
#endif
bool iconFlag(float flags, float bit) {
return mod(floor(flags / bit), 2.0) == 1.0;
@@ -177,10 +127,6 @@ void main() {
v_color = vec4(0.0);
v_proxy = 0.0;
v_overDepth = 0.0;
v_views = 0.0;
#ifdef ICON_VIEW_SHEETS
v_viewCell = 0.0;
#endif
gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn
float flags = style1.z;
@@ -249,25 +195,11 @@ void main() {
bool nearImage = style3.x > 0.0
? glyphPx / czm_pixelRatio > style3.x
: glyphPx > ${NEAR_IMAGE_DEVICE_PX.toFixed(1)};
// A view row's far image is its subject's first cell in the view sheet,
// its near image the atlas slot drawn in its place while the sheet is not
// registered or loaded.
bool views = false;
vec2 viewUv = vec2(0.0);
float slot = nearImage ? style1.y : style1.x;
if (iconFlag(flags, ${ICON_VIEWS.toFixed(1)})) {
#ifdef ICON_VIEW_SHEETS
views = u_viewsReady > 0.5 && style1.x >= 0.0;
#endif
slot = views ? style1.x : style1.y;
}
if (slot < 0.0) return; // no image set
vec4 rect = vec4(0.0, 0.0, 1.0, 1.0);
if (!views) {
if (slot >= float(ICON_SLOTS)) return; // past what this context addresses
rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet
}
if (slot >= float(ICON_SLOTS)) return; // past what this context addresses
vec4 rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet
vec2 halfSize = style0.xy * (scale * distanceScale * 0.5) * corner;
vec2 shift = vec2(0.0);
@@ -290,44 +222,15 @@ void main() {
vec3 east = dot(horizontal, horizontal) > 1.0 ? normalize(vec3(horizontal, 0.0)) : vec3(0.0, 1.0, 0.0);
vec3 north = cross(up, east);
vec3 forward = east * sin(course) + north * cos(course);
#ifdef ICON_VIEW_SHEETS
if (views) {
// A view lies flat on the ground, forward along its course, and draws
// the frame nearest the eye's direction. Its quad stays upright on
// screen; the frame is put on it where its card falls.
vec3 right = cross(forward, up);
vec3 toEye = normalize(-rte);
vec3 frame = viewNearest(
vec3(dot(toEye, forward), dot(toEye, right), dot(toEye, up)));
// The subject's axes in the eye's (x right, y up, z back).
mat3 axes = transpose(mat3(u_cameraRight, u_cameraUp, cross(u_cameraRight, u_cameraUp))) *
mat3(forward, right, up);
// This corner, square to the eye's ray (the eye's right and up, turned
// as its back turns onto the ray): a card facing the eye then fills
// the quad wherever on screen it is, without the stretch a wide view
// gives what is off its centre.
vec3 ray = normalize(positionEC.xyz);
vec3 turned = vec3(0.0, 0.0, 1.0) - ray;
vec3 offset =
(vec3(1.0, 0.0, 0.0) + turned * (ray.x / turned.z)) * halfSize.x +
(vec3(0.0, 1.0, 0.0) + turned * (ray.y / turned.z)) * halfSize.y;
viewUv = viewCardUv(
frame.x, frame.y, frame.z, axes, offset, ray,
style0.xy * (scale * distanceScale * 0.5));
v_viewCell = slot + viewRing(frame.x).y + frame.y;
} else
#endif
{
float dx = dot(forward, u_cameraRight);
float dy = -dot(forward, u_cameraUp);
// Heading into or out of the screen: no stable direction, stay upright
// (screenProjectedRotation's 0.5 m of a 2 km probe).
if (dx * dx + dy * dy >= 6.25e-8) {
float rotation = atan(-dx, -dy);
float c = cos(rotation);
float s = sin(rotation);
halfSize = mat2(c, s, -s, c) * halfSize;
}
float dx = dot(forward, u_cameraRight);
float dy = -dot(forward, u_cameraUp);
// Heading into or out of the screen: no stable direction, stay upright
// (screenProjectedRotation's 0.5 m of a 2 km probe).
if (dx * dx + dy * dy >= 6.25e-8) {
float rotation = atan(-dx, -dy);
float c = cos(rotation);
float s = sin(rotation);
halfSize = mat2(c, s, -s, c) * halfSize;
}
}
#ifdef ICON_EXTRAS
@@ -364,39 +267,22 @@ void main() {
v_overDepth = 1.0;
}
v_uv = views
? viewUv
: mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
v_views = views ? 1.0 : 0.0;
v_uv = mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
v_color = vec4(color.rgb, color.a * alpha);
}
`;
const FRAGMENT_SHADER = /* glsl */ `
uniform sampler2D u_atlas;
#ifdef ICON_VIEW_SHEETS
${VIEW_SHEET_FRAGMENT_GLSL}
in float v_viewCell;
#endif
in vec2 v_uv;
in vec4 v_color;
in vec4 v_pickColor;
in float v_proxy;
in float v_overDepth;
in float v_views;
void main() {
vec4 color = texture(u_atlas, v_uv);
#ifdef ICON_VIEW_SHEETS
// How small the sheet's cells are drawn (v_uv runs 0..1 across a view
// row's cell), worked out for every row so the cell can be read inside
// the branch.
vec2 texels = v_uv * (float(textureSize(u_views, 0).x) / max(u_viewGrid.x, 1.0));
float lod = log2(max(max(length(dFdx(texels)), length(dFdy(texels))), 1.0e-6));
if (v_views > 0.5) color = viewCell(v_viewCell, v_uv, lod);
#endif
color = czm_gammaCorrect(color);
vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv));
color *= czm_gammaCorrect(v_color);
// A pick proxy is picked wherever it covers, drawn or not.
if (v_proxy > 0.5) color = vec4(1.0);
@@ -422,100 +308,6 @@ void main() {
}
`;
/** The coarsest mip level a view sheet is sampled at (half-size cells). */
const VIEW_SHEET_MAX_LOD = 1;
/** Each context's view sheet textures, by URL. */
const sheetTextures = new WeakMap();
/**
* A view sheet's image as a texture on `context`, loaded once however many
* icon sets draw from it: `{state, texture}`, `state` going from `loading`
* to `ready` (its `texture` set) or `failed`. `onChange` runs when it does.
* Mipmapped where the context can (to `VIEW_SHEET_MAX_LOD`), so a sprite
* drawn smaller than its cell stays smooth; a cell's transparent margin
* keeps its neighbours out. The texture lives as long as its context.
* A sheet larger than the context's textures fails, as one that cannot load.
* @param {object} context A Cesium Context.
* @param {string} url
* @param {() => void} [onChange]
* @param {boolean} [grey] The sheet's pixels are grey: kept as one channel
* and alpha.
*/
export function viewSheetTexture(context, url, onChange, grey = false) {
let byUrl = sheetTextures.get(context);
if (!byUrl) sheetTextures.set(context, (byUrl = new Map()));
const key = `${grey ? 'grey' : 'colour'}|${url}`;
let entry = byUrl.get(key);
if (!entry) {
entry = { state: 'loading', texture: null, listeners: new Set() };
byUrl.set(key, entry);
const settle = (state) => {
entry.state = state;
for (const listener of entry.listeners) listener();
entry.listeners.clear();
};
if (typeof Image === 'undefined') settle('failed');
else {
const image = new Image();
image.decoding = 'async';
// A cross-origin image would taint the upload.
image.crossOrigin = 'anonymous';
image.onload = () => {
if (context.isDestroyed?.()) return;
// This context's own limit (Cesium's is the last context's made).
const gl = webglContext({ context });
const limit = gl.getParameter(gl.MAX_TEXTURE_SIZE);
if (Math.max(image.naturalWidth, image.naturalHeight) > limit) {
console.warn(
`[iconSetPrimitive] View sheet is larger than this context's textures (${limit} px): ${url}`,
);
settle('failed');
return;
}
const mipmapped = context.webgl2 === true;
entry.texture = new Cesium.Texture({
context,
source: image,
// A grey sheet as its grey (its red) and alpha: half the memory.
pixelFormat: grey
? Cesium.PixelFormat.LUMINANCE_ALPHA
: Cesium.PixelFormat.RGBA,
flipY: false,
sampler: new Cesium.Sampler({
wrapS: Cesium.TextureWrap.CLAMP_TO_EDGE,
wrapT: Cesium.TextureWrap.CLAMP_TO_EDGE,
minificationFilter: mipmapped
? Cesium.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR
: Cesium.TextureMinificationFilter.LINEAR,
magnificationFilter: Cesium.TextureMagnificationFilter.LINEAR,
}),
});
if (mipmapped) {
entry.texture.generateMipmap();
// No coarser than this: past it a cell's transparent margin is
// under a texel, and its neighbours would show at its edges.
gl.bindTexture(gl.TEXTURE_2D, rawTexture(entry.texture));
gl.texParameterf(
gl.TEXTURE_2D,
gl.TEXTURE_MAX_LOD,
VIEW_SHEET_MAX_LOD,
);
gl.bindTexture(gl.TEXTURE_2D, null);
}
settle('ready');
};
image.onerror = () => {
console.warn(`[iconSetPrimitive] View sheet failed to load: ${url}`);
settle('failed');
};
image.src = url;
}
}
if (onChange && entry.state === 'loading') entry.listeners.add(onChange);
return entry;
}
/**
* How many atlas slots the icon shader addresses on `context`: as many as
* the vertex uniform limit leaves room for (Cesium's ContextLimits, which
@@ -552,9 +344,7 @@ const EARTH_BOUNDS = new Cesium.BoundingSphere(
* Cesium's `BlendOption.TRANSLUCENT` billboards are, in place of an opaque
* pass and a translucent one (by default never). `pickObject` builds a row's pick object around the
* `primitive` drill picks hide it by (by default `{ id, iconSet, meta,
* primitive }`). `views` gives the view sheet the set's view rows draw from
* (`{image, layout, grey}`, `layout` as `viewLayout` returns; null: none),
* the same object until the sheet changes.
* primitive }`).
*/
export class IconSetPrimitive {
constructor({
@@ -565,22 +355,9 @@ export class IconSetPrimitive {
recede,
translucent,
pickObject,
views,
}) {
this.set = set;
this.renderTime = renderTime;
this._requestRender = requestRender ?? null;
// The set's view sheet: what it was last read as, its texture's entry
// and its layout as uniforms.
this._views = views ?? (() => null);
this._viewsFrom = null;
this._viewEntry = null;
this._viewGrid = new Cesium.Cartesian4();
this._viewRings = Array.from(
{ length: VIEW_RINGS_MAX / 2 },
() => new Cesium.Cartesian4(1, 0, 1, 0),
);
this._blank = null;
this._cull = cull ?? (() => true);
// The set's `recede`, and the parameters last made from it.
this._recede = recede ?? (() => null);
@@ -633,11 +410,7 @@ export class IconSetPrimitive {
u_recession: () => primitive._recession,
u_recessionFloors: () => primitive._recessionFloors,
u_slots: () => primitive._slotUniform,
u_atlas: () => primitive._texture ?? primitive._blank,
u_views: () => primitive._viewEntry?.texture ?? primitive._blank,
u_viewsReady: () => (primitive._viewEntry?.texture ? 1 : 0),
u_viewGrid: () => primitive._viewGrid,
u_viewRings: () => primitive._viewRings,
u_atlas: () => primitive._texture,
u_extras: () => primitive._extras,
u_cull: () => (primitive._cull() ? 1 : 0),
u_pickPass: () => primitive._pickPass,
@@ -658,10 +431,7 @@ export class IconSetPrimitive {
return;
const context = frameState.context;
this._syncAtlas(context);
this._syncViews(context);
// Nothing to draw from yet: no atlas image packed, no view sheet.
if (!this._texture && !this._viewEntry) return;
this._blank = context.defaultTexture;
if (!this._texture) return;
// Read as the commands run, which they do right after this update.
this._pickPass = frameState.passes.pick ? 1 : 0;
const renderTime = this.renderTime(frameState);
@@ -715,31 +485,6 @@ export class IconSetPrimitive {
Cesium.Cartesian4.unpack(iconAtlas.rects, slot * 4, this._slots[slot]);
}
/** Follow the set's view sheet: its layout's uniforms and its texture. */
_syncViews(context) {
const sheet = this._views();
if (sheet === this._viewsFrom) return;
this._viewsFrom = sheet;
this._viewEntry = null;
if (!sheet) return;
const { grid, rings } = viewUniforms(sheet.layout);
Cesium.Cartesian4.fromArray(grid, 0, this._viewGrid);
rings.forEach((pair, k) =>
Cesium.Cartesian4.fromArray(pair, 0, this._viewRings[k]),
);
this._viewEntry = viewSheetTexture(
context,
sheet.image,
() => this._requestRender?.(),
sheet.grey === true,
);
}
/** The set's view sheet: `none`, `loading`, `failed` or `ready`. */
viewsState() {
return this._viewEntry?.state ?? (this._views() ? 'loading' : 'none');
}
_allocate(context) {
const set = this.set;
this._destroyBuffers();
@@ -1004,16 +749,12 @@ export class IconSetPrimitive {
_createCommands(context) {
this._slotCount = contextIconSlots(context);
this._slotUniform = this._slots.slice(0, this._slotCount);
// View sheets are drawn on WebGL 2 only (as the draw port offers them):
// on WebGL 1 the shader is as it was without them.
const viewDefines = context?.webgl2 ? ['ICON_VIEW_SHEETS'] : [];
const programFor = (pass) =>
Cesium.ShaderProgram.fromCache({
context,
vertexShaderSource: new Cesium.ShaderSource({
defines: [
`ICON_SLOTS ${this._slotCount}`,
...viewDefines,
...(this._extras
? [
'ICON_EXTRAS',
@@ -1025,14 +766,12 @@ export class IconSetPrimitive {
sources: [VERTEX_SHADER],
}),
fragmentShaderSource: new Cesium.ShaderSource({
defines: [
...viewDefines,
...(pass === 'opaque'
defines:
pass === 'opaque'
? ['OPAQUE']
: pass === 'translucent'
? ['TRANSLUCENT']
: []),
],
: [],
sources: [FRAGMENT_SHADER],
}),
attributeLocations: ATTRIBUTE_LOCATIONS,
+2 -2
View File
@@ -18,7 +18,7 @@ import { createControlledCamera } from './controlledCamera.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import { createCesiumCredits } from './credits.js';
import { createCesiumDraw } from './draw.js';
import { gpuIconCapabilities } from './gpuIcons.js';
import { GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { createCesiumEffects } from './effects.js';
import { renderNow, willDraw } from './frame.js';
import { createCesiumGlobe } from './globe.js';
@@ -100,7 +100,7 @@ export function cesiumCapabilities(scene, only) {
...(scene?.screenSpaceCameraController && scene?.preRender
? ['keepEarthFramed']
: []),
...gpuIconCapabilities(scene),
...GPU_ICON_CAPABILITIES,
// Icon sets cluster on screen, on billboards and the GPU (`draw.js`).
'cluster',
'styles',
-1
View File
@@ -18,7 +18,6 @@ test('capabilities follow what the scene supports', () => {
'columns',
'motionSegments',
'courseGlide',
'viewSheets',
'cluster',
'styles',
'bloom',
-2
View File
@@ -207,8 +207,6 @@ export type Capability =
| 'fields'
/** Rate-limited course easing (`IconItem.courseGlide`). */
| 'courseGlide'
/** Icons drawn from a sheet of views, by where the eye is (`ViewSheet`). */
| 'viewSheets'
/** Lines that fade with the age of their points (`LineItem.ageFade`). */
| 'lineAgeFade'
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
+1 -47
View File
@@ -154,48 +154,10 @@ export interface Placed {
disableDepthTest?: number;
}
/**
* `viewSheets`: one image of small sprites that show subjects from a sphere
* of directions, registered with `DrawPort.views`. An icon whose image is a
* view (`{views, first}`) lies flat on the ground, forward along its course,
* and is drawn as the sprite that shows it from where the eye is.
*
* The image is a grid of square cells, `cellPx` a side, `columns` across and
* `rows` down. A subject is a block of consecutive cells, row-major from its
* `first`: rings of frames `ringStepDeg` apart, from straight above (ring 0,
* one frame) downward, short of straight below; ring `k` holds `rings[k]`
* frames, from the eye dead ahead of the subject, round its right side, to
* dead astern. The eye on its left side draws the right side's frame
* mirrored. A frame's up is the subject's forward, turned by the smallest
* rotation that takes its up onto the frame's direction. The frame nearest
* the eye's direction is drawn, as a card square to its own direction, so
* between frames it is tilted as its subject is (`data/viewSheet.js` holds
* the maths).
*/
export interface ViewSheet {
/** The sheet's URL. */
image: string;
cellPx: number;
columns: number;
rows: number;
ringStepDeg: number;
/** Frames in each ring; the first is 1. At most 18 rings. */
rings: readonly number[];
/**
* The sheet's pixels are grey (red, green and blue equal): a renderer may
* keep it as one channel and alpha.
*/
grey?: boolean;
}
/**
* An image an icon draws: a URL, a slot in a shared atlas, generated, or
* (`viewSheets`, icons only) a subject of a view sheet by its first cell.
*/
/** An image an icon draws: a URL, a slot in a shared atlas, or generated. */
export type ImageRef =
| string
| { atlas: string; slot: string }
| { views: string; first: number; fallback?: ImageRef }
| { svg: string }
| { blob: Blob }
| { canvas: HTMLCanvasElement | OffscreenCanvas; key: string };
@@ -249,12 +211,6 @@ export interface CourseGlide {
}
export interface IconItem extends Placed {
/**
* A view (`{views, first}`) needs `rotationMode: 'course'` and takes no
* `imageLod`; a set draws views from one sheet. Until its sheet is
* registered and loaded, and if that cannot load, it draws its `fallback`
* (any image but a view) along its course, or nothing without one.
*/
image: ImageRef;
/** Drawn size in CSS pixels. */
size: [width: number, height: number];
@@ -796,6 +752,4 @@ export interface DrawPort {
on(event: 'clampState', cb: (state: 'draped' | 'overlay') => void): Off;
/** Register an atlas of images icons refer to by slot. */
atlas(id: string, images: Record<string, ImageRef>): void;
/** `viewSheets`: register a sheet of views icons refer to by id. */
views?(id: string, sheet: ViewSheet): void;
}
-2
View File
@@ -41,7 +41,6 @@ export const CAPABILITIES = Object.freeze([
'meshes',
'fields',
'courseGlide',
'viewSheets',
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
@@ -175,7 +174,6 @@ export const PORTS = deepFreeze({
['quads', 'quads'],
['meshes', 'meshes'],
['field', 'fields'],
['views', 'viewSheets'],
]),
camera: Object.fromEntries([
...required(
-6
View File
@@ -23,7 +23,6 @@ import {
} from '../recession.js';
import { CLEAR_WEATHER, mergeWeather } from '../weather.js';
import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js';
import { viewLayout } from '../../data/viewSheet.js';
import { createStubCamera } from './camera.js';
import { motionPosition } from '../motion/iconMotion.js';
import { computeViewRectangle } from './viewRectangle.js';
@@ -705,11 +704,6 @@ export function createStubRenderer(options = {}) {
};
},
};
if (capabilities.has('viewSheets'))
draw.views = (id, sheet) => {
viewLayout(sheet); // refused as a renderer refuses it
log('draw', 'views', [id]);
};
if (capabilities.has('models'))
draw.models = (spec) => makeSet('models', spec);
if (capabilities.has('quads')) draw.quads = (spec) => makeSet('quads', spec);
-7
View File
@@ -8,8 +8,6 @@ import { bindRenderer } from '../render/rendererOf.js';
export function fakeDrawPort() {
const sets = new Map();
// Every `views(id, sheet)` call, in order.
const viewSheets = [];
const make = (kind) => (spec) => {
const live = sets.get(spec.id);
if (live && !live.disposed)
@@ -99,11 +97,6 @@ export function fakeDrawPort() {
clampState: () => 'draped',
on: () => () => {},
atlas() {},
/** The `views(id, sheet)` registrations, in order, as `[id, sheet]`. */
viewSheets,
views(id, sheet) {
viewSheets.push([id, sheet]);
},
};
}