@motionstudies/core 0.1.0-alpha.2 → 0.1.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,8 +4,8 @@ Shared packages for the Motion Studies transport instrument. The source workspac
4
4
 
5
5
  - `@motionstudies/core`: transport contracts, indexing, interpolation and visual theme contracts; no browser or Node dependencies.
6
6
  - `@motionstudies/three`: `NationalNetworkScene`, `HubPulseScene`, `StationFlowScene`, camera framing and label-mode contracts. React, React Three Fiber and Three.js are peers; rendering internals are not public subpaths.
7
- - `@motionstudies/web`: picker, button tooltips, theme application, mounting, progressive loaders, observed operations and recording. Import `tokens.css` and `mobile-picker.css` for isolated widgets. `shell.css` is an optional full-page study shell scoped to `.motion-study`; `mountMotionStudy` applies that class. Fonts and edition layouts belong to consumers.
8
- - `@motionstudies/data`: Node-only GTFS readers, network chunking, merging and station ranking. ZIP reading requires `unzip` on the host. Source selection, provenance overrides and compilation commands belong to each edition.
7
+ - `@motionstudies/web`: picker, button tooltips, theme application, mounting, progressive loaders, observed operations and recording. Import `tokens.css` and `mobile-picker.css` for isolated widgets. `shell.css` is an optional full-page study shell scoped to `.motion-study`; `mountMotionStudy` applies that class. Import `fonts.css` for the self-hosted Inter and DM Mono faces those stylesheets name, licensed under the SIL Open Font License 1.1; other typefaces and edition layouts belong to consumers.
8
+ - `@motionstudies/data`: Node-only GTFS readers, ADS-B heatmap compilation, air endpoint enrichment, network chunking, merging and station ranking. ZIP reading requires `unzip` on the host. Source selection, provenance overrides and compilation commands belong to each edition.
9
9
 
10
10
  ```tsx
11
11
  import { MobilePicker } from '@motionstudies/web/components/MobilePicker'
@@ -25,8 +25,237 @@ Build release candidates with `npm run build:packages`. Distribution manifests a
25
25
 
26
26
  Source workspace manifests always stay private. `npm run check:release` builds public candidates, tests their packed consumer and records the tested tarball hashes; `npm run release:dry-run` inspects the publication without writing to npm. The manual main-branch `release.yml` workflow publishes those same tarballs with public access and provenance. See [release instructions](https://github.com/emmettl/motionstudies/blob/main/docs/RELEASING.md) for bootstrap-token and trusted-publisher setup. All four shared packages are MIT-licensed; each distribution includes `LICENSE`.
27
27
 
28
+ ## Timetable patterns, station calls and observation windows
29
+
30
+ `@motionstudies/core/domain/network-patterns` provides a transport-neutral repeated-schedule codec. `@motionstudies/web/use-pattern-network-day` lazily decodes current/adjacent chunks after verifying byte length and SHA-256; it exposes retry and drops old-source state when the manifest URL changes. Supply stable options and a stable asset resolver. Format/category options support existing edition wire contracts.
31
+
32
+ `@motionstudies/core/domain/station-calls` supplies station calls, independent source status, namespaced source combination and upcoming-call filtering. Source IDs, repeated visits and acquired windows survive combination. Consumers supply interchange IDs and passenger restrictions; matching display names do not collapse services.
33
+
34
+ `@motionstudies/data/observation-windows` compiles bounded acquired records into hashed windows with explicit time semantics, conflict policy and acquisition-gap reporting. It preserves supplied record IDs, values and source references. It uses elapsed UTC seconds, including 23/25-hour study days, and performs no acquisition or inference. See [contracts, limits and parity evidence](../docs/ALLCHANGE-FOUNDATIONS.md).
35
+
36
+ ## Now and browser location
37
+
38
+ `useNowClock` from `@motionstudies/web/use-now-clock` follows the wall clock on each animation frame, so returning from a suspended tab catches up immediately. Call `start()` from a Now button, set the consumer's playback rate to 1, and render its `time` while `active`. With `NationalNetworkScene`, pass `isPlaying={false}` while this external clock owns time. Call `stop()` before pausing, seeking or changing speed, and retain the last clock time for ordinary playback. Clear moving vehicle selections on entry to keep the camera still; panning and zooming remain available.
39
+
40
+ Supply a resolver `(instant: Date) => number | null` that maps the instant into the edition's service-time coordinates. The edition owns timezone, service date, daylight-saving rules and source coverage. Now is appropriate when the data gives a meaningful sense of this place at this time; exact live vehicle positions are not required. An edition may explicitly map the current local clock onto a suitable representative weekday or seasonal timetable, with a quiet label such as “Typical weekday · realtime pace”. Historical or modelled sources need that same meaningful relationship to the present; merely having timestamps is insufficient. Return null outside the chosen data's coverage: the hook stops, retains the last valid time and exposes `unavailable`. Do not silently relabel a recording as live or wrap a partial study window. Timetable and observed-data labels remain the consumer's responsibility; 1× playback does not imply a live vehicle feed.
41
+
42
+ `useBrowserLocation` from `@motionstudies/web/use-browser-location` requests a single position only when `locate()` is called. It exposes `location`, `status` and `clear()`; it neither stores nor sends coordinates. Render localized messages for denied, timeout and unavailable states. Clearing or unmounting discards late responses. A secure browser context and user permission are required.
43
+
44
+ Pass an in-coverage position as `NationalNetworkScene`'s `userLocation` for a steady glowing dot. Use the existing `focus-location` camera command once after locating, with `[longitude, latitude]` and a suitable `distanceScale`. Validate coverage in the consumer and preserve the view when the user is outside it. Show the reported `accuracy` in accessible text; the dot is an approximate position. The marker hides in diagram layouts. The lab's **Now** specimen uses a clearly labelled synthetic UTC timetable and covers clock, permission and out-of-coverage behavior. Public editions still require independent adoption and releases.
45
+
46
+ ## Selection labels
47
+
48
+ `NationalNetworkScene` gives the selected station first label priority, followed by the selected route's terminal stops (including branches), then intermediate stops. Selected services use their own endpoints. Priority precedes retained labels and ordinary rank/tier admission; clearing selection restores edition ranking. This is built in for every consumer, including geographic and diagram layouts. Supply complete enabled infrastructure as `referenceSnapshot` to preserve endpoints through timetable gaps; its stop indexes need not match the active snapshot. See the [edition behaviour contract](https://github.com/emmettl/motionstudies/blob/main/docs/EDITIONS.md#selection-and-station-labels).
49
+
28
50
  ## Button help
29
51
 
30
52
  `mountMotionStudy` installs one shared tooltip surface. Independent consumers such as the lab can render `ButtonTooltips` from `@motionstudies/web/components/ButtonTooltips` once instead. Put concise, action-oriented help in each button’s `data-tooltip`; icon buttons fall back to their `aria-label`. An empty `data-tooltip` opts out. Avoid native `title` attributes on these buttons, which can also appear during touch interaction.
31
53
 
32
54
  Help appears after a short mouse hover or on keyboard focus when the primary pointer is fine and supports hover. Touch input suppresses it, including on hybrid devices. Escape, activation, scrolling and blur dismiss it. The tooltip stays inside the viewport, can itself be hovered, and temporarily extends `aria-describedby` without replacing existing descriptions. Copy and translations stay in the edition; rendering and input handling stay in this package. The Controls specimen and packed-consumer tests exercise this contract.
55
+
56
+ ## Airport heroes and split-flap boards
57
+
58
+ `AirportHeroCard` provides an airport identity header and switchable departure/arrival boards. `SplitFlapBoard` is the underlying transport-neutral widget, also suitable for rail stations. Both use scoped package styles, semantic tables, full accessible cell values, keyboard-operable selection, contained horizontal scrolling and reduced-motion support. Only changed characters remount for the flap animation.
59
+
60
+ ```tsx
61
+ import { AirportHeroCard } from '@motionstudies/web/components/AirportHeroCard'
62
+ import '@motionstudies/web/airport-hero-card.css'
63
+
64
+ <AirportHeroCard
65
+ key={airport.id}
66
+ airport={airport}
67
+ departures={departures}
68
+ arrivals={arrivals}
69
+ study={{ time, windowStart: metadata.windowStart, windowEnd: metadata.windowEnd }}
70
+ dateLabel={metadata.serviceDate}
71
+ note="Observed study · inferred directions; times are observations."
72
+ onSelectFlight={selectAirTrack}
73
+ selectedFlightId={selectedAirTrackId}
74
+ />
75
+ ```
76
+
77
+ Entries have a stable `id`, a `service` label, and optional numeric `time`, `place`, `stand`, `status` and `tone` (`neutral`, `accent` or `warning`). Movement times and `study.time`, `windowStart`, and `windowEnd` must use the same study-relative seconds and service date. Do not parse display strings or normalize numeric times at midnight: an event after 24:00 retains its value above 86,400. `formatTime` optionally controls display formatting; the default uses the study's `formatServiceTime` helper. The header clock is derived directly from `study.time`, with no independent wall clock.
78
+
79
+ The card sorts movements chronologically and shows up to eight rows per direction inside the intersection of the study bounds and a rolling window: ten minutes behind the playback clock and sixty minutes ahead, with inclusive endpoints. Override this with `horizon={{ lookBehindSeconds: 600, lookAheadSeconds: 3600 }}` and `maxRows`. Playback, backward seeking, changed study bounds and updated movement times all recalculate the rows. An out-of-study or invalid clock shows no movements; rows with missing or non-finite times are excluded because they cannot be placed in the window. Other unknown fields render as a dash. Labels include `studyTime`, `boardWindow` and `outsideWindow` for localization. Filtering does not infer operational statuses or clear the consumer's map selection when a row leaves the window.
80
+
81
+ Consumers still own time coordinates, source interpretation and data loading. Supply movements for the displayed horizon, not just aircraft active at the current second, and use the selected study's bounds rather than an individual progressive chunk's bounds. Do not turn an approach-envelope association into a confirmed departure/arrival: unclassified tracks should remain outside these direction lists. Current `AirTrack` data does not supply scheduled times, routes or gates; leave those fields absent, use observation times only when clearly labelled, and explain any inference in the required `note`.
82
+
83
+ Pass `labels` for edition translations, `loading`, or a localized `error` and `onRetry` for data states. The selected direction is local to each card; key the card by airport ID to reset it on selection changes. The Airports lab specimen exercises synthetic timetables, playback, scrubbing, study-window changes, incomplete observations, French labels, long destinations, updates and recovery. Edition adoption happens through their independently pinned package releases; adding this export does not update deployed studies.
84
+
85
+ For a custom rail or transport board, import `SplitFlapBoard` from `@motionstudies/web/components/SplitFlapBoard` and `@motionstudies/web/split-flap-board.css`. Supply `columns` (`key`, `label`, `characters`) and `rows` (`id`, `cells`, optional `tone`). Cell text longer than its flap count is visually ellipsized, with the full value retained for assistive technology and hover. `onSelectRow`, `selectedRowId` and `selectionColumn` optionally make one cell per row selectable.
86
+
87
+ For bus stops and local transport, `DotMatrixBoard` accepts the same rows, selection callbacks, loading state and empty/loading messages. It uses an amber 5 × 7 LED alphabet and its own scoped stylesheet; the flip-board stylesheet is not required. Consumers can switch components without remapping their data.
88
+
89
+ ```tsx
90
+ import { DotMatrixBoard } from '@motionstudies/web/components/DotMatrixBoard'
91
+ import '@motionstudies/web/dot-matrix-board.css'
92
+
93
+ <DotMatrixBoard
94
+ label="Bus departures"
95
+ columns={[
96
+ { key: 'route', label: 'Route', characters: 4, minCharacters: 4 },
97
+ { key: 'destination', label: 'Destination', characters: 24 },
98
+ { key: 'time', label: 'Due', characters: 6, minCharacters: 6, align: 'right' },
99
+ ]}
100
+ rows={[{ id: 'bus-71', cells: { route: '71', destination: 'City Centre', time: '2 min' } }]}
101
+ lineCount="auto"
102
+ style={{ height: 360 }}
103
+ />
104
+ ```
105
+
106
+ `lineCount` defaults to six display slots and accepts 1–30 (values outside that range are clamped; non-finite values use six). Fixed counts keep all slots and scale their contents to the available height, so dense boards need taller containers to remain readable. `"auto"` observes the actual container and fits 1–30 rows at a target `minRowHeight` of 34px. The default board height is 320px; use `style`, `className`, or `height: '100%'` inside a parent with a defined height. Unused slots stay blank; rows beyond the visible slots are omitted, without pagination or changes to consumer selection.
107
+
108
+ For dot-matrix columns, `characters` is a width weight, while `minCharacters` reserves space before the remaining width is distributed. At very narrow widths all columns scale down. Long cell values are visually ellipsized, with their full original text available to assistive technology and on hover. Characters outside the bitmap alphabet (including accented names and non-Latin scripts) use SVG text as a visual fallback. `--matrix-ink` and `--matrix-unlit` customize the LEDs. Updates are immediate, with no flashing or scrolling animation. The **Bus boards** lab specimen exercises both presentations, height/width resizing, row counts, selection, long names, loading and empty states using synthetic timetable data.
109
+
110
+ `variant="uk-rail"` gives the matrix a square black enclosure, mixed-case amber lettering, matrix column headings and horizontal display bands. Optional `heading` and `headingColumnSpan` replace the visual labels across the leading columns while preserving the individual accessible column headers. `footerLabel` and `clockLabel` add a matrix footer; the consumer owns clock formatting and updates. No live clock or pagination is inferred. `DotMatrixRow.note` adds a detail line and an accessible description on the selection button. Details consume one display slot and stay with their departure: if only one slot remains, the next departure with a detail waits until there is room for both. A one-line board still shows its first departure, retaining its full note for assistive technology.
111
+
112
+ ## Rail, bus and airport hero cards
113
+
114
+ Hero cards have separate transport-specific APIs and visual identities, with shared display components underneath:
115
+
116
+ | Card | Identity | Departure fields | Default display |
117
+ | --- | --- | --- | --- |
118
+ | `RailStationHeroCard` | Station name, optional code and locality | Scheduled time, destination, platform, expected time/status, via/service note | UK rail matrix |
119
+ | `BusStopHeroCard` | Stop name, optional stop code and locality | Route, destination, due estimate, optional via | Bus dot matrix |
120
+ | `AirportHeroCard` | IATA code, airport name and city | Flight, time, destination/origin, gate, remarks, direction tabs | Split flap |
121
+
122
+ Import the new cards from `@motionstudies/web/components/RailStationHeroCard` or `@motionstudies/web/components/BusStopHeroCard`, plus `@motionstudies/web/transport-hero-cards.css` (which includes both board styles). Airport imports and study-window behavior remain as documented above.
123
+
124
+ ```tsx
125
+ <RailStationHeroCard
126
+ station={{ name: 'Bristol Temple Meads', code: 'BRI', locality: 'Bristol' }}
127
+ departures={[{
128
+ id: 'train-1', time: '17:15', destination: 'Portsmouth Harbour',
129
+ platform: '9', expected: '17:22', via: 'Eastleigh',
130
+ }]}
131
+ lineCount="auto"
132
+ boardHeight={400}
133
+ clockLabel="16:49:26"
134
+ footerLabel="Study timetable"
135
+ note="Synthetic timetable. Example times, not a live service."
136
+ />
137
+
138
+ <BusStopHeroCard
139
+ stop={{ name: 'Anchor Road', code: 'A1', locality: 'Bristol' }}
140
+ departures={[{ id: 'bus-1', route: '71', destination: 'City Centre', due: '2 min' }]}
141
+ lineCount={6}
142
+ note="Synthetic timetable. Example estimates, not a live service."
143
+ />
144
+ ```
145
+
146
+ Rail and bus consumers supply already ordered and formatted departures, including their own filtering, timezones and freshness. Missing times, platforms and statuses stay unknown rather than becoming “On time”. Both cards accept `presentation` (`'uk-rail'`, `'dot-matrix'`, `'split-flap'`), `lineCount`, `boardHeight` in pixels, `minRowHeight`, `loading`, `error`, `onRetry`, localized `labels`, and controlled `onSelectDeparture`/`selectedDepartureId`. A required `note` explains the source. The matrix fits its container; the split-flap alternative contains scrolling and places any service details in an Information column. Fixed line counts represent physical matrix lines; in split-flap mode they limit departure rows. The **Transport heroes** lab compares all three cards, switches the new cards' presentations, and exercises details, row fitting, updates, long names and failure states.
147
+
148
+ The rail card additionally accepts `presentation="sbb"`: a blue-and-white typographic departure board with service badges, scheduled time, destination/via information and prominent track numbers. This layout follows the information hierarchy in [SBB's general display guide](https://www.sbb.ch/en/travel-information/stations/services-station/station-customer-information/general-display-board.html). It uses ordinary text, including accented and non-Latin names. `RailDeparture.service` supplies a train label such as `IC 1`; optional `serviceCategory` (`'intercity'`, `'international'`, `'regional'`, `'suburban'`) selects the badge treatment. `platformSector` supplies a separate sector label when known. Expected times or disruption messages appear below the scheduled time; absence of a message does not manufacture an “On time” assertion.
149
+
150
+ For this layout, `lineCount` counts departures with their inline detail, and `"auto"` fits rows using a default target height of 64px. Dense fixed counts reduce type size; long values remain in the accessible text and hover titles. Labels stay consumer-owned, including the added `service` column label. The lab's **SBB departure board** option selects a synthetic Zürich HB example with German, French, Italian and English labels. Both new board styles are included in `transport-hero-cards.css`.
151
+
152
+ At compact widths the SBB layout stacks the service badge under the time, preserving destination space and the separate track column. Rail and bus hero padding follows the card width rather than the viewport. The lab includes a 240–980px width slider and Compact/Mobile/Panel/Wide presets, plus a 180–640px board-height control. The size regression suite covers seven card widths, four board heights, fixed and automatic line counts, long destinations, selection during updates, mobile viewports and loading/error states in Chromium and WebKit. Prefer `lineCount="auto"` for small panels; high fixed line counts deliberately trade text size for density.
153
+
154
+ ```tsx
155
+ <RailStationHeroCard
156
+ presentation="sbb"
157
+ station={{ name: 'Zürich HB' }}
158
+ labels={{ station: 'Bahnhof', departures: 'Abfahrt', service: 'Zug', time: 'Zeit', destination: 'Nach', platform: 'Gleis' }}
159
+ departures={[{ id: 'example-1', service: 'IC 1', serviceCategory: 'intercity',
160
+ time: '09:02', destination: 'Genève-Aéroport', via: 'Bern · Lausanne', platform: '32', platformSector: 'ABCD' }]}
161
+ lineCount="auto"
162
+ boardHeight={430}
163
+ note="Synthetic timetable · Example data."
164
+ />
165
+ ```
166
+
167
+ The shared board also accepts `loading`, a localized `loadingMessage`, and `loadingRows` (default five). While loading, its decorative rows cycle through staggered letters and digits; they are hidden from assistive technology and cannot be selected. A single status message announces loading. When data arrives, characters flip through a short sequence and settle into their actual values; later changes animate only the changed characters. These CSS animations have no JavaScript timers and stop looping when loading ends or the board is removed. Reduced-motion users get static blank loading flaps and immediate final text. `AirportHeroCard` uses this shared loading treatment automatically. Use **Reload board** in the Airports lab to preview the complete loading-to-ready transition.
168
+
169
+ Empty messages also appear on the flaps, in the widest column (the destination/origin column in airport cards), with the other columns blank. Longer localized messages wrap across display rows instead of being truncated. They settle with the same animation as flight details, and one hidden status announces the complete message to assistive technology. This also applies when the study clock moves into a window with no movements.
170
+
171
+ Rail and other transport consumers can share the same time filtering through `movementBoardWindow(study, horizon)` and `movementsForBoard(entries, window, maxRows)` from `@motionstudies/core/domain/movement-board`. Format the returned numeric times when mapping them into `SplitFlapBoard` cells. The lab's rail board follows the same study clock and horizon as its airport card.
172
+
173
+ `@motionstudies/data/air-endpoints` provides offline `enrichAirEndpoints` for existing air manifests, chunks and opening snapshots. Supply cached same-date global ADSB.lol heatmaps, an OurAirports CSV and the service date's local UTC offset. It associates only unambiguous low-altitude endpoints near a reference airport; cruise-only traces and uncertain routes stay unknown. Optional `AirEndpoint` origin/destination fields carry airport identity, observed boundary time and `observed-endpoint` evidence. `airportBoardMovements` maps full manifest entries to board rows without confusing playback chunk boundaries with flight endpoints. Input hashes and source/licence attribution are recorded in fixture metadata. These fields describe inferred observations, never flight schedules, gates or live status.
174
+
175
+ ## Vehicle hero cards
176
+
177
+ `VehicleHeroCard` shows one vehicle's destination, next stop and remaining calling points. Import it from `@motionstudies/web/components/VehicleHeroCard` with `@motionstudies/web/vehicle-hero-card.css`. The **Vehicle heroes** lab compares `uk-bus` (amber onboard display), `uk-rail` (dark rail display), `yellow-bus` (yellow next-stop panel) and `sbb` (blue next-stop panel with a red service badge). These are presentation studies, not official operator components.
178
+
179
+ ```tsx
180
+ <VehicleHeroCard
181
+ presentation="sbb"
182
+ vehicle={{ service: 'IC 1', operator: 'SBB CFF FFS', destination: 'Genève-Aéroport' }}
183
+ stops={[
184
+ { id: 'bern', name: 'Bern', time: '10:28', platform: '6' },
185
+ { id: 'fribourg', name: 'Fribourg/Freiburg', time: '10:56' },
186
+ ]}
187
+ note="Synthetic journey · Example calls and times."
188
+ onSelectStop={selectStation}
189
+ selectedStopId={selectedStationId}
190
+ />
191
+ ```
192
+
193
+ Consumers supply remaining `stops` in journey order and update them with playback, seeking or observations; the card has no independent clock. The first supplied call is the next stop. Optional `time`, `platform` and `detail` are consumer-formatted; absent values stay absent. `vehicle.destination` is optional and shows an explicit unavailable label when missing. The final supplied stop is never inferred to be the destination: set `isDestination` only when confirmed, especially when data is progressively chunked. Empty calls mean no upcoming stops are available, without asserting that the vehicle has arrived.
194
+
195
+ The required `note` explains provenance. Optional `status`, `statusTone`, `clockLabel`, localized `labels`, `loading`, `error` and `onRetry` follow the consumer's data; the component never manufactures an on-time status. Loading and errors hide the calling points. Stop selection is controlled through stable call IDs and does not alter playback or clear when a call leaves the list. All supplied calls are shown, with wrapping names and container-based compact layouts. The lab exercises advance/rewind, unknown destinations/times, localization, disruption, recovery and narrow widths. Edition adoption requires its own package upgrade and data adapter.
196
+
197
+ ## Optional live airport feed
198
+
199
+ `AirportBoard` from `@motionstudies/web/components/AirportBoard` adds Study/Now controls around an existing `AirportHeroCard` configuration. Pass `studyCard` with the usual card props and `live={{ baseUrl, edition, airport }}` for the shared service. Import `airport-hero-card.css`. `labels` localizes the wrapper's control and availability messages. The lower-level `useAirportFeed` hook and core `domain/live-airport` contract are also public exports.
200
+
201
+ Live timestamps are Unix seconds and use the airport's timezone for display, independently of recorded service time. The wrapper does not pass live flight IDs to the recorded scene's selection callback. The recorded card remains mounted while hidden; the edition still owns playback and can pause its study when appropriate. Only Now mode fetches flight boards; checking capabilities does not query the paid provider. Stale results carry their retrieval time and disappear when expired. Source data never falls back to synthetic or recorded flights under a live label.
202
+
203
+ See [service architecture and operations](../docs/LIVE-AIRPORTS.md). The Worker is deployed separately; npm publication and edition adoption remain explicit release steps.
204
+
205
+ ## Shared recorded air compilation
206
+
207
+ `@motionstudies/data/adsb-heatmap` consolidates the offline heatmap pipeline previously copied between editions. `ingestAdsbHeatmaps` reads cached gzip slices, decodes observations, filters transport-scale tracks, splits flights, and writes either an opening snapshot or an indexed day with overlapping chunks. Source hashes, chunk hashes and ODbL attribution accompany the output. It makes no network requests.
208
+
209
+ The same `decodeAdsbHeatmap` now powers `enrichAirEndpoints`; endpoint inference retains full coordinate precision, while playback compilation retains the existing five-decimal coordinates. `transportAirTracks` and `chunkAirSnapshot` are also available for consumers that assemble their own pipeline. All functions have public TypeScript declarations and work in the packed Node package.
210
+
211
+ Editions supply geographic bounds, service date, explicit UTC offset, optional timezone, input files and output paths. Flight IDs and chunk overlap retain the existing contracts. The default splits known callsign changes and gaps over 30 minutes. Set `splitTracks: false` only when reproducing a legacy opening snapshot with one ID per aircraft. See [adoption and compatibility](../docs/AIR-DATA.md).
212
+
213
+ ## Shared edition controllers and performance
214
+
215
+ `positionForTrain` now indexes chronological stop times with binary search and retains sequential behavior for unordered observations. Stop arrays are immutable: replace the array when a timetable changes. Arrival/departure boundaries, dwell, cancellation and backward seeking retain the existing contract.
216
+
217
+ `countableVehicleTrains(network, stations, selection)` and `createActiveTimetableVehicleCounter(trains, options)` from `@motionstudies/core/domain/vehicle-counts` separate station/route/category membership from clock updates. Build the selector and counter with `useMemo` when data or selection changes, then call the counter at the displayed time. It includes both interval endpoints and excludes cancellations and inverted intervals. Missing stations yield no matches. By default it counts timetable intervals even if a journey lacks enough stops to position; `{ requirePositionable: true }` excludes journeys with fewer than two stops. This distinction is explicit so an edition can retain its established metric.
218
+
219
+ The renderer now shares active GPU upload ranges, paused frame reuse, label and trail frame budgets, cached text comparators and batched hub lines. Custom layers can import the low-level helpers from `@motionstudies/three/render-performance`. Recreate frame trackers when their geometry/data/selection inputs change; `batchHubLines` takes ownership of two-vertex source line resources. Edition-specific worker transfer, picking and cartographic adapters remain consumer-owned.
220
+
221
+ `useJsonAsset<T>(url, enabled, parse?, optional?)` from `@motionstudies/web/use-json-asset` loads a single asset lazily and exposes `data`, `loading`, `error`, `unavailable`, and `retry`. Keep the parser stable and perform edition-specific schema/source compatibility checks there. Successful data remains cached while disabled; consumers decide whether to display it. Changing the URL or parser immediately discards prior-source state, and disabling/unmounting cancels requests. `retry()` discards cached state and requests again when enabled. Optional HTTP 404 responses are unavailable; other failures are errors. No source fallback or freshness policy is inferred.
222
+
223
+ `useTransitionValue(target, { durationMs, easing, steps })` from `@motionstudies/web/use-transition-value` animates a numeric value, returning `value` and `transitioning`. It reverses from the current frame, cancels on teardown, and settles immediately when reduced motion becomes active. `smoothTransition` is the default easing; `cosineTransition` and stepped progress support existing edition rhythms. Keep custom easing functions stable. Camera actions and lazy layout loading stay in the edition.
224
+
225
+ Edition chunk scripts can call `runNetworkChunkCli()` from `@motionstudies/data/network-chunk-cli`. It accepts the existing `--input`, `--manifest`, `--opening`, `--chunk-hours`, `--opening-start`, `--opening-end`, and `--focus` arguments. Source acquisition, provenance, output paths and command invocation remain edition-owned.
226
+
227
+ For timetable-backed vehicle selections, `NetworkVehicleHeroCard` from `@motionstudies/web/components/NetworkVehicleHeroCard` accepts `snapshot`, `train`, playback `time`, a required source `note` and the vehicle card's presentation/state/label options. Import `vehicle-hero-card.css`. It resolves the selected train ID against the current snapshot, retaining destination identity but showing no stale calls when that ID is absent. Calls stay in journey order, use stable journey/call IDs and follow backward seeking. During dwell the heading becomes `atStopLabel` (default “At stop”) and the time is the departure; otherwise it is the upcoming arrival. Times are formatted with `formatServiceTime` by default, without normalizing after midnight or adding delay twice. Use `showTimes={false}` for frequency-modelled journeys, and explain the model in `note`. The core `vehicleCalls` helper is also exported from `@motionstudies/core/domain/vehicle-calls` for custom adapters. Selection callback IDs refer to calls, not station indexes.
228
+
229
+ ### Railway preparation
230
+
231
+ `@motionstudies/data/rail-wtt`, `rail-journeys`, `rail-public-calls`, `rail-routing` and `rail-geometry` expose typed offline railway preparation. XLSX reading, dated source-column audits, UID/date joins, public-call anchors and connected OSM paths preserve source evidence. Editions supply regional identities, calendar exceptions and clipping policy. Node 24+ and `unzip` are required; no Python runtime is shipped. See `docs/SHARED-RAIL-READERS.md` in the source repository for calendar limits and parity evidence.
232
+
233
+ `mountMotionStudy({ id, theme }, application)` requires presentation identity only; a full `MotionStudyEdition` remains accepted. Applications own their data catalogue and loading lifecycle.
234
+
235
+ For independent airport infrastructure, `mapStyle.airports.visible` hides the mounted group without rebuilding GPU resources, and `showLabels` controls its labels separately. Both default to `true`. Set these from the edition's layout and label controls; airport abbreviations equal to their IATA code are rendered once.
236
+
237
+ ## Compression at rest in the source store
238
+
239
+ `capture` and `importCapture` accept `compression: 'gzip'`. The object is stored as `objects/<sha256>.gz` when gzip saves at least ten percent, otherwise raw; the record keeps the raw content hash and byte count as identity and adds `storedBytes` and `encoding`. `readCapture` and the new `readObject(store, hash, expectedBytes)` follow either form, verify the raw hash after expansion, and refuse output beyond the recorded size. `compactObjects(store, { minimumSaving })` compresses existing raw objects in place, verifying each before removing the raw file; records are not rewritten, since reads do not depend on them. Already-compressed sources such as ZIP archives stay raw. Use `storedBytes` for storage accounting and `bytes` for provenance.
240
+
241
+ ## Estimated fields, gridded series, field paths and daylight
242
+
243
+ These transport-neutral modules came from Zugunruhe's radar-field studies and serve any work that renders a continuous surface between scattered instruments, a gridded weather product, illustrative flow, or the sun's position: modelled electricity demand between substations, rain radar, model wind, or a terminator crossing a national field. They are pure functions with no dependencies. See [the shared-field record](../docs/SHARED-FIELDS.md) for provenance and adoption.
244
+
245
+ `@motionstudies/core/domain/supported-field` estimates values between stations. `fieldNeighbours` weights stations by a Gaussian kernel with a smooth taper to a finite reach; `estimateField` blends station samples and reports `support`, a fade from the nearest station that supplied a value, and `vectorSupport` for the nearest complete vector. All kilometre scales are `FieldSupportOptions`; `DEFAULT_FIELD_SUPPORT` retains Zugunruhe's 90 km scale, 240 km reach and 120–240 km support fade. Null station values are excluded rather than treated as zero; vector components blend as east/north components, never as bearings. `createFieldGrid` precomputes neighbours for a regular grid whose rows run south to north, `sampleFieldGrid` packs value, east, north and support per cell and level with NaN for unavailable channels, and `sampleFieldGridAt` reads it bilinearly, returning null beside any missing corner. The `movement` flag withholds cells without a complete vector and limits their support to the nearest vector, for path integration.
246
+
247
+ Render support as opacity or reach, not as confidence in the underlying measurement: it says how far the nearest evidence is, nothing about that evidence's accuracy. The kernel scale is a claim about resolution and belongs in the study's provenance.
248
+
249
+ `@motionstudies/core/domain/published-day` reads a published day of the national layer as the recording host compiles it: `openPublishedDay` takes a transport (`fetchTransport` over a base URL, or any pair of text and bytes readers) and returns the manifest and index up front, then slices, members and packs on demand and cached per file; `partFor` resolves an operator and vehicle to the pack part that holds it; `sliceNameAt` and `cellOf` reproduce the compiler's slice and cell rules exactly, so a position lands in the cell the compiler put it in; `positionAt` interpolates along a track only inside a tolerated gap, and `journeyAt` finds the run in force at an instant. Before a composition is built on a day, `checkDayManifest` reports any disagreement between the manifest's hours, slice count, file list and totals, and `reconcileSlice` reports any cell whose distinct-vehicle count differs from its members or that appears in only one of the two files; both return an empty list when consistent. A trimmed fixture fails the manifest check by design. Packs are gunzipped with the platform's `DecompressionStream` unless an inflater is supplied.
250
+
251
+ `@motionstudies/core/domain/gridded-series` reads a regular latitude/longitude grid of variables at listed instants. `bracketTime` finds the adjacent frames; `sampleGriddedSeries` interpolates bilinearly in space and linearly in time; `meanGriddedSeries` returns an area-weighted mean, with an optional valid range. A missing sample with any weight makes the reading unavailable instead of bridging the gap. Values keep the source's units; the consumer converts percentages or applies its own scale.
252
+
253
+ `@motionstudies/core/domain/field-paths` integrates illustrative paths through an estimated velocity field. `advanceFieldPath` takes an explicit midpoint step in metres per second, with `secondsPerStep` converting one unit of study time, and refuses to start from, pass through or land on unsupported field. `mixFieldMovement` blends two readings; `visibleTrailSegments` returns the last `trail` steps of a track at a study time with a fade at either end, identical when scrubbing back. Paths are neither observed trajectories nor individual movers and must be labelled as illustration.
254
+
255
+ `@motionstudies/core/domain/daylight` computes `solarPosition` (altitude and azimuth in degrees, azimuth clockwise from north) from the Astronomy Answers low-precision algorithm, matching SunCalc to a thousandth of a degree without a dependency. `daylightAt` adds a unit `direction` towards the sun in a scene frame with +x east, +y up and +z south, and smooth `twilight`, `warmth` and `daylight` envelopes from `DaylightEnvelopes` (defaults: twilight −18° to −1°, warmth rising −12° to −1° and falling 3° to 15°, daylight −1° to 12°). The envelopes are artistic responses to sun altitude and encode no weather or sky observation. Sample several longitudes to place a terminator across a national field.
256
+
257
+ The lab's **Fields** specimen renders a synthetic archipelago of seven instruments with a mid-study gap and one vectorless instrument, an invented cover series as haze, integrated trails, and a terminator crossing with the study clock. Brightness is the estimate and opacity is support; clicking reads the estimate, cover and sun altitude at a place.
258
+
259
+ ## Recorded power days
260
+
261
+ `@motionstudies/core/domain/power-day` exports `readPowerDay`, `powerPeriod`, `unitPower`, `plannedPower`, `sumPower` and `fuelMixAt`, plus their data types. A complete civil day declares its timezone, UTC bounds, half-hour intervals, MWh settlement quantities and MW plans/aggregates. Missing values remain null; signed quantities remain signed. Interval energy becomes average power only through the explicit interval duration. Declarations are interpolated only within one unambiguous segment; fuel samples expire after five minutes. Callers choose aggregate membership and receive a missing-contributor count. The reader validates source links, settlement run labels, identities, placement coordinates and safe evidence-artifact paths without fetching data. Source adapters, placement policy and the composition stay outside core. See [power ownership](../docs/POWER.md#ownership-and-handoff).
package/air-search.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AirEndpoint } from './domain/air.ts';
1
2
  export interface AirSearchTrack {
2
3
  readonly id: string;
3
4
  readonly icaoAddress?: string;
@@ -5,6 +6,8 @@ export interface AirSearchTrack {
5
6
  readonly start: number;
6
7
  readonly end: number;
7
8
  readonly airportIds?: readonly string[];
9
+ readonly origin?: AirEndpoint;
10
+ readonly destination?: AirEndpoint;
8
11
  }
9
12
  export declare function airTrackSearchText(track: AirSearchTrack): string;
10
13
  export declare function airTrackSearchValue(track: AirSearchTrack): string;
@@ -0,0 +1,48 @@
1
+ /** Counts are vehicle passages at a detector or a provider-defined link, not vehicle identities. */
2
+ export type AggregateRoadInterval = {
3
+ readonly kind: 'provider-slot';
4
+ readonly serviceDate: string;
5
+ readonly index: number;
6
+ readonly endingLabel: string;
7
+ } | {
8
+ readonly kind: 'utc';
9
+ readonly from: string;
10
+ readonly to: string;
11
+ };
12
+ export interface AggregateRoadSample {
13
+ readonly interval: AggregateRoadInterval;
14
+ readonly vehicleCount: number | null;
15
+ readonly averageSpeed: {
16
+ readonly value: number;
17
+ readonly unit: 'mph' | 'km/h';
18
+ } | null;
19
+ readonly sourceRecordIds: readonly string[];
20
+ }
21
+ export interface AggregateRoadSeries {
22
+ readonly id: string;
23
+ readonly provider: string;
24
+ readonly dataset: string;
25
+ readonly siteId: string;
26
+ readonly modelVersion?: string;
27
+ readonly samples: readonly AggregateRoadSample[];
28
+ }
29
+ /** Geometry association is independent of measurements; a candidate is not a verified link. */
30
+ export interface AggregateRoadSection {
31
+ readonly id: string;
32
+ readonly seriesId: string;
33
+ readonly path: readonly (readonly [longitude: number, latitude: number])[];
34
+ readonly association: {
35
+ readonly kind: 'illustrative';
36
+ readonly method: string;
37
+ readonly maximumDistanceMetres: number;
38
+ } | {
39
+ readonly kind: 'provider-link';
40
+ readonly linkId: string;
41
+ readonly modelVersion: string;
42
+ };
43
+ }
44
+ export declare function aggregateRoadValue(sample: AggregateRoadSample | undefined, metric: 'vehicleCount' | 'averageSpeed'): number | null;
45
+ /** Compile once per immutable series. Conflicting or duplicate slots remain unavailable.
46
+ * No interpolation, nearest-slot fallback or conversion between provider and UTC clocks.
47
+ */
48
+ export declare function indexAggregateRoadSlots(series: AggregateRoadSeries, serviceDate: string): ReadonlyMap<number, AggregateRoadSample>;
@@ -0,0 +1,22 @@
1
+ export function aggregateRoadValue(sample, metric) {
2
+ const value = metric === 'vehicleCount' ? sample?.vehicleCount : sample?.averageSpeed?.value;
3
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && (metric !== 'vehicleCount' || Number.isInteger(value)) ? value : null;
4
+ }
5
+ /** Compile once per immutable series. Conflicting or duplicate slots remain unavailable.
6
+ * No interpolation, nearest-slot fallback or conversion between provider and UTC clocks.
7
+ */
8
+ export function indexAggregateRoadSlots(series, serviceDate) {
9
+ const result = new Map(), conflicts = new Set();
10
+ for (const sample of series.samples) {
11
+ const interval = sample.interval;
12
+ if (interval.kind !== 'provider-slot' || interval.serviceDate !== serviceDate || !Number.isSafeInteger(interval.index) || interval.index < 0)
13
+ continue;
14
+ if (result.has(interval.index)) {
15
+ result.delete(interval.index);
16
+ conflicts.add(interval.index);
17
+ }
18
+ else if (!conflicts.has(interval.index))
19
+ result.set(interval.index, sample);
20
+ }
21
+ return result;
22
+ }
@@ -1,4 +1,4 @@
1
- import type { AirSnapshot, AirTrack } from './air.ts';
1
+ import type { AirEndpoint, AirSnapshot, AirTrack } from './air.ts';
2
2
  export interface AirDayAircraft {
3
3
  readonly id: string;
4
4
  readonly icaoAddress: string;
@@ -6,6 +6,8 @@ export interface AirDayAircraft {
6
6
  readonly start: number;
7
7
  readonly end: number;
8
8
  readonly airportIds?: readonly string[];
9
+ readonly origin?: AirEndpoint;
10
+ readonly destination?: AirEndpoint;
9
11
  readonly chunkIds: readonly string[];
10
12
  }
11
13
  export interface AirDayChunkDescriptor {
package/domain/air.d.ts CHANGED
@@ -5,6 +5,15 @@ export type AirSample = readonly [
5
5
  altitudeFeet: number,
6
6
  groundSpeedKnots: number
7
7
  ];
8
+ export interface AirEndpoint {
9
+ readonly icao: string;
10
+ readonly iata: string;
11
+ readonly name: string;
12
+ readonly city: string;
13
+ /** Study-local seconds at the observed approach/departure boundary; not a scheduled time. */
14
+ readonly time: number;
15
+ readonly evidence: 'observed-endpoint';
16
+ }
8
17
  export interface AirTrack {
9
18
  readonly id: string;
10
19
  readonly icaoAddress?: string;
@@ -12,6 +21,8 @@ export interface AirTrack {
12
21
  readonly start: number;
13
22
  readonly end: number;
14
23
  readonly airportIds?: readonly string[];
24
+ readonly origin?: AirEndpoint;
25
+ readonly destination?: AirEndpoint;
15
26
  readonly samples: readonly AirSample[];
16
27
  }
17
28
  export interface AirSnapshot {
@@ -1,4 +1,5 @@
1
1
  import type { AirTrack } from './air.ts';
2
+ import type { AirSearchTrack } from '../air-search.ts';
2
3
  export interface StudyAirport {
3
4
  readonly id: string;
4
5
  readonly name: string;
@@ -15,3 +16,18 @@ export declare function airportSearchText(airport: StudyAirport): string;
15
16
  export declare function searchAirports(airports: readonly StudyAirport[], searchQuery: string, limit?: number): readonly StudyAirport[];
16
17
  export declare function airTrackServesAirport(track: AirTrack, airport: StudyAirport): boolean;
17
18
  export declare function airportAirTrackIds(tracks: readonly AirTrack[], airport: StudyAirport): ReadonlySet<string>;
19
+ /** Board events come from full-flight endpoint evidence, not truncated playback chunks. */
20
+ export declare function airportBoardMovements(aircraft: readonly AirSearchTrack[], airport: StudyAirport): {
21
+ departures: {
22
+ id: string;
23
+ time: number;
24
+ service: string;
25
+ place?: string;
26
+ }[];
27
+ arrivals: {
28
+ id: string;
29
+ time: number;
30
+ service: string;
31
+ place?: string;
32
+ }[];
33
+ };
package/domain/airport.js CHANGED
@@ -39,3 +39,26 @@ export function airportAirTrackIds(tracks, airport) {
39
39
  .filter((track) => airTrackServesAirport(track, airport))
40
40
  .map((track) => track.id));
41
41
  }
42
+ /** Board events come from full-flight endpoint evidence, not truncated playback chunks. */
43
+ export function airportBoardMovements(aircraft, airport) {
44
+ const departures = [];
45
+ const arrivals = [];
46
+ const seen = new Set();
47
+ for (const track of aircraft) {
48
+ for (const direction of ['origin', 'destination']) {
49
+ const endpoint = track[direction];
50
+ if (!endpoint || endpoint.icao !== airport.icao || !Number.isFinite(endpoint.time))
51
+ continue;
52
+ const key = `${track.icaoAddress ?? track.id}:${direction}:${endpoint.time}`;
53
+ if (seen.has(key))
54
+ continue;
55
+ seen.add(key);
56
+ const other = direction === 'origin' ? track.destination : track.origin;
57
+ const row = { id: track.id, time: endpoint.time, service: track.callsign,
58
+ place: other ? `${other.city || other.name} ${other.iata || other.icao}` : undefined };
59
+ const rows = direction === 'origin' ? departures : arrivals;
60
+ rows.push(row);
61
+ }
62
+ }
63
+ return { departures, arrivals };
64
+ }
@@ -0,0 +1,32 @@
1
+ /** Sun position and smooth lighting envelopes for a place and instant. The position follows the
2
+ * low-precision solar algorithm published by Astronomy Answers (as popularised by SunCalc), good
3
+ * to a fraction of a degree: enough to light a scene and place a terminator, not for astronomy.
4
+ * The envelopes are artistic colour responses to sun altitude; they encode no weather or sky observation.
5
+ */
6
+ export interface SolarPosition {
7
+ /** Degrees above the horizon; negative below. */
8
+ readonly altitude: number;
9
+ /** Degrees clockwise from north. */
10
+ readonly azimuth: number;
11
+ }
12
+ /** Sun-altitude thresholds in degrees. Each envelope rises smoothly between its bounds; warmth also falls again between its last two. */
13
+ export interface DaylightEnvelopes {
14
+ readonly twilight: readonly [from: number, to: number];
15
+ readonly warmth: readonly [from: number, to: number, fallFrom: number, fallTo: number];
16
+ readonly daylight: readonly [from: number, to: number];
17
+ }
18
+ export declare const DEFAULT_DAYLIGHT_ENVELOPES: DaylightEnvelopes;
19
+ export interface Daylight extends SolarPosition {
20
+ /** Unit vector towards the sun in a scene frame with +x east, +y up and +z south. */
21
+ readonly direction: readonly [number, number, number];
22
+ /** 0 in full night, 1 once the sun nears the horizon. */
23
+ readonly twilight: number;
24
+ /** Peaks around sunrise and sunset, 0 at night and in full day. */
25
+ readonly warmth: number;
26
+ /** 0 below the horizon, 1 once the sun is well up. */
27
+ readonly daylight: number;
28
+ }
29
+ /** Sun altitude and azimuth for an instant, or null for an invalid instant or place. */
30
+ export declare function solarPosition(time: number | string | Date, latitude: number, longitude: number): SolarPosition | null;
31
+ /** Sun direction and lighting envelopes for a place and instant, or null for an invalid instant or place. */
32
+ export declare function daylightAt(time: number | string | Date, latitude: number, longitude: number, envelopes?: DaylightEnvelopes): Daylight | null;
@@ -0,0 +1,32 @@
1
+ export const DEFAULT_DAYLIGHT_ENVELOPES = { twilight: [-18, -1], warmth: [-12, -1, 3, 15], daylight: [-1, 12] };
2
+ const rad = Math.PI / 180, dayMs = 86_400_000, J1970 = 2440588, J2000 = 2451545, obliquity = rad * 23.4397;
3
+ const smooth = (a, b, value) => { const t = Math.max(0, Math.min(1, (value - a) / (b - a))); return t * t * (3 - 2 * t); };
4
+ const instant = (time) => typeof time === 'number' ? time : time instanceof Date ? time.getTime() : Date.parse(time);
5
+ /** Sun altitude and azimuth for an instant, or null for an invalid instant or place. */
6
+ export function solarPosition(time, latitude, longitude) {
7
+ const ms = instant(time);
8
+ if (!Number.isFinite(ms) || !Number.isFinite(latitude) || !Number.isFinite(longitude))
9
+ return null;
10
+ const days = ms / dayMs - .5 + J1970 - J2000, phi = rad * latitude;
11
+ const anomaly = rad * (357.5291 + .98560028 * days);
12
+ const eclipticLongitude = anomaly + rad * (1.9148 * Math.sin(anomaly) + .02 * Math.sin(2 * anomaly) + .0003 * Math.sin(3 * anomaly)) + rad * 102.9372 + Math.PI;
13
+ const declination = Math.asin(Math.sin(obliquity) * Math.sin(eclipticLongitude));
14
+ const rightAscension = Math.atan2(Math.sin(eclipticLongitude) * Math.cos(obliquity), Math.cos(eclipticLongitude));
15
+ const hourAngle = rad * (280.16 + 360.9856235 * days) + rad * longitude - rightAscension;
16
+ const altitude = Math.asin(Math.sin(phi) * Math.sin(declination) + Math.cos(phi) * Math.cos(declination) * Math.cos(hourAngle));
17
+ const fromSouth = Math.atan2(Math.sin(hourAngle), Math.cos(hourAngle) * Math.sin(phi) - Math.tan(declination) * Math.cos(phi));
18
+ return { altitude: altitude / rad, azimuth: ((fromSouth / rad + 180) % 360 + 360) % 360 };
19
+ }
20
+ /** Sun direction and lighting envelopes for a place and instant, or null for an invalid instant or place. */
21
+ export function daylightAt(time, latitude, longitude, envelopes = DEFAULT_DAYLIGHT_ENVELOPES) {
22
+ const position = solarPosition(time, latitude, longitude);
23
+ if (!position)
24
+ return null;
25
+ const altitude = position.altitude * rad, fromSouth = (position.azimuth - 180) * rad;
26
+ const [tw0, tw1] = envelopes.twilight, [w0, w1, w2, w3] = envelopes.warmth, [d0, d1] = envelopes.daylight;
27
+ return { ...position,
28
+ direction: [-Math.sin(fromSouth) * Math.cos(altitude), Math.sin(altitude), Math.cos(fromSouth) * Math.cos(altitude)],
29
+ twilight: smooth(tw0, tw1, position.altitude),
30
+ warmth: smooth(w0, w1, position.altitude) * (1 - smooth(w2, w3, position.altitude)),
31
+ daylight: smooth(d0, d1, position.altitude) };
32
+ }
@@ -0,0 +1,35 @@
1
+ /** Paths integrated through an estimated velocity field. They illustrate the field; they are not
2
+ * observed trajectories of anything. Integration refuses to start from, pass through or land on
3
+ * unsupported field, so a trail ends at a gap instead of crossing it.
4
+ */
5
+ export interface FieldPoint {
6
+ readonly latitude: number;
7
+ readonly longitude: number;
8
+ }
9
+ export interface FieldMovement {
10
+ readonly value: number;
11
+ readonly vector: readonly [east: number, north: number];
12
+ readonly support: number;
13
+ }
14
+ /** Reads the field at a place and study time; null or undefined where it is unavailable. */
15
+ export type FieldMovementSample = (point: FieldPoint, time: number) => FieldMovement | null | undefined;
16
+ export interface FieldTrack {
17
+ /** Study time of the first point. */
18
+ readonly start: number;
19
+ readonly level: number;
20
+ /** One point per unit step: latitude, longitude and any further channels to interpolate. */
21
+ readonly points: readonly (readonly number[])[];
22
+ }
23
+ export interface TrailSegment {
24
+ readonly a: readonly number[];
25
+ readonly b: readonly number[];
26
+ readonly tail: number;
27
+ readonly fade: number;
28
+ readonly level: number;
29
+ }
30
+ /** Linear blend of two readings. Either side unavailable makes the blend unavailable except at its exact ends. */
31
+ export declare function mixFieldMovement(a: FieldMovement | null | undefined, b: FieldMovement | null | undefined, fraction: number): FieldMovement | null;
32
+ /** Explicit midpoint step. Vectors are metres per second; `secondsPerStep` converts one unit of study time. */
33
+ export declare function advanceFieldPath(point: FieldPoint, time: number, step: number, sample: FieldMovementSample, secondsPerStep?: number): (FieldPoint & FieldMovement) | null;
34
+ /** The part of a track visible at a study time: the last `trail` steps, with a fade at either end of the track. Scrubbing back restores identical segments. */
35
+ export declare function visibleTrailSegments(track: FieldTrack, index: number, trail?: number): TrailSegment[];
@@ -0,0 +1,43 @@
1
+ const rad = Math.PI / 180, kmPerDegree = 6371.0088 * rad;
2
+ const smooth = (t) => { t = Math.max(0, Math.min(1, t)); return t * t * (3 - 2 * t); };
3
+ /** Linear blend of two readings. Either side unavailable makes the blend unavailable except at its exact ends. */
4
+ export function mixFieldMovement(a, b, fraction) {
5
+ if (fraction === 0)
6
+ return a ?? null;
7
+ if (fraction === 1)
8
+ return b ?? null;
9
+ if (!a || !b)
10
+ return null;
11
+ const mix = (x, y) => x * (1 - fraction) + y * fraction;
12
+ return { value: mix(a.value, b.value), vector: [mix(a.vector[0], b.vector[0]), mix(a.vector[1], b.vector[1])], support: mix(a.support, b.support) };
13
+ }
14
+ const displace = (p, v, seconds) => ({
15
+ latitude: p.latitude + v.vector[1] * seconds / 1000 / kmPerDegree,
16
+ longitude: p.longitude + v.vector[0] * seconds / 1000 / (kmPerDegree * Math.cos(p.latitude * rad)),
17
+ });
18
+ /** Explicit midpoint step. Vectors are metres per second; `secondsPerStep` converts one unit of study time. */
19
+ export function advanceFieldPath(point, time, step, sample, secondsPerStep = 300) {
20
+ const a = sample(point, time);
21
+ if (!a || a.support <= 0)
22
+ return null;
23
+ const mid = displace(point, a, step * secondsPerStep / 2), b = sample(mid, time + step / 2);
24
+ if (!b || b.support <= 0)
25
+ return null;
26
+ const next = displace(point, b, step * secondsPerStep), value = sample(next, time + step);
27
+ return value && value.support > 0 ? { ...next, ...value } : null;
28
+ }
29
+ /** The part of a track visible at a study time: the last `trail` steps, with a fade at either end of the track. Scrubbing back restores identical segments. */
30
+ export function visibleTrailSegments(track, index, trail = 15) {
31
+ const end = track.start + track.points.length - 1;
32
+ if (index <= track.start || index >= end)
33
+ return [];
34
+ const fade = smooth((index - track.start) / 2) * smooth((end - index) / 3), segments = [];
35
+ for (let i = Math.max(0, Math.floor(index - trail - track.start)); i < track.points.length - 1; i++) {
36
+ const t = track.start + i, a = Math.max(t, index - trail), b = Math.min(t + 1, index);
37
+ if (b <= a)
38
+ continue;
39
+ const p = track.points[i], q = track.points[i + 1], at = (f) => p.map((v, k) => v * (1 - f) + q[k] * f);
40
+ segments.push({ a: at(a - t), b: at(b - t), tail: Math.max(0, 1 - (index - (a + b) / 2) / trail), fade, level: track.level });
41
+ }
42
+ return segments;
43
+ }