Compare commits

..
Author SHA1 Message Date
Mazeyar Moeini FeizabadiandClaude Fable 5.2 e9c9de0878 docs(changelog): add the #1907 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 04:13:45 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 01187cbe7a feat(vessels): draw vessels as shaded sprites seen from the camera's angle
Vessels on the map were flat, top-down hulls turned along their course,
drawn at one size at every range.

Each hull shape (the ten vessel kinds, a dredger and a pilot boat) is
now rendered in Blender into a view sheet like the aircraft's
(public/sprites/vessel-views.webp: 208 views a shape, 7.5 degrees apart
from straight above down to the horizon, 4096 x 2496, grey, 2.2 MB),
cut at the waterline. On a renderer with `viewSheets` the Vessels layer
draws a vessel as the view of its hull from where the eye is, with the
flat hull as the fallback while the sheet loads or if it cannot load.
A vessel keeps its kind's colour; aids to navigation keep their upright
buoy; a renderer without view sheets draws the flat hulls as before.

Every AIS ship type code 0-99 maps to a shape in the sheet
(`vesselShape`, vesselTypes.js), pinned by a test. Type text such as
"Search & Rescue" and "Anti Pollution" is now recognised, which also
gives those vessels their right kind colour.

Size: a vessel's icon now follows its range from the eye on the same
range aircraft icons use (1.5 times its former size up close, its
former size at about 1,000 km, a third from 8,000 km out), so it stays
under an aircraft's icon at every range, and the vessel set recedes
toward the horizon as the aircraft sets do.

Tools: the bake script handles both sheets
(scripts/bake-view-sheet.py; `npm run build:aircraft-views`,
`npm run build:vessel-views`), and refuses a partial bake over a shipped
sheet. scripts/qa-view-sheet.mjs writes contact sheets of a bake;
scripts/qa-aircraft-views.mjs takes `--layer vessels`. The aircraft
sheet is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-23 04:10:58 +01:00
19 changed files with 1115 additions and 272 deletions

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
- Vessels on the map are shaded sprites that show the view of the ship from
where the camera is, instead of flat top-down hulls: each hull shape (the
ten vessel kinds, a dredger and a pilot boat) is drawn from a sheet
rendered from straight above down to the horizon, laid flat on the water
along its course, so a ship seen at an oblique angle looks solid. A
vessel keeps its kind's colour; aids to navigation keep their upright buoy,
and a renderer without view sheets draws the flat hulls as before. A
vessel's size now follows the camera's range: larger up close, smaller
than an aircraft from far out, and shrinking and fading toward the
horizon as aircraft do (Mazeyar Moeini Feizabadi, #1907).
+1 -1
View File
@@ -8909,7 +8909,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. **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/bake-view-sheet.py --sheet aircraft`, `npm run build:aircraft-views`). 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, milLine truncated
- 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.
+2 -1
View File
@@ -49,7 +49,8 @@
"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",
"build:aircraft-views": "node scripts/build-view-sheet.mjs --sheet aircraft",
"build:vessel-views": "node scripts/build-view-sheet.mjs --sheet vessels",
"preview": "vite preview",
"test": "node scripts/run-unit-tests.mjs",
"test:perf": "node scripts/run-perf-tests.mjs",
+2 -1
View File
@@ -37,7 +37,8 @@ How the layers use them:
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)).
with, and one ship model for each vessel hull shape, cut at its waterline,
into the vessel view sheet ([`../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
+80 -45
View File
@@ -1,71 +1,106 @@
# Aircraft View Sheet
# View Sheets
`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.
A view sheet is one image of small shaded sprites: each subject rendered from
a sphere of camera angles. On a renderer with the `viewSheets` capability a
layer lays a contact flat on the earth along its course and the renderer
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 a contact seen at an oblique angle looks solid and turns with
the camera.
- `aircraft-views.webp` holds the far-away aircraft of Flights, Military
Flights and Local ADS-B.
- `vessel-views.webp` holds the vessels of the vessel layer.
Each has a manifest beside it (`.json`).
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. |
| 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. |
| `vessel-views.webp` | 4096 × 2496 px, lossless WebP: 64 px cells, 64 a row, 39 rows. Grey. |
| `vessel-views.json` | Its manifest, of the same shape. |
## 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`).
A sheet holds each subject as a block of consecutive cells, row-major:
subject `i` starts at cell `i × frames`. Within a block the frames lie in
rings 7.5° apart from straight above (ring 0, one frame) downward. A ring
runs from the eye dead ahead of the nose or bow, 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 subject'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 layouts (`AIRCRAFT_VIEWS`,
`VESSEL_VIEWS`) and the maths that picks a frame;
`src/data/viewSheet.test.mjs` checks the manifests, the shipped images and
the bake script against them.
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.
| Sheet | Frames a subject | Rings | Subjects, in order |
| -------- | ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Aircraft | 302 | 17, to 30° below the horizon: 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22 | `airliner`, `widebody`, `quadjet`, `turboprop`, `light`, `glider`, `fastjet`, `bizjet`, `uav`, and `helicopter0` to `helicopter2` (the helicopter's three rotor frames, `src/data/rotorFrames.js`) |
| Vessels | 208 | 13, to the horizon (a ship is never seen from below): 1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25 | `cargo`, `tanker`, `passenger`, `highspeed`, `fishing`, `tug`, `sailing`, `pleasure`, `military`, `other` (the kinds of `vesselKind`, `src/data/vesselTypes.js`), `dredger`, `pilot` |
The sprites are neutral (white paint, grey shading, dark glass, a dark edge)
The sprites are neutral (light 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.
exactly grey (`"grey": true`): the renderer keeps a 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. Every cell keeps
its outer 2 px transparent, so the renderer's mipmaps never pull in a
neighbour.
Thin subjects are thickened a little before their edge so they still read
20 to 30 px wide: the glider, UAV, light aircraft and helicopter, and every
vessel (the container ship, tanker and patrol boat most).
Vessels differ from aircraft in four ways:
- **Waterline.** A ship model's origin is its waterline. Each model is cut
there before it is rendered, so no hull below the water is drawn, even from
the horizon.
- **Paint.** The ship models are many colours (hull paint, decks,
containers). The vessel paint makes every colour a light grey, black hull
paint included, except the windows (a dark colour whose blue stands above
its red), which stay dark.
- **Beam.** Hulls are long and thin, so most are widened across the beam
(1.2 to 1.5 times; the trawler and tug as built). The side view keeps its
true height.
- **Sailboat.** The sailboat's mast is taller than its hull is long. Above
1.2 m it is squashed to 0.4 of its height, so the hull fills its cell from
above and the sail still reads from the side.
## Rebuilding
```
npm run build:aircraft-views # about 7 minutes
npm run build:aircraft-views -- --only glider,uav --out /tmp/views
npm run build:vessel-views # about 4 minutes
npm run build:vessel-views -- --only tug,sailing --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.
`/Applications/Blender.app`). Each runs `scripts/build-view-sheet.mjs`, which
runs `scripts/bake-view-sheet.py --sheet aircraft|vessels` headless (one
script, with each sheet's layout, models, paint and adjustments). The bake
renders every frame with Cycles and refuses a frame whose pixels reach
within 2 px of its cell's edge. `build-view-sheet.mjs` then 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. Cycles is not
bit-reproducible, so a rebuild changes the WebP's bytes slightly; rebuild a
sheet only to change it.
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):
To review a bake, write a contact sheet per subject: its rings as rows, plus
a few frames at 40, 30 and 20 px in each tint the layers draw it with.
- Aircraft: over a dark sea, pale land and a mid satellite tone, in the
fleet, tracked and military tints.
- Vessels: over a dark sea, pale shallow water and a satellite ocean tone,
in white and the kind's colour.
```
node scripts/qa-aircraft-view-sheet.mjs [--manifest public/sprites/aircraft-views.json] [--out qa-shots/aircraft-views]
node scripts/qa-view-sheet.mjs --manifest public/sprites/vessel-views.json [--out qa-shots/vessel-views]
```
+86
View File
@@ -0,0 +1,86 @@
{
"image": "vessel-views.webp",
"cellPx": 64,
"columns": 64,
"rows": 39,
"ringStepDeg": 7.5,
"rings": [
1,
4,
7,
10,
13,
16,
18,
20,
22,
23,
24,
25,
25
],
"fill": 0.92,
"grey": true,
"subjects": {
"cargo": {
"first": 0,
"model": "ships/container_ship.glb",
"radiusM": 160.913
},
"tanker": {
"first": 208,
"model": "ships/tanker.glb",
"radiusM": 130.314
},
"passenger": {
"first": 416,
"model": "ships/cruise_ship.glb",
"radiusM": 168.583
},
"highspeed": {
"first": 624,
"model": "ships/fast_ferry.glb",
"radiusM": 23.032
},
"fishing": {
"first": 832,
"model": "ships/trawler.glb",
"radiusM": 13.229
},
"tug": {
"first": 1040,
"model": "ships/tug.glb",
"radiusM": 16.418
},
"sailing": {
"first": 1248,
"model": "ships/sailboat.glb",
"radiusM": 8.358
},
"pleasure": {
"first": 1456,
"model": "ships/motor_yacht.glb",
"radiusM": 10.073
},
"military": {
"first": 1664,
"model": "ships/patrol.glb",
"radiusM": 36.28
},
"other": {
"first": 1872,
"model": "ships/generic_vessel.glb",
"radiusM": 21.828
},
"dredger": {
"first": 2080,
"model": "ships/dredger.glb",
"radiusM": 53.542
},
"pilot": {
"first": 2288,
"model": "ships/pilot_boat.glb",
"radiusM": 10.774
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

@@ -1,46 +1,52 @@
"""Bake the aircraft view sheet: every aircraft class seen from a sphere of
directions, as one image of small shaded sprites.
"""Bake a view sheet: each subject of a sheet (an aircraft class, a vessel
kind) 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>]
blender -b --factory-startup --python scripts/bake-view-sheet.py -- \
--sheet aircraft|vessels --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.
It writes `<name>.png` and its manifest `<name>.json` to `--out`, `<name>`
being the sheet's name (`aircraft-views`, `vessel-views`). The manifest names
the shipped image, `<name>.webp`, which `npm run build:aircraft-views` or
`npm run build:vessel-views` (scripts/build-view-sheet.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
(`src/data/viewSheet.js` holds the same layouts and maths; its test,
`src/data/viewSheet.test.mjs`, checks this script's sheets and the shipped
manifests against it). A frame is an orthographic view of the subject's
fleet model (`public/models/fleet/`, nose or bow 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
Directions. `d` is the unit vector from the subject to the eye in the
subject's own frame (forward, right, up), the subject 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.
the sheet's `ring_step_deg` apart from straight above (ring 0, one frame)
down to its last ring (30 degrees below the horizon for aircraft, the horizon
for vessels). 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
subject's centre plane.
Roll. A frame's image up is where the aircraft's forward goes under the
Roll. A frame's image up is where the subject'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
The sprites are neutral (light 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
that is not. Each sheet has its paint ramp (`PAINTS`), and a subject may
have its own. 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. A vessel is cut at its waterline (its origin, z = 0) before it
is rendered, so no hull below the water is drawn and its bounding sphere is
of what floats; a subject's model may be widened across the beam (`beam`)
or squashed above a height (`squash_above`: a sailboat's mast). 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.
"""
@@ -51,49 +57,78 @@ import os
import struct
import sys
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
# --- The sheet's layout (mirrored in src/data/viewSheet.js) -----------------
# --- The sheets (their layouts mirrored in src/data/viewSheet.js) -----------
# A sheet: its name (the files it writes), its rings of frames (each ring's
# frame count, from dead ahead round starboard to dead astern), its paint,
# whether its models are cut at the waterline, and its subjects, in the order
# of their blocks of frames. A subject is (name, model, options); options:
# rotor_deg a helicopter's rotor frame: the rotors turned this far
# paint its own paint ramp (a key of PAINTS)
# bold_px cell pixels it is thickened by before its edge, so thin
# wings, blades and hulls still read 20 to 30 px wide
# beam its model scaled across the beam by this much
# squash_above [z, k]: its model above z metres scaled up by k
AIRCRAFT = {
"name": "aircraft-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22],
"columns": 64,
"paint": "aircraft",
"waterline": False,
"subjects": [
("airliner", "aircraft/a320.glb", {}),
("widebody", "aircraft/b789.glb", {}),
("quadjet", "aircraft/b744.glb", {}),
("turboprop", "aircraft/at72.glb", {}),
("light", "aircraft/c172.glb", {"bold_px": 0.35}),
("glider", "aircraft/glider.glb", {"bold_px": 1.0}),
("fastjet", "aircraft/t38.glb", {}),
("bizjet", "aircraft/glf4.glb", {}),
("uav", "aircraft/mq9.glb", {"bold_px": 1.0}),
# The helicopter has one block for each rotor frame (rotorFrames.js).
("helicopter0", "helicopters/generic_heli.glb", {"rotor_deg": 15, "paint": "helicopter", "bold_px": 0.4}),
("helicopter1", "helicopters/generic_heli.glb", {"rotor_deg": 45, "paint": "helicopter", "bold_px": 0.4}),
("helicopter2", "helicopters/generic_heli.glb", {"rotor_deg": 75, "paint": "helicopter", "bold_px": 0.4}),
],
}
# Vessels: down to the horizon only, as a ship is never seen from below. The
# subjects are the hull kinds of vesselKind (src/data/vesselTypes.js), then
# the dredger (AIS 33) and the pilot boat (pilot, rescue, tender and
# anti-pollution craft).
VESSELS = {
"name": "vessel-views",
"ring_step_deg": 7.5,
"rings": [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25],
"columns": 64,
"paint": "ship",
"waterline": True,
"subjects": [
("cargo", "ships/container_ship.glb", {"beam": 1.4, "bold_px": 1.0}),
("tanker", "ships/tanker.glb", {"beam": 1.4, "bold_px": 1.0}),
("passenger", "ships/cruise_ship.glb", {"beam": 1.4, "bold_px": 0.5}),
("highspeed", "ships/fast_ferry.glb", {"beam": 1.2, "bold_px": 0.5}),
("fishing", "ships/trawler.glb", {"bold_px": 0.5}),
("tug", "ships/tug.glb", {"bold_px": 0.5}),
("sailing", "ships/sailboat.glb", {"beam": 1.3, "bold_px": 0.5, "squash_above": [1.2, 0.4]}),
("pleasure", "ships/motor_yacht.glb", {"beam": 1.25, "bold_px": 0.5}),
("military", "ships/patrol.glb", {"beam": 1.5, "bold_px": 1.0}),
("other", "ships/generic_vessel.glb", {"beam": 1.3, "bold_px": 0.5}),
("dredger", "ships/dredger.glb", {"beam": 1.3, "bold_px": 0.5}),
("pilot", "ships/pilot_boat.glb", {"beam": 1.2, "bold_px": 0.5}),
],
}
SHEETS = {"aircraft": AIRCRAFT, "vessels": VESSELS}
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.
@@ -104,11 +139,11 @@ RIGHT = Vector((0.0, 1.0, 0.0))
UP = Vector((0.0, 0.0, 1.0))
def frame_directions():
def frame_directions(sheet):
"""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 ring, count in enumerate(sheet["rings"]):
alpha = math.radians(ring * sheet["ring_step_deg"])
for i in range(count):
phi = 0.0 if count == 1 else math.pi * i / (count - 1)
d = (
@@ -131,6 +166,7 @@ def frame_up(d):
def args_after_dashes():
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
opts = {
"sheet": "aircraft",
"out": "public/sprites",
"cell": 64,
"supersample": 4,
@@ -148,6 +184,8 @@ def args_after_dashes():
opts["cell"] = int(opts["cell"])
opts["supersample"] = int(opts["supersample"])
opts["samples"] = int(opts["samples"])
if opts["sheet"] not in SHEETS:
raise SystemExit(f"--sheet is one of {', '.join(SHEETS)}")
return opts
@@ -210,17 +248,26 @@ def setup_scene(render_px, samples):
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)]
# Paint by the model's own colour value (its largest channel, linear), as
# (value, grey) stops. Aircraft: 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. Ships: windows and the darkest fittings stay dark, and hull
# paint, decks and cargo all become light greys a little apart.
PAINTS = {
"aircraft": [(0.03, 0.07), (0.10, 0.30), (0.26, 0.56), (0.40, 0.76), (0.85, 0.90)],
"helicopter": [(0.04, 0.07), (0.08, 0.38), (0.39, 0.95)],
"ship": [(0.0, 0.62), (0.25, 0.78), (0.85, 0.95)],
}
# Glass by its colour, for a paint that lifts even black hull paint: a dark
# colour (value at most `value`) whose blue is at least `blue` and
# `blue_over_red` times its red (the ship models' windows) is painted `grey`.
GLASS = {"ship": {"value": 0.08, "blue": 0.025, "blue_over_red": 2.5, "grey": 0.07}}
SUN_STRENGTH = 1.4
SKY_STRENGTH = 0.38
FILL_STRENGTH = 0.9
def paint_material(paint_ramp=PAINT_RAMP, solid=None):
def paint_material(paint_ramp, solid=None, glass=None):
"""Neutral paint that keeps the model's light and dark parts apart."""
material = bpy.data.materials.new("paint")
material.use_nodes = True
@@ -251,7 +298,37 @@ def paint_material(paint_ramp=PAINT_RAMP, solid=None):
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"])
if glass is None:
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
return material
def math_node(operation, a, b, c=None):
node = nodes.new("ShaderNodeMath")
node.operation = operation
for i, x in enumerate((a, b, c)):
if x is None:
continue
if isinstance(x, (int, float)):
node.inputs[i].default_value = x
else:
links.new(x, node.inputs[i])
return node.outputs[0]
dark = math_node("LESS_THAN", value.outputs[0], glass["value"] + 1e-4)
blue = math_node("GREATER_THAN", split.outputs[2], glass["blue"] - 1e-4)
red_scaled = math_node("MULTIPLY", split.outputs[0], glass["blue_over_red"])
over_red = math_node(
"GREATER_THAN", math_node("SUBTRACT", split.outputs[2], red_scaled), -1e-4
)
is_glass = math_node("MULTIPLY", math_node("MULTIPLY", dark, blue), over_red)
ramp_grey = nodes.new("ShaderNodeSeparateColor")
links.new(ramp.outputs["Color"], ramp_grey.inputs["Color"])
to_glass = math_node("SUBTRACT", glass["grey"], ramp_grey.outputs[0])
grey = math_node("MULTIPLY_ADD", is_glass, to_glass, ramp_grey.outputs[0])
combine = nodes.new("ShaderNodeCombineColor")
for i in range(3):
links.new(grey, combine.inputs[i])
links.new(combine.outputs["Color"], bsdf.inputs["Base Color"])
return material
@@ -316,15 +393,47 @@ def turn_rotors(mesh, parts, degrees, rotor_material):
return swept_radii
def load_model(path, material, rotor_deg, rotor_material):
def reshape(mesh, waterline, beam, squash_above):
"""Bring a mesh into the scene's axes, cut away what lies below the
waterline (z = 0) and scale it across the beam and above a height."""
world = mesh.matrix_world.copy()
mesh.parent = None
mesh.matrix_world = Matrix.Identity(4)
mesh.data.transform(world)
bm = bmesh.new()
bm.from_mesh(mesh.data)
if waterline:
bmesh.ops.bisect_plane(
bm,
geom=bm.verts[:] + bm.edges[:] + bm.faces[:],
dist=1e-4,
plane_co=(0.0, 0.0, 0.0),
plane_no=(0.0, 0.0, 1.0),
clear_inner=True,
)
for vertex in bm.verts:
vertex.co.y *= beam
if squash_above and vertex.co.z > squash_above[0]:
height, k = squash_above
vertex.co.z = height + (vertex.co.z - height) * k
bm.to_mesh(mesh.data)
bm.free()
def load_model(path, material, rotor_deg, rotor_material, waterline=False, options=None):
options = options or {}
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 []
beam = options.get("beam", 1.0)
squash_above = options.get("squash_above")
radius = 0.0
for mesh in meshes:
if waterline or beam != 1.0 or squash_above:
reshape(mesh, waterline, beam, squash_above)
mesh.data.materials.clear()
mesh.data.materials.append(material)
swept_radii = turn_rotors(mesh, parts, rotor_deg, rotor_material) if parts else {}
@@ -490,55 +599,63 @@ def save_png(path, pixels):
def main():
opts = args_after_dashes()
config = SHEETS[opts["sheet"]]
name_of_sheet = config["name"]
columns = config["columns"]
subjects = config["subjects"]
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()
materials = {
key: paint_material(ramp, glass=GLASS.get(key)) for key, ramp in PAINTS.items()
}
rotor_material = paint_material(None, solid=0.82)
directions = frame_directions(config)
frames = len(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)
rows = math.ceil(len(subjects) * frames / columns)
sheet = np.zeros((rows * cell, columns * cell, 4), dtype=np.float32)
manifest = {
"image": "aircraft-views.webp",
"image": f"{name_of_sheet}.webp",
"cellPx": cell,
"columns": COLUMNS,
"columns": columns,
"rows": rows,
"ringStepDeg": RING_STEP_DEG,
"rings": RINGS,
"ringStepDeg": config["ring_step_deg"],
"rings": config["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
for index, (name, model, options) 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,
materials[options.get("paint", config["paint"])],
options.get("rotor_deg"),
rotor_material,
config["waterline"],
options,
)
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))
frame = finish(read_pixels(tmp), supersample, options.get("bold_px", 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
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)
@@ -547,15 +664,15 @@ def main():
)
for obj in objects:
bpy.data.objects.remove(obj, do_unlink=True)
print(f"baked {name}: {FRAMES} frames, radius {radius:.2f} m", flush=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:
save_png(os.path.join(out, f"{name_of_sheet}.png"), sheet)
with open(os.path.join(out, f"{name_of_sheet}.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})")
print(f"wrote {out}/{name_of_sheet}.png ({columns * cell}x{rows * cell})")
main()
@@ -1,13 +1,16 @@
#!/usr/bin/env node
/**
* build-aircraft-views.mjs: bake the aircraft view sheet and ship it.
* build-view-sheet.mjs: bake a view sheet (aircraft or vessels) 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`.
* Runs `scripts/bake-view-sheet.py` in Blender (headless) into a scratch
* directory, then writes the sheet to `public/sprites/` as
* `<name>.webp` (lossless WebP of the baked PNG) and `<name>.json` (its
* manifest): `aircraft-views` or `vessel-views`. See
* `public/sprites/README.md`.
*
* Run: npm run build:aircraft-views [-- --only airliner,light] [--out public/sprites]
* Run: node scripts/build-view-sheet.mjs --sheet aircraft|vessels
* [--only airliner,light] [--out public/sprites]
* (npm run build:aircraft-views, npm run build:vessel-views)
* Blender: `$BLENDER`, else `blender` on the PATH, else the macOS app.
*/
import { spawnSync } from 'node:child_process';
@@ -25,6 +28,15 @@ const opt = (name, fallback) => {
};
const OUT = path.resolve(root, opt('--out', 'public/sprites'));
const ONLY = opt('--only', null);
const SHEET = opt('--sheet', null);
if (SHEET !== 'aircraft' && SHEET !== 'vessels')
throw new Error('--sheet is aircraft or vessels');
// A bake of some subjects leaves the others' cells empty: it is for looking
// at, never for the sheet the app loads.
if (ONLY && !argv.includes('--out'))
throw new Error(
'--only bakes part of a sheet: give it its own --out, not public/sprites',
);
function blender() {
if (process.env.BLENDER) return process.env.BLENDER;
@@ -53,7 +65,7 @@ async function assertGrey(file) {
}
}
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'aircraft-views-'));
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'view-sheet-'));
try {
const bake = spawnSync(
blender(),
@@ -61,8 +73,10 @@ try {
'-b',
'--factory-startup',
'--python',
path.join(root, 'scripts', 'build-aircraft-view-sheet.py'),
path.join(root, 'scripts', 'bake-view-sheet.py'),
'--',
'--sheet',
SHEET,
'--out',
scratch,
...(ONLY ? ['--only', ONLY] : []),
@@ -75,20 +89,19 @@ try {
console.error(bake.stdout.split('\n').slice(-20).join('\n'));
throw new Error(`the bake failed (exit ${bake.status})`);
}
const [json] = fs.readdirSync(scratch).filter((f) => f.endsWith('.json'));
const name = path.basename(json, '.json');
const manifest = JSON.parse(
fs.readFileSync(path.join(scratch, 'aircraft-views.json'), 'utf8'),
fs.readFileSync(path.join(scratch, json), 'utf8'),
);
const png = path.join(scratch, 'aircraft-views.png');
const png = path.join(scratch, `${name}.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'),
);
fs.copyFileSync(path.join(scratch, json), path.join(OUT, json));
const kb = Math.round(fs.statSync(webp).size / 1024);
console.log(`wrote ${path.relative(root, webp)} (${kb} KB) and its manifest`);
} finally {
+6 -3
View File
@@ -2399,7 +2399,8 @@
"src/data/detectionOcclusion.js",
"src/layers/vessels/photos.js",
"src/data/openVesselPhoto.js",
"src/data/viewSheet.js"
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": ["cesium", "kdbush"]
},
@@ -5622,7 +5623,8 @@
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
@@ -6480,7 +6482,8 @@
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js",
"src/data/aircraftViews.js",
"src/data/viewSheet.js"
"src/data/viewSheet.js",
"src/data/vesselViews.js"
],
"external": [
"hls.js",
+85 -16
View File
@@ -10,7 +10,7 @@
* below.
*
* Run: node scripts/qa-aircraft-views.mjs --url http://localhost:4173 [--out qa-shots/views]
* [--layer military|flights] [--block-sheet] [--headful]
* [--layer military|flights|vessels] [--block-sheet] [--headful]
* [--orbit [--orbit-step 2] [--orbit-pitch -35]]
* Needs the dev server (`npm run dev`).
*/
@@ -27,9 +27,13 @@ const opt = (name, 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).
// `military` (amber, every class by type code), `flights` (white, the
// classes an ADS-B emitter category gives) or `vessels` (every hull kind by
// AIS ship type, at sea level).
const LAYER = opt('--layer', 'military');
const VESSELS = LAYER === 'vessels';
// The app's id of the layer.
const LAYER_ID = VESSELS ? 'ais-live-vessels' : LAYER;
// Fail the sheet's request: the contacts should draw their flat glyphs.
const BLOCK_SHEET = argv.includes('--block-sheet');
const GPU = argv.includes('--gpu');
@@ -56,11 +60,27 @@ const CATEGORIES = [
['glider', 9],
['helicopter', 8],
];
const ROWS = LAYER === 'flights' ? CATEGORIES : CLASSES;
// An AIS ship type for each hull kind (vesselTypes.js).
const HULLS = [
['cargo', 70],
['tanker', 80],
['passenger', 60],
['highspeed', 40],
['fishing', 30],
['tug', 52],
['sailing', 36],
['pleasure', 37],
['military', 35],
['other', 90],
['dredger', 33],
['pilot', 50],
];
const ROWS = VESSELS ? HULLS : LAYER === 'flights' ? CATEGORIES : CLASSES;
const COURSES = [0, 45, 90, 135, 180, 225, 270, 315];
const CENTRE = { lon: -97.74, lat: 30.3 };
// Aircraft over Austin; vessels on open water in the North Sea.
const CENTRE = VESSELS ? { lon: 3.2, lat: 52.6 } : { lon: -97.74, lat: 30.3 };
const STEP_DEG = 0.03;
const ALT_FT = 12000;
const ALT_FT = VESSELS ? 0 : 12000;
const contacts = [];
ROWS.forEach(([klass, type], row) =>
@@ -88,7 +108,11 @@ const SHOTS = [
{ 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 },
// From below, looking up at the grid; a vessel is never seen from there,
// so vessels get a shot from just above the water in its place.
VESSELS
? { name: '7-horizon-north', heading: 0, pitch: -5, rangeKm: 30 }
: { 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
@@ -139,7 +163,7 @@ async function main() {
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.isInterceptResolutionHandled()) return;
if (/\/sprites\/aircraft-views\./.test(request.url())) request.abort();
if (/\/sprites\/[a-z]+-views\./.test(request.url())) request.abort();
else request.continue();
});
}
@@ -197,6 +221,39 @@ async function main() {
),
}),
);
if (url.includes('/api/vessels') && seed.layer === 'vessels') {
const now = Date.now();
return Promise.resolve(
json({
rows: seed.contacts.map((c, i) => ({
...at(c),
name: c.flight,
mmsi: String(235000000 + i),
imo: '0',
type: String(c.t),
destination: 'QA',
length: 120,
beam: 20,
speed: SPEED_MPS * 1.9438,
course: c.courseDeg,
heading: c.courseDeg,
last_position_UTC: new Date(now).toISOString(),
last_position_epoch: Math.floor(now / 1000),
})),
source: 'AISStream',
status: 'live',
error: null,
refreshing: false,
newestPositionAt: now,
lastMessageAt: now,
silentForMs: 0,
reconnectAttempt: 0,
nextAttemptAt: null,
staleAfterMs: 120000,
watchdog: 'armed',
}),
);
}
if (url.includes('/api/flights/track'))
return Promise.resolve(json({ path: [] }));
if (url.includes('/api/flights') && seed.layer === 'flights') {
@@ -241,14 +298,26 @@ async function main() {
() => 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);
const seeded = await page.evaluate(
async (name, centre) => {
const { dataManager, viewer } = window.__godsEyeView;
// Over the grid first: a layer may ask only for what is in view.
const Cartesian3 = viewer.camera.position.constructor;
viewer.camera.setView({
destination: Cartesian3.fromDegrees(centre.lon, centre.lat, 60000),
});
await dataManager.setEnabled(name, true);
const layer = dataManager.layers.get(name).module;
for (let i = 0; i < 4; i++) {
await layer.update(viewer);
await new Promise((resolve) => setTimeout(resolve, 500));
}
window.__viewQaDriver = setInterval(() => layer.update(viewer), 8000);
return layer.getStats().count;
},
LAYER_ID,
CENTRE,
);
console.log(` ${LAYER} contacts: ${seeded}/${contacts.length}`);
if (seeded !== contacts.length)
throw new Error(
@@ -1,24 +1,29 @@
#!/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
* qa-view-sheet.mjs: contact sheets of a baked view sheet (aircraft or
* vessels), for reviewing a bake (`scripts/bake-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.
* (straight above at the top, the last ring at the bottom, each ring from
* dead ahead to dead astern), in white, over three grounds the subject is
* seen over. Under them, a few frames (above, oblique, abeam, and below or
* low on the horizon) shrunk to the sizes a contact is drawn at, in each
* tint the layers draw it with, to judge whether thin wings and hulls still
* read. Aircraft: a dark sea, pale land and a mid satellite tone; the fleet,
* tracked and military tints. Vessels: a dark sea, pale shallow water and a
* satellite ocean tone; white and the colour of each kind the subject is
* drawn for (`VESSEL_KIND_STYLES`).
*
* 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]
* Run: node scripts/qa-view-sheet.mjs [--manifest public/sprites/aircraft-views.json]
* [--sheet <image>] [--out qa-shots/<name>] [--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';
import { VESSEL_KIND_STYLES } from '../src/data/vesselTypes.js';
const argv = process.argv.slice(2);
const opt = (name, fallback) => {
@@ -28,26 +33,51 @@ const opt = (name, 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 VESSELS = manifest.image.startsWith('vessel');
const OUT = path.resolve(
opt('--out', `qa-shots/${path.basename(manifest.image, '.webp')}`),
);
const WHITE = { name: 'white', rgb: [1, 1, 1] };
/** `#rrggbb` as 0..1 channels. */
const rgbOf = (css) =>
[1, 3, 5].map((i) => parseInt(css.slice(i, i + 2), 16) / 255);
/** Grounds a contact is seen over. */
const GROUNDS = VESSELS
? [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'shallows', css: '#8fc3c1' },
{ name: 'satellite', css: '#0f2e44' },
]
: [
{ name: 'sea', css: '#1f3a4f' },
{ name: 'land', css: '#d9d2bd' },
{ name: 'satellite', css: '#6f7559' },
];
/** The kinds a vessel shape that is not a kind of its own is coloured as: a
* vessel takes its kind's colour (`vesselKind`), whatever its shape. */
const SHAPE_KINDS = { dredger: ['other'], pilot: ['tug', 'military'] };
/** A subject's tints, multiplied into the neutral sprite as the layers do. */
const tintsOf = (name) =>
VESSELS
? [
WHITE,
...(SHAPE_KINDS[name] ?? [name]).map((kind) => ({
name: kind,
rgb: rgbOf(VESSEL_KIND_STYLES[kind].css),
})),
]
: [
WHITE,
{ name: 'tracked', rgb: [0.22, 0.82, 1] },
{ name: 'military', rgb: [1, 0.72, 0] },
];
const sheetPath = path.resolve(
opt('--sheet', path.join(path.dirname(MANIFEST), manifest.image)),
);
@@ -58,13 +88,17 @@ 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));
const last = rings.length - 1;
/** Frames shown shrunk, as ring and index: straight above, oblique from
* ahead and to the right, abeam on the horizon, and from below, abeam. */
* ahead and to the right, abeam on the horizon, and the last ring from
* below abeam or, if the last ring is the horizon, from the bow quarter. */
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)],
last === ringAt(90)
? [last, Math.round((rings[last] - 1) / 4)]
: [last, Math.round((rings[last] - 1) / 2)],
];
const sheet = sharp(sheetPath, { limitInputPixels: false });
@@ -100,6 +134,7 @@ async function cellImage(index, tint, size) {
}
async function subjectSheet(name, first) {
const TINTS = tintsOf(name);
const tile = cell * ZOOM;
const panelW = widest * tile;
const panelH = rings.length * tile;
@@ -122,11 +157,11 @@ async function subjectSheet(name, first) {
left: x0,
top: GAP,
});
// Rings as rows, fleet white.
// Rings as rows, 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),
input: await cellImage(first + firsts[ring] + i, WHITE, cell),
left: x0 + i * tile,
top: GAP + ring * tile,
});
+53 -2
View File
@@ -59,9 +59,9 @@ const VESSEL_KIND_RULES = [
['fishing', /fishing|trawler/i],
[
'military',
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i,
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search\W+(?:and\W+|&\W*)?rescue/i,
],
['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i],
['tug', /tug|tow|pilot|tender|supply|service|anti\W?pollution/i],
['sailing', /sail/i],
['pleasure', /pleasure|yacht/i],
];
@@ -116,6 +116,57 @@ export function vesselKind(type) {
return kind;
}
/**
* Hull shapes drawn within a kind, where an AIS ship type has a hull of its
* own: a dredger (AIS 33, otherwise `other`), and the small workboats that
* are neither tugs nor patrol craft, drawn as a pilot boat (AIS 50 pilot,
* 51 search and rescue, 53 port tender, 54 anti-pollution). In order: the
* first that matches.
*/
const VESSEL_SHAPE_RULES = [
['dredger', /dredg/i],
[
'pilot',
/pilot|\bsar\b|search\W+(?:and\W+|&\W*)?rescue|port\W?tender|anti\W?pollution/i,
],
];
/** Every hull shape {@link vesselShape} names: the kinds, then the rest. */
export const VESSEL_SHAPES = Object.freeze([
'cargo',
'tanker',
'passenger',
'highspeed',
'fishing',
'tug',
'sailing',
'pleasure',
'military',
'other',
...VESSEL_SHAPE_RULES.map(([shape]) => shape),
]);
const SHAPE_MEMO = new Map();
/**
* The hull a vessel is shown as from the eye's angle (the vessel view
* sheet, `vesselViews.js`): its own where its AIS type has one, else its
* kind's ({@link vesselKind}). Its colour is always its kind's.
* @param {string} type Raw AIS type.
* @returns {string} One of `VESSEL_SHAPES`.
*/
export function vesselShape(type) {
const text = normalizeVesselType(type);
let shape = SHAPE_MEMO.get(text);
if (shape !== undefined) return shape;
shape =
VESSEL_SHAPE_RULES.find(([, pattern]) => pattern.test(text))?.[0] ??
vesselKind(type);
if (SHAPE_MEMO.size >= KIND_MEMO_MAX) SHAPE_MEMO.clear();
SHAPE_MEMO.set(text, shape);
return shape;
}
/**
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
+74
View File
@@ -0,0 +1,74 @@
/**
* @module data/vesselViews
* @description Which block of the vessel view sheet (`viewSheet.js`) a
* vessel's icon draws from. Each hull shape (`vesselShape`, vesselTypes.js)
* is rendered there from a sphere of camera angles, from straight above
* down to the horizon; a renderer with the `viewSheets` capability lays the icon
* flat on the water along its course and draws the view that matches where
* the eye is, so a ship seen at an oblique angle looks solid instead of
* like a flat hull. An aid to navigation keeps its upright buoy.
*/
import { VESSEL_VIEWS } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import { VESSEL_KINDS } from './vesselTypes.js';
/** One frozen image ref per shape and kind, so equal refs are the same. */
const refs = new Map();
/**
* The view image of a vessel: `{views, first, fallback}`, the sheet's id,
* the first cell of its hull shape's block and its kind's flat hull sprite
* (drawn while the sheet loads, or if it fails). A shape the sheet does not
* hold draws its kind's block, and a kind it does not hold `other`'s.
* @param {string} shape One of `VESSEL_SHAPES` (`vesselShape`).
* @param {string} [kind] One of `VESSEL_KINDS` (`vesselKind`); the shape
* itself by default.
* @returns {{views: string, first: number, fallback: string}}
*/
export function vesselViewRef(shape, kind = shape) {
const held = (name) => Number.isInteger(VESSEL_VIEWS.subjects[name]);
const flat = VESSEL_KINDS.includes(kind) ? kind : 'other';
const subject = held(shape) ? shape : held(flat) ? flat : 'other';
const key = `${subject}|${flat}`;
let ref = refs.get(key);
if (!ref) {
ref = Object.freeze({
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[subject],
fallback: vesselSprite(flat),
});
refs.set(key, ref);
}
return ref;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the vessel 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 registerVesselViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.('viewSheets')) return false;
if (!registered.has(drawPort)) {
const sheet = VESSEL_VIEWS.sheet;
drawPort.views(VESSEL_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { registerVesselViews, vesselViewRef } from './vesselViews.js';
import { VESSEL_VIEWS, viewLayout } from './viewSheet.js';
import { vesselSprite } from './vesselSprites.js';
import {
VESSEL_KINDS,
VESSEL_SHAPES,
vesselKind,
vesselShape,
} from './vesselTypes.js';
test('VESSEL_VIEWS holds a block for every hull shape, each on the sheet', () => {
const layout = viewLayout(VESSEL_VIEWS.sheet);
assert.equal(layout.frames, VESSEL_VIEWS.frames);
// To the horizon and no further: a ship is never seen from below.
assert.equal(
(VESSEL_VIEWS.sheet.rings.length - 1) * VESSEL_VIEWS.sheet.ringStepDeg,
90,
);
// Every shape, in order, a block each: the ten kinds, then the rest.
assert.deepEqual(Object.keys(VESSEL_VIEWS.subjects), [...VESSEL_SHAPES]);
assert.deepEqual(
VESSEL_SHAPES.slice(0, VESSEL_KINDS.length).toSorted(),
[...VESSEL_KINDS].sort(),
);
VESSEL_SHAPES.forEach((shape, i) =>
assert.equal(VESSEL_VIEWS.subjects[shape], i * VESSEL_VIEWS.frames, shape),
);
assert.ok(
VESSEL_SHAPES.length * VESSEL_VIEWS.frames <=
VESSEL_VIEWS.sheet.columns * VESSEL_VIEWS.sheet.rows,
);
});
test('every AIS ship type, 0 to 99, draws a shape the sheet holds, in its kind’s colour', () => {
// ITU-R M.1371: the families by their tens, and the types with a hull of
// their own.
const shapeOf = (code) => vesselShape(String(code));
const kindOf = (code) => vesselKind(String(code));
for (let code = 0; code < 100; code++) {
assert.ok(Number.isInteger(VESSEL_VIEWS.subjects[shapeOf(code)]), code);
assert.ok(VESSEL_KINDS.includes(kindOf(code)), code);
}
const drawn = (codes, shape, kind = shape) =>
codes.forEach((code) =>
assert.deepEqual([shapeOf(code), kindOf(code)], [shape, kind], code),
);
const tens = (ten) => Array.from({ length: 10 }, (_, i) => ten * 10 + i);
drawn(tens(7), 'cargo');
drawn(tens(8), 'tanker');
drawn(tens(6), 'passenger');
drawn(tens(4), 'highspeed');
drawn([30], 'fishing');
drawn([31, 32, 52], 'tug');
drawn([36], 'sailing');
drawn([37], 'pleasure');
drawn([35, 55], 'military');
drawn([33], 'dredger', 'other');
// Pilot, port tender and anti-pollution craft are service boats (the
// tug's colour); search and rescue is a patrol colour. One small hull.
drawn([50, 53, 54], 'pilot', 'tug');
drawn([51], 'pilot', 'military');
// Wing-in-ground craft, diving and medical vessels, the reserved and
// spare codes and "other": the plain hull.
drawn(
[0, 1, 19, ...tens(2), 34, 38, 39, 56, 57, 58, 59, ...tens(9)],
'other',
);
// A feed that names the type in words draws the same shapes.
assert.equal(vesselShape('Dredger'), 'dredger');
assert.equal(vesselShape('Pilot Vessel'), 'pilot');
assert.equal(vesselShape('Search and Rescue'), 'pilot');
// However the words are joined, the hull and the colour are the code's.
for (const text of ['Search & Rescue', 'Search-and-rescue', 'SAR'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'military'],
text,
);
for (const text of ['Anti Pollution', 'Anti-pollution', 'Port Tender'])
assert.deepEqual(
[vesselShape(text), vesselKind(text)],
['pilot', 'tug'],
text,
);
assert.equal(vesselShape('Tug'), 'tug');
assert.equal(vesselShape('Container Ship'), 'cargo');
assert.equal(vesselShape(''), 'other');
});
test('a vessel draws its shape’s block of the sheet, with its kind’s flat hull to fall back on', () => {
for (const kind of VESSEL_KINDS) {
const ref = vesselViewRef(kind);
assert.deepEqual(ref, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects[kind],
fallback: vesselSprite(kind),
});
assert.ok(Object.isFrozen(ref));
// One object a shape and kind: an unchanged icon is seen as unchanged.
assert.equal(vesselViewRef(kind), ref);
}
// A shape within a kind: its own block, its kind's flat hull.
assert.deepEqual(vesselViewRef('pilot', 'tug'), {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
assert.notEqual(
vesselViewRef('pilot', 'tug'),
vesselViewRef('pilot', 'military'),
);
assert.equal(
vesselViewRef('dredger', 'other').first,
VESSEL_VIEWS.subjects.dredger,
);
// A shape the sheet does not hold: its kind's block, then `other`'s.
assert.equal(
vesselViewRef('hovercraft', 'highspeed'),
vesselViewRef('highspeed'),
);
assert.equal(vesselViewRef('submarine'), vesselViewRef('other'));
assert.equal(vesselViewRef(undefined), vesselViewRef('other'));
});
test('the sheet is registered once a port, at the layer’s asset URL, on a renderer that draws views', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const views = new Set(['viewSheets']);
const resolve = (url) => `/gev${url}`;
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(registerVesselViews(port, views, resolve), true);
assert.equal(calls.length, 1);
assert.equal(calls[0][0], VESSEL_VIEWS.id);
assert.deepEqual(calls[0][1], {
...VESSEL_VIEWS.sheet,
image: '/gev/sprites/vessel-views.webp',
});
// No capability, no port, or a port without `views`: flat hulls.
assert.equal(registerVesselViews(port, new Set(), resolve), false);
assert.equal(registerVesselViews(port, null), false);
assert.equal(registerVesselViews(null, views), false);
assert.equal(registerVesselViews({}, views), false);
});
+41 -2
View File
@@ -3,8 +3,9 @@
* @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.
* engine. `scripts/bake-view-sheet.py` bakes the aircraft and
* vessel sheets to their layouts here; a renderer with the `viewSheets`
* capability draws them.
*
* **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
@@ -64,6 +65,44 @@ export const AIRCRAFT_VIEWS = Object.freeze({
}),
});
/**
* The vessel hull shapes' view sheet (`public/sprites/vessel-views.json`):
* from straight above down to the horizon, a ship never being seen from
* below.
*/
export const VESSEL_VIEWS = Object.freeze({
id: 'vessel-views',
sheet: Object.freeze({
image: '/sprites/vessel-views.webp',
cellPx: 64,
columns: 64,
rows: 39,
ringStepDeg: 7.5,
rings: Object.freeze([1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 208,
/**
* Each hull shape's first cell (`vesselShape`, vesselTypes.js): the ten
* hull kinds, then the shapes drawn within a kind.
*/
subjects: Object.freeze({
cargo: 0,
tanker: 208,
passenger: 416,
highspeed: 624,
fishing: 832,
tug: 1040,
sailing: 1248,
pleasure: 1456,
military: 1664,
other: 1872,
dredger: 2080,
pilot: 2288,
}),
});
/**
* Check a sheet's layout, and return it with each ring's first frame.
* @param {{image: string, cellPx: number, columns: number, rows: number,
+101 -51
View File
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
import test from 'node:test';
import {
AIRCRAFT_VIEWS,
VESSEL_VIEWS,
frameDirection,
frameUp,
viewFrame,
@@ -266,65 +267,110 @@ test('AIRCRAFT_VIEWS is consistent: a block a subject, every block on the sheet'
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,
);
const BAKE = new URL('../../scripts/bake-view-sheet.py', 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`);
/** The sheets the bake script bakes: its config name, the layout it must
* match, the files it ships and the size the layout pins. */
const SHEETS = [
{
config: 'AIRCRAFT',
views: AIRCRAFT_VIEWS,
name: 'aircraft-views',
frames: 302,
size: [4096, 3648],
},
{
config: 'VESSELS',
views: VESSEL_VIEWS,
name: 'vessel-views',
frames: 208,
size: [4096, 2496],
},
];
/** A sheet's entry in the bake script: `NAME = { ... }`. */
function bakeConfig(script, config) {
const block = new RegExp(`^${config} = \\{([\\s\\S]*?)^\\}`, 'm').exec(
script,
);
assert.ok(block, `${config} in the bake script`);
const field = (key) => {
const match = new RegExp(`^\\s*"${key}": (.+),$`, 'm').exec(block[1]);
assert.ok(match, `${config}.${key} 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);
});
const names = [...block[1].matchAll(/^\s*\("(\w+)", "([\w/.]+)"/gm)];
return {
field,
names: names.map((m) => m[1]),
models: names.map((m) => m[2]),
};
}
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;
for (const { config, views, name, frames, size } of SHEETS) {
test(`${views.id} is pinned: ${frames} frames a subject, ${size.join(' × ')} px`, () => {
const { sheet } = views;
assert.equal(views.frames, frames);
assert.equal(viewLayout(sheet).frames, frames);
assert.equal(sheet.cellPx * sheet.columns, size[0]);
assert.equal(sheet.cellPx * sheet.rows, size[1]);
assert.equal(sheet.image, `/sprites/${name}.webp`);
assert.equal(sheet.grey, true);
});
test(`the bake script lays ${views.id} out as the layout says`, () => {
const { field, names } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = views;
assert.equal(field('name'), name);
assert.equal(field('ring_step_deg'), sheet.ringStepDeg);
assert.deepEqual(field('rings'), [...sheet.rings]);
assert.equal(field('columns'), sheet.columns);
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,
);
});
const manifestUrl = new URL(
`../../public/sprites/${name}.json`,
import.meta.url,
);
test(`the baked manifest matches ${views.id}`, () => {
// Shipped with the app: a missing manifest fails, it does not skip.
assert.ok(existsSync(manifestUrl), `public/sprites/${name}.json`);
const manifest = JSON.parse(readFileSync(manifestUrl, 'utf8'));
const { models } = bakeConfig(readFileSync(BAKE, 'utf8'), config);
const { sheet, subjects } = 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.equal(manifest.image, `${name}.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);
},
);
Object.entries(subjects).forEach(([subject, first], i) => {
assert.equal(manifest.subjects[subject].first, first, subject);
assert.equal(manifest.subjects[subject].model, models[i], subject);
assert.ok(manifest.subjects[subject].radiusM > 0, `${subject} baked`);
});
});
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 sheetUrl = new URL(
`../../public/sprites/${name}.webp`,
import.meta.url,
);
test(`the shipped ${name}.webp is the size the layout says, grey, and clear at every cell’s edge`, async () => {
assert.ok(existsSync(sheetUrl), `public/sprites/${name}.webp`);
const { default: sharp } = await import('sharp');
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
const { data, info } = await sharp(fileURLToPath(SHEET))
const { sheet, subjects } = views;
const { data, info } = await sharp(fileURLToPath(sheetUrl))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
@@ -335,21 +381,25 @@ test(
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).
// Each used cell keeps its outer 2 px transparent (the mipmaps), and
// has something in it.
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;
let drawn = 0;
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)
const alpha = data[at(left + x, top + y) + 3];
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) drawn += alpha;
else if (alpha !== 0)
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
}
assert.ok(drawn > 0, `cell ${n} is empty`);
}
},
);
});
}
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
+72 -2
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createVesselLayer } from './index.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { VESSEL_VIEWS } from '../../data/viewSheet.js';
// Following the world clock on a renderer that moves icons along motion
// segments on its own clock, each vessel's icon is drawn along its track
@@ -10,7 +12,7 @@ import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const noop = () => {};
function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
function setup(t, { capabilities = new Set(['motionSegments']), fleet } = {}) {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
@@ -35,6 +37,7 @@ function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
clearOverlaySource: noop,
},
geoid: {},
...(fleet ? { fleet } : null),
sprites: {},
focus: {
focusNowMs: () => 0,
@@ -68,7 +71,7 @@ function setup(t, { capabilities = new Set(['motionSegments']) } = {}) {
[...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
);
return { layer, viewer, icons };
return { layer, viewer, icons, draw };
}
const T = 1_000_000;
@@ -282,3 +285,70 @@ test('going live, a vessel a live update has drawn since stays where that drew i
assert.deepEqual(icons().items.get(id).pos, visual.position);
}
});
test('on a renderer that draws view sheets a vessel is a view of its hull, an aid still its buoy', (t) => {
const { layer, viewer, icons, draw } = setup(t, {
capabilities: new Set(['motionSegments', 'viewSheets']),
fleet: { resolveAsset: (url) => `/gev${url}` },
});
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
{ ...row(minuteFixes), mmsi: '222', type: '36' },
{ ...row(minuteFixes), mmsi: '333', type: '50' },
{ ...row(minuteFixes), mmsi: '993672001', type: 'Port Hand Mark' },
]);
// The sheet, once, at the layer's asset URL.
assert.deepEqual(draw.viewSheets, [
[
VESSEL_VIEWS.id,
{ ...VESSEL_VIEWS.sheet, image: '/gev/sprites/vessel-views.webp' },
],
]);
const set = icons();
const cargo = set.items.get('111');
assert.deepEqual(cargo.image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.cargo,
fallback: vesselSprite('cargo'),
});
assert.equal(cargo.rotationMode, 'course', 'a view lies along its course');
assert.equal(cargo.imageLod, undefined);
assert.equal(set.items.get('222').image.first, VESSEL_VIEWS.subjects.sailing);
// A pilot boat: its own hull from the sheet, a service boat's flat hull.
assert.deepEqual(set.items.get('333').image, {
views: VESSEL_VIEWS.id,
first: VESSEL_VIEWS.subjects.pilot,
fallback: vesselSprite('tug'),
});
const buoy = set.items.get('993672001');
assert.equal(buoy.image, aidSprite());
assert.equal(buoy.rotationMode, 'screen');
});
test('without view sheets a vessel keeps its flat hull', (t) => {
const { layer, viewer, icons, draw } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
{ ...row(minuteFixes), type: 'Cargo' },
]);
assert.deepEqual(draw.viewSheets, []);
assert.equal(icons().items.get('111').image, vesselSprite('cargo'));
});
test('a vessel is drawn larger near than far, under an aircraft at every range, and recedes toward the horizon', (t) => {
const { layer, viewer, icons } = setup(t);
layer.testing._reconcileVesselsForTest(viewer, [
// The fastest step of a vessel's own scale.
{ ...row(minuteFixes), type: 'Cargo', speed: 20 },
]);
const set = icons();
assert.deepEqual(set.spec.recede, {}, "the renderer's own recession");
const item = set.items.get('111');
const curve = item.scaleByDistance;
const px = (value) => item.size[0] * item.scale * value;
assert.ok(px(curve.nearValue) > px(1), 'larger up close than it was');
// An aircraft icon: 20 px, three times that near and half of it far, over
// the same range (aircraftIconLayer.js).
assert.deepEqual([curve.near, curve.far], [1000, 8000000]);
assert.ok(px(curve.nearValue) < 20 * 3);
assert.ok(px(curve.farValue) < 20 * 0.5);
});
+56 -12
View File
@@ -44,8 +44,13 @@ import {
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { vesselPartState } from '../../data/modelPartDrivers.js';
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
import {
isAidToNavigation,
vesselKind,
vesselShape,
} from '../../data/vesselTypes.js';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { registerVesselViews, vesselViewRef } from '../../data/vesselViews.js';
import { cssColor } from '../../render/color.js';
import { KNOT_MPS } from '../../data/units.js';
@@ -61,6 +66,19 @@ const HIDDEN_FOLLOW_MS = 250;
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
const SHIP_ICON_PX = 32;
/**
* How a vessel or aid sprite's size follows its range from the eye, on the
* aircraft icons' range (`aircraftIconLayer.js`): half as large again up
* close, where a hull's shape reads; as it was drawn before at some
* 1,000 km; and a third from 8,000 km out. Under an aircraft's icon at every
* range, so a world of ships is a field of small marks.
*/
const SHIP_SCALE_BY_DISTANCE = Object.freeze({
near: 1000,
nearValue: 1.5,
far: 8000000,
farValue: 0.35,
});
let instances = 0;
@@ -228,6 +246,7 @@ export function createRendering({
advanceSpriteFocus,
focusAlphaNeedsWrite,
spriteFocusAtRest,
nearFarScalarValueAtDistance,
} = services.focus;
const {
holdContinuousRender,
@@ -265,12 +284,22 @@ export function createRendering({
const capabilities = rendererOf(viewer)?.capabilities ?? null;
iconMotion = capabilities?.has('motionSegments') === true;
segmentsWere = segmentsOn();
// On a renderer that draws view sheets a vessel is the view of its
// hull from where the eye is, not the flat hull.
iconViews = registerVesselViews(
drawOf(viewer),
capabilities,
services.fleet?.resolveAsset,
);
const set = drawOf(viewer).icons({
id: `ais-vessels:${++instances}`,
// Translucent, as its billboards were: overlapping chevrons keep
// their outlines rather than the first one's fill.
blend: 'translucent',
horizonCull: true,
// Toward the horizon a vessel shrinks and fades, as an aircraft does
// (the renderer's defaults, which are the aircraft sets').
recede: {},
drawOrder: spriteDrawOrder?.('ais') ?? 0,
...(iconMotion ? { motionClock: motionClock(segmentsWere) } : null),
});
@@ -286,6 +315,8 @@ export function createRendering({
// segments on its own clock.
let iconSet = null;
let iconMotion = false;
// Whether a vessel's icon is drawn from the vessel view sheet.
let iconViews = false;
// Whether the icons last moved on the renderer's clock.
let segmentsWere = false;
// The record drawn under each icon id, for replanning an id.
@@ -381,6 +412,7 @@ export function createRendering({
state.icons?.dispose();
state.icons = null;
iconSet = null;
iconViews = false;
iconRecords.clear();
planFrom.clear();
replannedAtMs = -Infinity;
@@ -430,6 +462,7 @@ export function createRendering({
// Tinted by type; selection changes neither the colour nor the size.
color: shipTint(record),
scale: shipScale(record),
scaleByDistance: SHIP_SCALE_BY_DISTANCE,
// An aid's buoy stands upright on screen; a vessel turns with course.
rotationMode: aid ? 'screen' : 'course',
rotation: 0,
@@ -529,18 +562,22 @@ export function createRendering({
}
/**
* The sprite a vessel is drawn as: the white hull of its kind
* (`vesselKind`), bow up so the row's course turns it to its heading, or
* for an aid to navigation the buoy. The layer tints it
* (`shipTint`), so each shape takes one icon-atlas slot.
* The sprite a vessel is drawn as: on a renderer that draws view sheets,
* the view of its kind's hull (`vesselKind`) from where the eye is
* (`vesselViews.js`), with the flat hull to fall back on; else the flat
* white hull, bow up so the row's course turns it to its heading. An aid
* to navigation is the buoy either way. The layer tints it (`shipTint`).
* @param {Object} record - Vessel record.
* @returns {string} SVG data URL.
* @returns {string|{views: string, first: number, fallback: string}} SVG
* data URL, or a view of the vessel sheet.
*/
function shipIcon(record) {
return isAidToNavigation(record)
? aidSprite()
: vesselSprite(vesselKind(record.type));
if (isAidToNavigation(record)) return aidSprite();
const kind = vesselKind(record.type);
return iconViews
? vesselViewRef(vesselShape(record.type), kind)
: vesselSprite(kind);
}
/**
@@ -1308,18 +1345,25 @@ export function createRendering({
!focusAlphaNeedsWrite(icons.focus(id), 1, params)
)
continue;
const cameraDistance = cameraDistanceFor(position);
// The sprite's half size as drawn at that range.
const half =
(item.scale ?? 1) *
(nearFarScalarValueAtDistance?.(item.scaleByDistance, cameraDistance) ??
1) *
0.5;
const focus = advanceSpriteFocus(sprite, {
// Hidden/far-side icons still finish any pending release so the active
// count remains truthful and they cannot reappear with stale dim alpha.
screenPosition: visual.visible ? screenPositionFor(position) : null,
cameraDistance: cameraDistanceFor(position),
cameraDistance,
nowMs,
target,
params,
// Vessel artwork is 32 px before scale. Including the ambient
// chevron's own rendered extent prevents edge-overlap misses.
spriteHalfWidthPx: item.size[0] * (item.scale ?? 1) * 0.5,
spriteHalfHeightPx: item.size[1] * (item.scale ?? 1) * 0.5,
spriteHalfWidthPx: item.size[0] * half,
spriteHalfHeightPx: item.size[1] * half,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;