diff --git a/CHANGELOG.md b/CHANGELOG.md index 93a1c8f..ccf8d81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 4.4.0 + +### Minor Changes + +- cd5f46c: Add optional Grid Walk initialPosition: 'start-line' to align the actual start/finish line near the right or top scene edge. Preserve selected-entry centering by default. Measure framing in local canvas coordinates through host loading-scale transitions and refresh late overlay measurements so first interaction does not change a stale camera frame. + + Break browser startup into cancellation-aware tasks during procedural generation and track drawing, preserve automatic Grid Walk, and render one complete initial frame. Keep synchronous generation/restart APIs and deterministic geometry unchanged. + +### Patch Changes + +- ff900fd: Preserve configured drivers across environment participant resets and browser restarts, and keep active state intact when replacement simulation creation fails. Make composable controllers available to ready callbacks, share reentrant startup calls, and stop obsolete restart rendering after callback teardown. Record near-line and exact floating-point sector/lap crossings, carry rounded telemetry times across minute boundaries, and render accepted CSS driver colors consistently on the canvas. + ## 4.3.2 ### Patch Changes diff --git a/INSTALL_AND_UPDATE.md b/INSTALL_AND_UPDATE.md index 46170b8..2ed008e 100644 --- a/INSTALL_AND_UPDATE.md +++ b/INSTALL_AND_UPDATE.md @@ -116,12 +116,19 @@ npm run check Install a specific version when the host needs a controlled upgrade: ```bash -npm install @inventure71/paddockjs@4.3.0 +npm install @inventure71/paddockjs@4.4.0 npm run check ``` After updating, smoke-test the page that mounts the simulator. Browser behavior changes should be checked in the consuming host, because host CSS, container size, and route handling are outside the package. +### 4.4.0 Migration Notes + +- No breaking host migration is required from `4.3.x`. Rebuild the host bundle to receive the startup and lifecycle fixes. +- Browser startup now yields during track generation and drawing while preserving automatic Grid Walk, cancellation and ready callbacks. Local measurements show shorter blocking tasks with a modest increase in elapsed initialization time; see [Browser Startup Responsiveness](docs/browser_startup.md). +- Set `gridWalk: { enabled: true, initialPosition: 'start-line' }` to place the actual start/finish line near the safe right edge in wide hosts or top edge in tall hosts. The default `'selected'` retains initial-entry centering. Grid Walk also keeps its camera framing stable through host loading-scale transitions and late overlay resizing. +- Participant resets/restarts retain configured drivers, ready callbacks can operate the published controller, and timing/color rendering includes reliability fixes. Existing public import paths and synchronous generation/restart APIs are preserved. + ### 4.3.0 Migration Notes - Existing browser and composable mounts retain Race as their default view. Enable Grid Walk with `gridWalk: { enabled: true, initialView: 'grid-walk' }`. Choose `ui: { viewControls: 'toggle' }` for the green Start race / red Stop race button; the default is the two-button switch. See [Grid Walk](docs/grid_walk.md) for host metadata, external controls, camera sizing and paused-progress behavior. diff --git a/README.md b/README.md index 4af7337..99eb3e1 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,8 @@ npm run demo:smoke Pass `gridWalk: { enabled: true }` to either mounting API to explore the starting grid before racing. Supply entry `presentation` metadata for full names, summaries and ordinary links in the same bottom project banner used by Race. The arrow selector sits centered at the top, with centered entry text; Grid Walk adds no separate project details panel. +Add `gridWalk: { enabled: true, initialPosition: 'start-line' }` to start with the start/finish line near the right edge in a wide host or the top edge in a tall host. The default `'selected'` centers the initially selected entry. + Its package-styled Grid Walk / Race switch lives outside the scene: mount `simulator.mountViewControls(viewControlsRoot)` before `start()` alongside a composable `mountRaceCanvas()`, or use the equivalent `mountViewControls(viewControlsRoot, simulator)` helper. The all-in-one shell and race telemetry drawer include these controls above the scene automatically. Choose `ui: { viewControls: 'toggle' }` for one green **Start race** / red **Stop race** button instead of the default two-button switch. Stop pauses the race and returns to its original display grid; Start resumes saved progress. The main demo demonstrates this single-button option. `setView('grid-walk' | 'race')` switches presentation without resetting progress; the same grid camera rotates for actual component dimensions and supports drag, touch and wheel browsing. Browser-native scrolling drives that camera and hands scrolling to the host page at the grid's ends. Race wheel zoom uses continuous scroll distance, yields at its limits and preserves native page touch gestures. Neither mode registers a canceling wheel listener or locks body/document scrolling; Ctrl/Meta wheel retains browser zoom. This avoids the nonpassive wheel-listener path implicated in macOS Gecko scroll freezes; it does not patch the browser itself. Grid Walk reuses race controls and panels, with varied preparation crews and a continuous flow of visitors entering and leaving beyond the camera bounds. Existing consumers retain Race defaults. See [Grid Walk](docs/grid_walk.md) for the API, lifecycle and example, or open `/guide/grid-walk.html` on the website. The main demo also starts with Grid Walk. diff --git a/docs/architecture.md b/docs/architecture.md index eacdf6f..894b9b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,7 +1,13 @@ # Architecture +## Cooperative browser startup + +`src/app/runtime/browserSimulationStartup.js` prewarms immutable geometry cooperatively before invoking the existing simulation factory. `startupTasks.js` owns time budgeting, real task yields and cancellation checks. `src/rendering/track/trackRenderSteps.js` drains shared synchronous/asynchronous drawing generators; kerb/border safety loops expose bounded work checkpoints. Partial scene objects remain owned by the stopped Pixi stage throughout startup. Grid Walk sync can prepare layout without rendering; its scene/input availability becomes active immediately before the single complete initial render. See [Browser startup responsiveness](browser_startup.md). + ## Grid Walk presentation boundary +Grid Walk measures chrome in the canvas's local CSS coordinate space, normalizing shared host scaling before calculating camera frames. The layout owner observes overlay size changes and cancels pending layout work on destruction. Initial start-line positioning uses the track's actual zero-distance point; after pan/focus the camera retains its longitudinal world position. + `src/app/gridWalk/` owns optional Grid Walk presentation. `GridWalkController` composes the lifecycle and scene without owning UI action handlers. `GridWalkSession` captures assigned display poses and transition state without changing or stepping the race. `GridWalkCamera` retains one longitudinal world position and a fixed grid axis; `GridWalkNavigation` normalizes pointer and keyboard input into that single camera action; shared native-scroll controls own wheel browsing. `GridWalkControls` owns in-scene entry-selector actions, `GridWalkLabels` owns measured, collision-free label lanes and focus restoration, `GridWalkProjectBanner` composes the shared race banner template/presenter and enabled/muted policy, and `GridWalkLayout` measures chrome/safe scene bounds and restores covered Race UI. Camera framing and label visibility use the same path after selection and manual browsing. Car taps select on release; staging snaps display headings while Race retains smoothing. `GridWalkCrew` creates varied per-car mechanic groups and visitor geometry once, animates transforms with cosmetic randomness independent of the race, and maintains continuous coverage with irregular visitor spacing, varied lateral paths and bounded individual pace/sway, and extends paths beyond the full permitted camera envelope by filling only new offscreen coverage without repositioning existing visitors. `src/ui/gridWalkTemplate.js` composes the semantic surfaces; `src/data/entryPresentation.js` normalizes host metadata/URLs. Runtime visibility, ticker, resize and cleanup paths remain shared. Race, physics and environment modules do not depend on Grid Walk. `src/ui/viewControlsTemplate.js` and `src/app/controls/SimulatorViewControls.js` own the external Grid Walk / Race component, its startup availability and synchronized active state. `ui.viewControls` selects either the default two-button switch or the single Start race / Stop race action, including on restart; both variants delegate to the same view lifecycle. The composable controller exposes `mountViewControls()`; shell and telemetry-drawer templates compose it above their scenes. A standalone race canvas owns no mode-switch markup. The shared scroll controller directs native scrolling to the Grid Walk camera while active and to Race zoom otherwise. Native boundaries hand scrolling to the host page, and browser modifier zoom remains native. See [Grid Walk](grid_walk.md). @@ -120,6 +126,10 @@ training script The environment runtime consumes per-step events directly from the simulation during `frameSkip` and builds the full public snapshot once for the returned result. This keeps `reset()` / `step()` semantics unchanged while avoiding repeated full car, wheel, penalty, and track serialization inside one environment action. +Resolved environment options retain an internal `configuredDrivers` roster separately from the participating `drivers` used to create a simulation. Reset merging uses the full roster unless the caller replaces `drivers`, allowing previously excluded drivers to participate again. The runtime creates a replacement simulation before committing its options; browser expert hosts likewise defer visual option/driver updates until simulation creation succeeds. Public snapshots, observations, and specs do not expose the internal roster. + +Composable startup records its pending promise before initialization can invoke host code. After full renderer/control/ticker setup, an internal initialization hook publishes the running app before ready callbacks. Cancellation during earlier initialization still prevents publication and late ready delivery. + Browser expert mode reuses the same environment runtime around the visual app's existing `RaceSimulation` instance. When `expert.enabled` is true, the visual ticker does not advance simulation time automatically; `simulator.expert.reset()` and `simulator.expert.step(actions)` are the only simulation-advance entry points. ## Shared Data and Presentation Rules diff --git a/docs/browser_startup.md b/docs/browser_startup.md new file mode 100644 index 0000000..e50838d --- /dev/null +++ b/docs/browser_startup.md @@ -0,0 +1,28 @@ +# Browser startup responsiveness + +Browser mounting prepares track geometry and draws the scene cooperatively. Automatic Grid Walk starts without a host interaction. Public mount/start promises, ready callbacks, synchronous restart and `createProceduralTrack()` contracts are unchanged. + +## Task boundaries and ownership + +`src/app/runtime/startupTasks.js` supplies cancellation-aware checkpoints with an 8 ms work budget and real timer-task yields. Microtasks alone cannot release the main thread for input or painting. Track generation yields between candidate construction and validation, and before publishing immutable cached geometry. The existing simulation factory retains ownership of warmup, RNG and mutable race state. Synchronous and asynchronous generation share candidate order, mathematics and cache behavior. + +`ProceduralTrackAsset.renderAsync()` consumes the same drawing steps as synchronous rendering. Kerb and border safety queries yield within expensive loops. Every partially built Graphics object is attached to the owned scene before a pause, so destruction releases it. The scene remains non-renderable, its ticker stopped, and its Grid Walk controls inert until construction finishes. Startup renders one complete initial frame before clearing loading state and delivering ready callbacks. Cancellation is checked at task resumptions and before publishing the prepared simulation; a disposed startup cannot restore resources or deliver ready. + +## Measured portfolio workload + +Measured on 2026-11-12 using an isolated copy of the portfolio Projects page and its real automatic loader, seven F1 entries, simulation seed 71 and track seed 7110. The browser used Apple M4 Pro hardware through ANGLE Metal, viewport 1280×800, DPR 2, with no CPU throttling. Each variant used three fresh page navigations. Diagnostic builds recorded function spans, Long Tasks API entries and an 8 ms timer heartbeat; asynchronous span durations include time yielded to the browser. Baseline and candidate runs were grouped rather than alternated, so these are local ranges, not a general device guarantee. + +| Metric | Before | After | +| --- | ---: | ---: | +| Longest startup main-thread task | 597–627 ms | 62–71 ms | +| Longest heartbeat interval | 607–634 ms | 78–86 ms | +| Worst scheduled navbar-handler delay | 598–625 ms | 64–76 ms | +| Initialization until ready | 918–978 ms | 1243–1372 ms | + +The baseline spent 224–240 ms in simulation preparation and 537–555 ms drawing the track, predominantly borders (407–418 ms) and kerbs (124–130 ms). Individual geometry candidates took roughly 30–54 ms. Texture loading included asynchronous waits; the candidate first render took 47–50 ms. Initial DOM readouts took about 2 ms, so deferring unused UI was not justified. Cooperative scheduling increases elapsed startup time by roughly 0.3–0.4 seconds while substantially reducing individual stalls. No worker or texture-preparation rewrite was needed for this measured workload. GPU initialization and individual geometry candidates can still exceed the 8 ms scheduling budget because checkpoints cannot preempt an atomic operation. + +A separate real navbar click at 768×900 occurred while both initialization and track drawing were pending. The unrelated navbar expanded before startup completed; its First Input entry reported 1.3 ms processing delay and 8 ms duration. This real input measurement is separate from the scheduled-handler comparison above. Baseline and candidate initial simulation snapshots had identical SHA-256 hashes for the fixed workload. + +## Regression verification + +`startupTasks.test.js`, `runtimeStartup.test.js`, `proceduralTrackAsync.test.js` and `proceduralTrackAsset.test.js` cover real task turns, sync/async parity, cancellation before cache commit and during scene construction, destruction at promise completion, partial resource cleanup and retry. Grid Walk browser smoke covers automatic startup, loading-scale transitions, late overlay resizing, both start-line orientations, input and remounting. Run the package release gate and runtime benchmark for changes to these paths. Repeat host profiling with the real stylesheet/loader, a fixed workload and recorded renderer metadata; distinguish elapsed preparation from blocking task duration. diff --git a/docs/data_contract.md b/docs/data_contract.md index 6b19058..0bcda26 100644 --- a/docs/data_contract.md +++ b/docs/data_contract.md @@ -2,7 +2,9 @@ This file documents the data that host websites pass into PaddockJS. -`gridWalk?: { enabled?: boolean, initialView?: 'grid-walk' | 'race', ambientMotion?: boolean }` enables [Grid Walk](grid_walk.md). Defaults are disabled, Grid Walk initial view when enabled, and ambient motion enabled. `SimulatorDriver` and `ChampionshipEntryBlueprint` accept `presentation?: EntryPresentation` with optional `name`, `summary`, `technologies: string[]`, `details: string[]`, `image: { src, alt? }`, `href` and `linkLabel`. Matching entry metadata overrides driver metadata. Full driver names, legacy `raceData` and `link` are compatible fallbacks. URLs are normalized and text is escaped; Grid Walk links are anchors independent of `onDriverOpen`. Its shared race banner displays name/summary/link content only; technologies, details and image remain accepted metadata but are not rendered in an extra inspector. +`gridWalk.initialPosition?: 'selected' | 'start-line'` chooses initial camera positioning. The default `'selected'` centers the initial entry; `'start-line'` aligns the actual start/finish line 24 px inside the safe right/top edge according to composition. Invalid values use `'selected'`. Initial line alignment adapts to layout until pan/focus input; subsequent layout changes retain the browsing world position. Restart preserves or replaces the option through the normal partial merge. + +`gridWalk?: { enabled?: boolean, initialView?: 'grid-walk' | 'race', initialPosition?: 'selected' | 'start-line', ambientMotion?: boolean }` enables [Grid Walk](grid_walk.md). Defaults are disabled, Grid Walk initial view when enabled, and ambient motion enabled. `SimulatorDriver` and `ChampionshipEntryBlueprint` accept `presentation?: EntryPresentation` with optional `name`, `summary`, `technologies: string[]`, `details: string[]`, `image: { src, alt? }`, `href` and `linkLabel`. Matching entry metadata overrides driver metadata. Full driver names, legacy `raceData` and `link` are compatible fallbacks. URLs are normalized and text is escaped; Grid Walk links are anchors independent of `onDriverOpen`. Its shared race banner displays name/summary/link content only; technologies, details and image remain accepted metadata but are not rendered in an extra inspector. Grid Walk mode controls are a separate presentation surface: `simulator.mountViewControls(controlsRoot)` or `mountViewControls(controlsRoot, simulator)`. Mount it before `start()` alongside a standalone race canvas; the all-in-one shell and race telemetry drawer compose it automatically above the scene. Its buttons share the controller's `getView()` / `setView()` state, stay disabled during startup and hide when Grid Walk is disabled. `ui.viewControls: 'switch' | 'toggle'` chooses the default two-button switch or a single Start race / Stop race action. Stop pauses exact race progress and shows the original starting grid using display poses; Start resumes saved progress. Both variants use the same mounting API, including after restart. No host-specific routing is required. @@ -138,6 +140,8 @@ result = env.step({ ``` `controlledDrivers` is required. It supports one or many externally controlled cars. Non-controlled participants use the built-in driver AI in the stable 1.0 environment API. + +Participant filtering does not discard the configured driver roster, including across browser Restart. Partial resets can switch between `controlled-only`, `all`, and explicit participant lists, or change `controlledDrivers`, without resupplying excluded drivers. An explicit `drivers` array replaces that roster. If option validation or simulation creation fails during reset, the active configuration, simulation, and episode remain usable; browser expert resets follow the same rule. `externalRenderer` is optional and observer-only. It can be a function or `{ onFrame(frame) }`, and receives `{ snapshot, observation, meta }` on `reset`, `step`, and `resetDrivers`. The hook does not mutate simulation state and hook failures are isolated so stepping continues. `warmup` is optional and enabled by default. It primes a disposable runtime during load/reset creation and caches by configuration fingerprint so repeated identical resets skip warmup. Use `warmup: { enabled, policy: 'config-change' | 'always' | 'never', steps }` or `warmup: false` to disable. `physicsMode` is optional and accepts `'arcade'` or `'advanced'`. Invalid values, including the removed old `'simulator'` name, fall back to `'arcade'`, which is the default compatibility mode. `'advanced'` keeps the same public action contract but uses four-contact force and yaw-inertia dynamics and exposes additional telemetry fields on snapshots and observations: `velocityX`, `velocityY`, `lateralG`, `longitudinalG`, `gripUsage`, `slipAngleRadians`, `tractionLimited`, and `stabilityState`. In advanced mode, `slipAngleRadians` is derived from the car heading versus actual velocity direction, and each wheel contributes forces from its own surface and normal load; wheel snapshots retain their existing contact-patch shape. `gripUsage` is the maximum requested combined force divided by adhesion over the four contacts; it can exceed one. `tractionLimited` flags this demand threshold, while `stabilityState` distinguishes front/rear demand imbalance and large body slip. Acceleration telemetry is the velocity change over the caller step, projected into the body axes at the start of that step, in m/s²; G divides it by 9.80665. Tire slip at a contact is internal and must not be substituted for the public body `slipAngleRadians`. Terminal and race-control-held advanced-mode cars publish `velocityX: 0` and `velocityY: 0` whenever scalar `speed` is zero, so training loops do not see stale pre-DNF, pre-grid, pre-red-flag, or pre-queue motion. Arcade snapshots publish `velocityX` and `velocityY` as `null`; consumers that need a heading-aligned arcade velocity should derive it from `heading` and `speed`. The rebuilt advanced model intentionally changes trajectories and grip-response distributions; controllers/checkpoints trained on the previous advanced dynamics need reevaluation or retraining. Action shapes and observation schema remain unchanged. @@ -798,6 +802,8 @@ Fields: - `customFields`: optional driver overview fields. Use an object or an array of `{ label, value }`. - `driverModel`: optional opaque host metadata. PaddockJS preserves the value on normalized driver data and internal car state for host/controller bookkeeping, but does not interpret it or include it in model observations. +Driver colors accept hexadecimal, named, RGB/RGBA, and HSL/HSLA CSS colors. Canvas car and replay tints use the corresponding RGB channels, matching the color identity used by the DOM readouts; sprite opacity remains controlled separately. Context-dependent colors such as `currentcolor` cannot resolve against a canvas element and use the renderer's white fallback. + ## Entry Shape Entries are optional. If omitted, defaults are used. @@ -878,10 +884,12 @@ onDriverOpen(driver) { } ``` -The callback receives the normalized driver object. If the host wants modals, routing, analytics, or external tabs, it should implement that inside this callback. `onDriverOpen` is host-owned navigation code and should handle its own failures; unlike lifecycle callbacks, it is not routed through `onError`. +The callback receives the normalized driver object. If the host wants modals, routing, analytics, or external tabs, it should implement that inside this callback. Exceptions from `onDriverOpen` are isolated from the simulator loop and routed to `onError(error, { callback: 'onDriverOpen' })` when supplied. Optional lifecycle callbacks: +The composable controller is available inside `onLoadingChange({ loading: false, phase: 'ready' })` and `onReady`: getters, expert operations, selection, and runtime controls operate on the ready app. Readiness notifications run after renderer and ticker setup. A ready callback may restart or destroy the runtime; early loading callbacks still cannot restart pending initialization. Reentrant `start()` calls share the pending operation. + ```js { onLoadingChange({ loading, phase }) {}, diff --git a/docs/grid_walk.md b/docs/grid_walk.md index 17f18ea..8024a28 100644 --- a/docs/grid_walk.md +++ b/docs/grid_walk.md @@ -34,6 +34,7 @@ A standalone race canvas does not insert a mode switch. Composable hosts must mo ## Lifecycle and state - `gridWalk.enabled` defaults to `false`. When enabled, `initialView` defaults to `'grid-walk'`; use `'race'` to begin playback with Grid Walk available afterward. `ambientMotion` defaults to `true`. +- `gridWalk.initialPosition` defaults to `'selected'`, centering the initially selected entry. Use `'start-line'` to place the actual start/finish line 24 px inside the safe right edge in horizontal composition or the top edge in vertical composition. Initial line alignment follows layout/orientation changes until pan or explicit focus input; subsequent browsing retains its world position. Restart reapplies the configured initial position. Unknown values use `'selected'`. - `getView()` returns `'grid-walk'` or `'race'`. `setView(view)` returns `true` for an accepted change and `false` for an unchanged/invalid view, disabled Grid Walk, or a composable controller that has not started. View changes do not call `restart()`. - Before the first departure from Grid Walk, the simulation clock and lights are held. Choosing Race clears the crew over 650 ms of visible activity, then starts the existing deterministic lights sequence. With reduced motion or `ambientMotion: false`, clearing is immediate. Returning during clearing cancels the transition. - Returning after playback has begun pauses the exact live race and shows its original starting grid using display poses only. Race resumes saved time, laps, order, tires, pit state, selected entry and fractional fixed-step remainder. The simulation object, RNG, entries and track are not recreated or changed by browsing or resizing. Project banner selection/open state survives a mode switch. @@ -55,6 +56,8 @@ The measured canvas host's width and height choose composition, independent of v The camera measures the wrapping top controls and shared bottom banner to reserve a safe scene area. It keeps a stable scale for that area and a single world position along the original grid axis. Selecting an on-screen car changes the project without resetting the camera, zoom or other labels. Previous/next and the native selector bring offscreen entries into view; Home explicitly recenters the selected entry. Resizing, rotation and mode switches preserve the browsing position. +Measurements use local canvas CSS coordinates even when a host scales its wrapper during loading/reveal. Header/banner size changes are observed, including late font metrics, so the next interaction does not discover stale startup framing. + Drag the canvas or an entry label with a mouse or touch to move along the grid. All camera input uses the same axis: horizontal composition accepts left/right dragging and arrow keys, vertical composition accepts up/down. Diagonal drags and scroll cannot move across that axis. A vertical wheel travels front to rear in both compositions; horizontal trackpad input is accepted only in horizontal composition. Browsing is bounded near the grid. Browser-native overflow handles wheel gestures, with passive `scroll` events moving the same camera and native page handoff at the grid's ends. A sticky viewport keeps the canvas and its labels in place while scroll coordinates change; scrolling never moves the simulator DOM through its content. Selection, drag, keyboard and resize changes synchronize those coordinates without issuing another camera command. Race zoom is inactive while Grid Walk owns the scene. Race also uses browser-native scrolling: each 100 CSS pixels changes zoom by one 1.4-unit zoom step, continuously, in every camera mode. Reaching either zoom limit hands scrolling to the containing page. Ctrl/Meta keyboard modifiers temporarily release the internal scroll surface, and browser wheel/pinch zoom remains native. Passive touch lifecycle listeners release the surface for native page swipes in Race; active Grid Walk retains direct touch dragging. Neither mode registers a canceling wheel listener or changes body/document overflow. Scrolling outside the canvas keeps normal host behavior, and modified keyboard navigation such as Ctrl/Cmd+Home keeps its browser behavior. A drag starting on a car or label does not select it; a click or tap does, including a gesture that moves only in the forbidden direction. diff --git a/docs/rules.md b/docs/rules.md index 89ddb02..05d6e00 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -230,6 +230,8 @@ Lap is computed from each car's cumulative race distance over the track length. Hidden timing-line crossings use exact forward `(previousDistance, currentDistance]` boundaries and the same representable line distance for indexing and recording. A car infinitesimally before a line must still record that crossing; no tolerance band may silently drop a lap timestamp. +Sector and lap telemetry follows the same forward boundary rule, including very small positive steps and exact arrival at a line on later laps. Timing and sector position share the same representable line distance; lap lines remain exact multiples of track length. A crossing is recorded once; remaining on or moving onward from that line does not record it again. Displayed lap and sector times round to milliseconds before splitting minutes and seconds, so rounding across a minute produces `2:00.000` rather than `1:60.000`. + Each track is automatically divided into three equal sectors. Sector and lap telemetry is recorded when a car's cumulative race distance crosses a sector boundary or start/finish boundary. Completed current-lap sector split times before the active sector are exposed as `currentSectors`, while `liveSectors` keeps only the active sector's elapsed time updated before the boundary is crossed and clears any future-sector values. `sectorProgress` is recomputed every snapshot as the live S1/S2/S3 fill state for the current lap, so sector-map UI does not derive progress from completed split state or keep stale future sectors lit. Timing values are stored in seconds and exposed on each car snapshot as `lapTelemetry`. Each car is marked `finished` when it reaches `track.length * totalLaps`. It receives a frozen provisional `finishRank`, exposes `raceStatus: 'waved-flag'` / `wavedFlag: true`, and emits a `car-finish` event. The first finisher becomes provisional `winner`, but the race keeps running until every race participant has either crossed the finish distance or is currently DNF. While the field is still finishing, timing order keeps already-finished cars in provisional finish order ahead of cars still running, and DNF cars sit below active cars in the order they retired. A car that has already crossed the finish line keeps that result even if it later touches the barrier or satisfies stalled-off-track detection while the rest of the field is still finishing; post-finish retirement checks do not turn it into DNF. A DNF car restored before final classification re-enters the live order and must finish before the race can complete; restoring it after final classification does not reopen the race. diff --git a/docs/system_specs.md b/docs/system_specs.md index 344bdd3..7432847 100644 --- a/docs/system_specs.md +++ b/docs/system_specs.md @@ -4,6 +4,8 @@ PaddockJS mounts an interactive F1-style race simulator into a host webpage. The package owns the simulator UI, PixiJS renderer, bundled simulator assets, simulation core, default demo data, and public mount API. +Grid Walk accepts `initialPosition: 'selected' | 'start-line'` (default `'selected'`). The optional start-line preset aligns the actual line near the safe right/top edge until pan/focus input takes ownership. Its layout measurements stay in local canvas coordinates through host scale transitions; late overlay resizing refreshes framing before interaction. + The host website owns only: - The root DOM element where the simulator mounts. @@ -20,6 +22,8 @@ Grid Walk releases drag capture on window blur, document hiding and a pointer mo Native scrolling avoids the nonpassive wheel-listener path implicated in macOS Gecko bugs [2072785](https://bugzilla.mozilla.org/show_bug.cgi?id=2072785) and [2072786](https://bugzilla.mozilla.org/show_bug.cgi?id=2072786), where a queued event can be dropped before reaching content and stall scrolling across tabs. This package mitigation does not patch or establish a verified fix for Gecko's shared APZ queue. No browser preference is changed; the reported native Zen trackpad freeze has not yet been captured in a diagnostic trace. +Browser startup yields between procedural track candidates and within expensive kerb/border drawing work. Automatic Grid Walk and ready ordering are preserved; the scene stays non-renderable and controls unavailable until the first complete frame. Cancellation releases partial resources and prevents late ready delivery. Public synchronous generation and restart remain synchronous. See [Browser startup responsiveness](browser_startup.md) for measurements and elapsed-time tradeoffs. + ## Public API Main import: @@ -288,7 +292,8 @@ Returned controller: - Composable mounting can embed the timing tower directly inside the race canvas with `mountRaceCanvas(root, { includeTimingTower: true })`. - The race canvas is required before `start()` because PixiJS needs a canvas host. - Mount component roots before calling `start()`. A pre-start `restart(nextOptions)` re-resolves options and refreshes already mounted component markup, so non-asset changes such as title, kicker, UI visibility, theme, drivers, entries, seed, or track seed are reflected before `start()` binds the runtime. -- `restart()` during pending composable startup is rejected before options or mounted DOM change. Await `start()` (or its rejection) before restarting. +- `restart()` during pending composable initialization is rejected before options or mounted DOM change. The controller becomes operational before the ready loading notification and `onReady`, so those callbacks may use runtime controls or restart. Reentrant `start()` calls during earlier loading share the same initialization. +- Restart validates expert configuration and constructs the replacement simulation before releasing the current race or expert adapter. Invalid simulation options or a replacement roster missing a controlled expert driver leave the active runtime usable for a corrected retry. If snapshot callbacks destroy or restart during a successful restart, obsolete rendering work stops immediately. - Each composable surface key owns one root. Replacing that surface clears its previous root, and different surface keys cannot share one root. Concurrent `start()` calls await one initialization; failure destroys partial state and leaves the controller retryable. - Destroying a composable controller during `start()` cancels that start promise. Pending renderer resources are released once initialization settles, and late assets cannot repopulate the unmounted scene or emit ready callbacks. After the cancelled promise settles, hosts may remount components and start again. Cleanup failures are reported through `onError(error, { phase: 'destroy' })` without abandoning independent cleanup or masking an earlier initialization error. - Hosts that constrain a standalone telemetry stack should give its root a definite height; the stack then owns internal scrolling. A maximum height alone does not resolve the child's percentage height and can allow content to overflow neighboring host surfaces. @@ -331,7 +336,7 @@ Returned controller: - `physicsMode` accepts `'arcade'` and `'advanced'`. The default is `'arcade'` to preserve existing hosts. `'advanced'` is opt-in and keeps cars controlled only through steering, throttle, brake, and pit intent while enabling four-contact tire forces, load transfer, yaw inertia, aerodynamic load/drag, velocity-heading slip, and advanced telemetry. The old `'simulator'` mode name is removed and falls back to `'arcade'` like any other invalid value. Snapshots expose `physicsMode` plus per-car `lateralG`, `longitudinalG`, `gripUsage`, `slipAngleRadians`, `tractionLimited`, `stabilityState`, and the latest `appliedControls`. - `restart(nextOptions)` can change race data and deterministic seeds such as `trackSeed`, but it does not support changing asset URLs. Asset changes require `destroy()` and a fresh mount because PixiJS texture loading is an initialization boundary. - `onDriverOpen(driver)` is the navigation boundary. -- Lifecycle callbacks are optional: `onLoadingChange`, `onReady`, `onError`, `onDriverSelect`, `onRaceEvent`, `onLapChange`, and `onRaceFinish`. Normal ticker frames and expert-driven frames use the same lifecycle emitter. Stable event identifiers distinguish separate same-time events, while duplicate delivery of the same event is suppressed. Lifecycle callback failures are routed to `onError` when possible and must not stop the simulator loop. `onDriverOpen(driver)` is host-owned navigation code and is not wrapped as a lifecycle callback. +- Lifecycle callbacks are optional: `onLoadingChange`, `onReady`, `onError`, `onDriverSelect`, `onRaceEvent`, `onLapChange`, and `onRaceFinish`. Normal ticker frames and expert-driven frames use the same lifecycle emitter. Stable event identifiers distinguish separate same-time events, while duplicate delivery of the same event is suppressed. Lifecycle callback failures are routed to `onError` when possible and must not stop the simulator loop. `onDriverOpen(driver)` remains host-owned navigation code; its exceptions use the same `onError` isolation contract. - Race completion is part of the simulation snapshot. Cars receive individual `finished`, `finishTime`, `finishRank`, `status: 'waved-flag'`, `raceStatus: 'waved-flag'`, `wavedFlag`, `penaltySeconds`, `adjustedFinishTime`, and `classifiedRank` values as they cross the finish distance. Destroyed/out-of-race cars expose `dnf`, `dnfReason`, `dnfAt`, and `dnfOrder`, appear below active cars in timing, render faded/gray in the race canvas, and do not block race completion while they remain DNF. The first finisher sets a provisional `raceControl.winner`; already-finished cars remain frozen in provisional finish order while the remaining cars complete the distance. Final `raceControl.classification` and `raceControl.finished` are set only after every race participant has finished or is DNF. DNF entries are included after finishers with no finish time. A DNF car restored before final classification re-enters live timing and must finish; after final classification, resurrection does not reopen the race. Final classification converts unserved drive-through and stop-go penalties into configured time, sorts finishers by `finishTime + penaltySeconds`, applies position-drop and disqualification consequences, then race control switches to `safety-car`, the final order freezes to the classified result, and the field keeps circulating under safety-car behavior. Timing presentation continues to show final winner/finished labels from `raceControl.finished` rather than reverting to safety-car labels. - Race rules support package presets and custom module config. Supported rulesets are `paddock`, `grandPrix2025`, `fia2025`, and `custom`. Active advanced modules include pit stops, tire strategy, tire degradation, stalled off-track DNF, and penalties. Weather, reliability, and fuel load are reserved module placeholders only; they do not currently change grip, power, retirement risk, mass, or pace. The current simulator normalizes all module config, creates/renders track-owned pit-lane geometry on tracks whose resolved generation options enable it, treats pit-lane asphalt, working-lane service areas, and garage boxes as legal drivable surfaces, runs automatic bounded pit-train entry/service/exit through the main fast lane and shared team service areas when pit stops are enabled, lets host/expert pit calls choose a target tire compound, uses the team queue point as a rolling gate when the service area is free, queues a second team car behind the active service area and moves it forward through a queue-release route only after the active service area is physically clear, keeps pit-route approach speed bounded until the final queue/service capture instead of crawling through open route, optionally varies pit-service time from team pit-crew stats with a perfect-training override, supports pit-lane open/closed state plus red flags, requests pit stops from configurable tire-energy thresholds, applies nonlinear tire-grip degradation down to 1% unless `rules.modules.tireDegradation.enabled` is `false`, can retire cars that remain off legal racing/pit surfaces below the configured stalled-DNF speed threshold for the configured duration when `rules.modules.stalledDnf.enabled` is `true`, applies the pit speed limiter only on the main pit lane/working lane, enforces pit-lane speeding on speed-limited pit-lane parts but not on entry/exit connectors, keeps the safety car about `55m` ahead of the leader with compact `22m` frozen-order queue slots, lets the built-in driver AI ride kerbs, attack, defend, and recover through normal steering/throttle/brake decisions with short controller-state commitments for rejoin and attack decisions, and enforces stewarded penalties for collisions, track limits, pit-lane speeding, and tire requirements. `tireStrategy` does not enable automatic pit stops; `pitStops.enabled` is required for pit routing and non-clear pit intent requests. - Penalty subsections use `strictness` from `0` to `1`, not only boolean enablement. `strictness: 0` means the subsection is not enforced; `strictness: 1` applies the configured rule margin. Steward decisions are exposed as `penalty` events and as top-level `snapshot.penalties`. Penalty entries include normalized consequences and lifecycle status. Immediate consequences apply time, grid, position, or disqualification effects directly; drive-through and stop-go consequences remain issued until served, cancelled, or converted at final classification. diff --git a/docs/testing-reliability-guide.md b/docs/testing-reliability-guide.md index b8a6468..ced9892 100644 --- a/docs/testing-reliability-guide.md +++ b/docs/testing-reliability-guide.md @@ -28,6 +28,8 @@ Use the smallest verification layer that proves the behavior, then run the broad | Browser runtime, Pixi lifecycle, layout support, readouts, controls, theme, loading, or smoke pages | Focused DOM/render helper tests where possible | `npm run check`; full browser smoke for broad layout/showcase changes | | Docs-only consumer guidance | `npm run docs:check` | `npm run check` when docs describe package behavior changed in code | +Browser startup changes also require real task-turn and cancellation tests, sync/async geometry/drawing parity, and a host-page responsiveness measurement with the real automatic loader and stylesheet. Include an unrelated input control during pending initialization, report longest blocking tasks separately from total ready time, and identify viewport, DPR and GPU renderer. See [Browser startup responsiveness](browser_startup.md). + ## Test Quality Rules - Test behavior through the production path whenever practical. Avoid tests that recreate private helper logic and only prove the helper still matches itself. diff --git a/package-lock.json b/package-lock.json index b518334..249f302 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@inventure71/paddockjs", - "version": "4.3.2", + "version": "4.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@inventure71/paddockjs", - "version": "4.3.2", + "version": "4.4.0", "license": "Apache-2.0", "dependencies": { "pixi.js": "8.20.1" diff --git a/package.json b/package.json index 7d65861..23f3d0d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@inventure71/paddockjs", - "version": "4.3.2", + "version": "4.4.0", "type": "module", "description": "A data-driven browser F1 simulator component for host websites.", "license": "Apache-2.0", diff --git a/site/guide/api.html b/site/guide/api.html index 1f32099..2cf6d3a 100644 --- a/site/guide/api.html +++ b/site/guide/api.html @@ -58,28 +58,28 @@

Select driver

Race control

- - - - - + + + + +

Pit strategy

- - + +

Penalty methods

- - - + + +
diff --git a/site/package-lock.json b/site/package-lock.json index 0a50251..ce255bd 100644 --- a/site/package-lock.json +++ b/site/package-lock.json @@ -15,7 +15,7 @@ }, "..": { "name": "@inventure71/paddockjs", - "version": "4.3.2", + "version": "4.4.0", "license": "Apache-2.0", "dependencies": { "pixi.js": "8.20.1" diff --git a/site/src/shared/routes.js b/site/src/shared/routes.js index 84a3723..69e5127 100644 --- a/site/src/shared/routes.js +++ b/site/src/shared/routes.js @@ -157,6 +157,13 @@ export const REFERENCE_DOCUMENTS = [ path: '/reference/composable-layouts.html', group: 'Start and integrate', }, + { + id: 'browser-startup', + source: 'docs/browser_startup.md', + title: 'Browser startup responsiveness', + path: '/reference/browser-startup.html', + group: 'Contributor notes', + }, { id: 'concepts', source: 'docs/concepts.md', diff --git a/site/src/showcase/main.js b/site/src/showcase/main.js index eb41e05..2948a51 100644 --- a/site/src/showcase/main.js +++ b/site/src/showcase/main.js @@ -1120,6 +1120,7 @@ async function mountApiPage() { wireDriverButtons(); wireActions(); renderApiSnapshot(controller); + document.querySelectorAll('[data-action]').forEach((button) => { button.disabled = false; }); window.setInterval(() => renderApiSnapshot(controller), 1000); } diff --git a/site/src/showcase/styles.css b/site/src/showcase/styles.css index dec2668..3e702f0 100644 --- a/site/src/showcase/styles.css +++ b/site/src/showcase/styles.css @@ -691,6 +691,7 @@ code { } .piece-shell--sector-banner > .piece-mount { + --preview-placeholder-min-height: 170px; position: relative; min-height: 170px; overflow: hidden; diff --git a/smoke/browser-smoke.mjs b/smoke/browser-smoke.mjs index b903b22..325b77f 100644 --- a/smoke/browser-smoke.mjs +++ b/smoke/browser-smoke.mjs @@ -53,6 +53,10 @@ function delay(ms) { async function assertCanvasRendered(page, label) { const canvas = page.locator('[data-track-canvas] canvas').first(); await canvas.waitFor({ state: 'visible', timeout: 15000 }); + // A loading overlay can look like painted canvas pixels in a screenshot. + // Require the package's first-frame readiness before inspecting the image. + await page.waitForFunction(() => document.querySelector('[data-track-canvas] canvas') + ?.closest('[data-paddock-component="race-canvas"]')?.classList.contains('is-loaded'), null, { timeout: 15000 }); const box = await canvas.evaluate((node) => { const rect = node.getBoundingClientRect(); return { @@ -2078,7 +2082,7 @@ async function smokeApi(page, baseUrl) { } async function clickApiAction(page, action) { - await clickLocatorElement(page.locator(`[data-action="${action}"]`)); + await page.locator(`[data-action="${action}"]`).click(); } async function smokePolicyRunner(page, baseUrl) { diff --git a/smoke/gridWalkSmoke.mjs b/smoke/gridWalkSmoke.mjs index 7f5e33b..6a685f3 100644 --- a/smoke/gridWalkSmoke.mjs +++ b/smoke/gridWalkSmoke.mjs @@ -1,6 +1,76 @@ import assert from 'node:assert/strict'; import { assertPageScrollOutsideSimulator } from './pageScroll.mjs'; +async function assertInitialFraming(page) { + const readFrame = () => page.evaluate(() => { + const app = window.gridWalkShowcase.app; + const { frame } = app.gridWalk; + return { x: frame.x, y: frame.y, scale: frame.scale, position: frame.position }; + }); + const assertSameFrame = (before, after, label) => { + assert.ok(Math.abs(before.scale - after.scale) < 0.00001, `${label}: scale changed`); + for (const axis of ['x', 'y', 'position']) assert.ok(Math.abs(before[axis] - after[axis]) < 0.05, `${label}: ${axis} changed`); + }; + + // The portfolio reveals its ready mount from scale(.985). That screen-space + // transition must never become a change to the local Pixi camera. + await page.evaluate(() => { + document.getElementById('grid-host').style.transform = 'scale(0.985)'; + window.gridWalkShowcase.restart(); + }); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + const loadingFrame = await readFrame(); + await page.evaluate(() => document.getElementById('grid-host').style.removeProperty('transform')); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + await page.locator('[data-grid-entry][aria-pressed="true"]').click(); + assertSameFrame(loadingFrame, await readFrame(), 'First selection after host reveal'); + + // Late font/layout metrics are measured before another user interaction. + await page.locator('[data-grid-heading]').evaluate((heading) => { heading.style.fontSize = '90px'; }); + try { + await page.waitForFunction(() => { + const app = window.gridWalkShowcase.app; + const bannerHeight = app.gridWalk.banner.element.getBoundingClientRect().height; + return Math.abs(app.gridWalk.frame.area.bottom - (app.canvasHost.clientHeight - 40 - bannerHeight)) < 0.1; + }); + const settled = await readFrame(); + await page.locator('[data-grid-entry][aria-pressed="true"]').click(); + assertSameFrame(settled, await readFrame(), 'First selection after late layout'); + } finally { + await page.locator('[data-grid-heading]').evaluate((heading) => heading.style.removeProperty('font-size')); + } +} + +async function assertStartLinePosition(page) { + for (const [width, height, orientation] of [[1120, 620, 'horizontal'], [390, 760, 'vertical']]) { + await page.evaluate(({ width, height }) => { + const host = document.getElementById('grid-host'); + host.style.width = `${width}px`; + host.style.height = `${height}px`; + window.gridWalkShowcase.restart({ gridWalk: { initialPosition: 'start-line' } }); + }, { width, height }); + await page.waitForFunction((orientation) => { + const { gridWalk, worldLayer } = window.gridWalkShowcase.app; + if (gridWalk.orientation !== orientation) return false; + const line = worldLayer.toGlobal(gridWalk.camera.startLine); + return Math.abs(orientation === 'horizontal' + ? line.x - (gridWalk.frame.area.right - 24) + : line.y - (gridWalk.frame.area.top + 24)) < 0.1; + }, orientation); + await assertLayout(page); + await page.locator('canvas').first().focus(); + const before = await page.evaluate(() => window.gridWalkShowcase.app.gridWalk.camera.position); + await page.keyboard.press(orientation === 'horizontal' ? 'ArrowLeft' : 'ArrowDown'); + await page.waitForFunction((before) => window.gridWalkShowcase.app.gridWalk.camera.position !== before, before); + } + await page.evaluate(() => { + const host = document.getElementById('grid-host'); + host.style.width = '1120px'; + host.style.height = '620px'; + window.gridWalkShowcase.restart({ gridWalk: { initialPosition: 'selected' } }); + }); +} + async function assertLayout(page) { // Container ResizeObserver and its scheduled layout pass settle on frames. await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); @@ -135,6 +205,8 @@ export async function smokeGridWalk(page, baseUrl) { await page.setViewportSize({ width: 1280, height: 1050 }); await page.goto(`${baseUrl}/guide/grid-walk.html`); await page.waitForFunction(() => window.gridWalkShowcase?.getSnapshot()); + await assertInitialFraming(page); + await assertStartLinePosition(page); await assertInterruptedDrag(page); const initial = await page.evaluate(() => JSON.stringify(window.gridWalkShowcase.getSnapshot())); await page.waitForTimeout(250); diff --git a/src/__tests__/carRenderer.test.js b/src/__tests__/carRenderer.test.js index 0a84a47..98ed8ce 100644 --- a/src/__tests__/carRenderer.test.js +++ b/src/__tests__/carRenderer.test.js @@ -1,8 +1,27 @@ import { describe, expect, test, vi } from 'vitest'; import { Container, Texture } from 'pixi.js'; import { CarRenderer } from '../app/rendering/carRenderer.js'; +import { buildChampionshipDriverGrid } from '../data/championship.js'; describe('car renderer', () => { + test.each(['#0000ff', '#00f', 'blue', 'rgb(0, 0, 255)', 'rgb(0 0 255)', 'hsl(240, 100%, 50%)'])( + 'renders accepted driver color %s consistently at creation and during playback', (color) => { + const drivers = buildChampionshipDriverGrid([{ id: 'entry', name: 'Entry', color }], []); + const renderer = new CarRenderer({ carSprites: new Map(), carHitAreas: new Map(), serviceCountdownLabels: new Map() }); + const layer = new Container(); + const textures = { car: Texture.WHITE }; + try { + renderer.createCars({ drivers, textures, carLayer: layer }); + expect(renderer.carSprites.get('entry').tint).toBe(0x0000ff); + renderer.renderCars({ cars: [{ ...drivers[0], x: 20, y: 30, heading: 0 }], + raceControl: { mode: 'green' }, safetyCar: { deployed: false } }, { textures, carLayer: layer }); + expect(renderer.carSprites.get('entry').tint).toBe(0x0000ff); + } finally { + layer.destroy({ children: true }); + } + }, + ); + test('staging snaps to the original pose while ordinary racing keeps heading smoothing', () => { const renderer = new CarRenderer({ carSprites: new Map(), carHitAreas: new Map(), serviceCountdownLabels: new Map() }); const layer = new Container(); diff --git a/src/__tests__/environmentBrowserReset.test.js b/src/__tests__/environmentBrowserReset.test.js new file mode 100644 index 0000000..e2070ac --- /dev/null +++ b/src/__tests__/environmentBrowserReset.test.js @@ -0,0 +1,117 @@ +import { describe, expect, test, vi } from 'vitest'; +import { createBrowserExpertAdapter } from '../app/BrowserExpertAdapter.js'; +import { F1SimulatorApp } from '../app/F1SimulatorApp.js'; +import { resolveEnvironmentOptions } from '../environment/options.js'; +import { createRaceSimulation } from '../simulation/raceSimulation.js'; +import { TRACK } from '../simulation/trackModel.js'; + +function createBrowserHost() { + const options = resolveEnvironmentOptions({ + drivers: [ + { id: 'alpha', name: 'Alpha', color: '#ff0000' }, + { id: 'bravo', name: 'Bravo', color: '#0000ff' }, + ], + entries: [], + controlledDrivers: ['alpha'], + seed: 71, + trackSeed: 2097, + track: TRACK, + warmup: false, + ui: { raceDataBanners: {} }, + assets: { trackTextures: {} }, + sensors: { rays: { enabled: false }, nearbyCars: { enabled: false } }, + }); + return { + options, + drivers: options.drivers, + driverById: new Map(options.drivers.map((driver) => [driver.id, driver])), + sim: createRaceSimulation(options), + root: { style: { setProperty: vi.fn() } }, + applyExpertOptions: F1SimulatorApp.prototype.applyExpertOptions, + createRaceSimulation: vi.fn(createRaceSimulation), + createCars: vi.fn(), + renderTrack: vi.fn(), + renderExpertFrame: vi.fn(), + }; +} + +describe('browser environment resets', () => { + test('recreating the browser adapter preserves excluded drivers and honors a replacement roster', () => { + const app = createBrowserHost(); + let expert = createBrowserExpertAdapter(app, { controlledDrivers: ['alpha'] }); + try { + expert.reset({ scenario: { participants: 'controlled-only' } }); + expert.destroy(); + expert = createBrowserExpertAdapter(app, { controlledDrivers: ['alpha'] }); + expect(expert.reset({ scenario: { participants: 'all' } }).state.snapshot.cars.map((car) => car.id)) + .toEqual(['alpha', 'bravo']); + + expert.destroy(); + app.applyExpertOptions({ drivers: [app.drivers[0]] }); + expert = createBrowserExpertAdapter(app, { controlledDrivers: ['alpha'] }); + expect(expert.reset({ scenario: { participants: 'all' } }).state.snapshot.cars.map((car) => car.id)) + .toEqual(['alpha']); + expect(() => expert.reset({ controlledDrivers: ['bravo'] })).toThrow('controlled driver does not exist: bravo'); + } finally { + expert.destroy(); + } + }); + + test('failed simulation creation keeps the host configuration and visible simulation intact', () => { + const app = createBrowserHost(); + const expert = createBrowserExpertAdapter(app, { controlledDrivers: ['alpha'] }); + const previousOptions = app.options; + const previousDrivers = app.drivers; + const previousDriverById = app.driverById; + const previousSimulation = app.sim; + try { + expect(() => expert.reset({ + controlledDrivers: ['bravo'], + scenario: { participants: 'controlled-only' }, + track: null, + trackGeneration: { profile: 'invalid-reset-profile' }, + })).toThrow('Unsupported procedural track profile: invalid-reset-profile'); + + expect(app.options).toBe(previousOptions); + expect(app.drivers).toBe(previousDrivers); + expect(app.driverById).toBe(previousDriverById); + expect(app.sim).toBe(previousSimulation); + expect(app.createCars).not.toHaveBeenCalled(); + expect(app.renderTrack).not.toHaveBeenCalled(); + expect(app.renderExpertFrame).not.toHaveBeenCalled(); + expect(expert.getActionSpec().controlledDrivers).toEqual(['alpha']); + expect(expert.reset().state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + } finally { + expert.destroy(); + } + }); + + test('successful participant resets synchronize the host, simulation, specs, and rendered observations', () => { + const app = createBrowserHost(); + const expert = createBrowserExpertAdapter(app, { controlledDrivers: ['alpha'] }); + try { + expert.reset({ scenario: { participants: 'controlled-only' } }); + expect(app.drivers.map((driver) => driver.id)).toEqual(['alpha']); + + const switched = expert.reset({ controlledDrivers: ['bravo'] }); + expect(app.options.controlledDrivers).toEqual(['bravo']); + expect(app.drivers.map((driver) => driver.id)).toEqual(['bravo']); + expect(app.sim.cars.map((car) => car.id)).toEqual(['bravo']); + expect(expert.getActionSpec().controlledDrivers).toEqual(['bravo']); + expect(Object.keys(switched.observation)).toEqual(['bravo']); + expect(app.renderExpertFrame).toHaveBeenLastCalledWith( + switched.state.snapshot, + { forceDomUpdate: true, observation: switched.observation }, + ); + + const restored = expert.reset({ scenario: { participants: 'all' } }); + expect(app.options.drivers).toBe(app.drivers); + expect(app.drivers.map((driver) => driver.id)).toEqual(['alpha', 'bravo']); + expect(app.sim.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + expect(restored.state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + expect([...app.driverById.keys()]).toEqual(['alpha', 'bravo']); + } finally { + expert.destroy(); + } + }); +}); diff --git a/src/__tests__/environmentParticipants.test.js b/src/__tests__/environmentParticipants.test.js index f22997c..85e1984 100644 --- a/src/__tests__/environmentParticipants.test.js +++ b/src/__tests__/environmentParticipants.test.js @@ -1,5 +1,7 @@ import { describe, expect, test } from 'vitest'; import { resolveEnvironmentOptions } from '../environment/options.js'; +import { createPaddockEnvironment } from '../environment/index.js'; +import { TRACK } from '../simulation/trackModel.js'; const drivers = [ { id: 'alpha', name: 'Alpha', color: '#ff0000' }, @@ -35,3 +37,97 @@ describe('environment participant membership', () => { .toThrow('PaddockJS environment controlled driver must be included in scenario participants: alpha'); }); }); + +describe('environment participant resets', () => { + function createEnvironment(participants = 'all') { + return createPaddockEnvironment({ + ...options, + track: TRACK, + warmup: false, + scenario: { participants }, + sensors: { rays: { enabled: false }, nearbyCars: { enabled: false } }, + }); + } + + test.each(['all', 'controlled-only'])('restores the full configured roster after %s participation', (participants) => { + const env = createEnvironment(participants); + try { + if (participants === 'all') env.reset({ scenario: { participants: 'controlled-only' } }); + expect(env.getState().snapshot.cars.map((car) => car.id)).toEqual(['alpha']); + + const restored = env.reset({ scenario: { participants: 'all' } }); + expect(restored.state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + expect(Object.keys(restored.observation)).toEqual(['alpha']); + expect(restored.state.snapshot).not.toHaveProperty('configuredDrivers'); + expect(env.getActionSpec()).not.toHaveProperty('configuredDrivers'); + expect(env.getObservationSpec()).not.toHaveProperty('configuredDrivers'); + } finally { + env.destroy(); + } + }); + + test('can include an excluded driver through an explicit participant list', () => { + const env = createEnvironment(['alpha']); + try { + const restored = env.reset({ scenario: { participants: ['bravo', 'alpha'] } }); + expect(restored.state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + } finally { + env.destroy(); + } + }); + + test('can control an excluded configured driver without resupplying the roster', () => { + const env = createEnvironment('controlled-only'); + try { + const switched = env.reset({ controlledDrivers: ['bravo'] }); + expect(switched.state.snapshot.cars.map((car) => car.id)).toEqual(['bravo']); + expect(Object.keys(switched.observation)).toEqual(['bravo']); + expect(env.getActionSpec().controlledDrivers).toEqual(['bravo']); + + const restored = env.reset({ scenario: { participants: 'all' } }); + expect(restored.state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + expect(Object.keys(restored.observation)).toEqual(['bravo']); + } finally { + env.destroy(); + } + }); + + test('an explicit driver roster replaces retained participants', () => { + const env = createEnvironment('controlled-only'); + try { + const replaced = env.reset({ + drivers: [drivers[0], { id: 'charlie', name: 'Charlie', color: '#00ff00' }], + scenario: { participants: 'all' }, + }); + expect(replaced.state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'charlie']); + + env.reset({ scenario: { participants: 'controlled-only' } }); + const restored = env.reset({ scenario: { participants: 'all' } }); + expect(restored.state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'charlie']); + expect(() => env.reset({ controlledDrivers: ['bravo'] })).toThrow('controlled driver does not exist: bravo'); + } finally { + env.destroy(); + } + }); + + test('a failed simulation reset preserves the active configuration and episode', () => { + const env = createEnvironment(); + const action = { alpha: { steering: 0, throttle: 0, brake: 0 } }; + try { + const before = env.step(action); + expect(() => env.reset({ + controlledDrivers: ['bravo'], + track: null, + trackGeneration: { profile: 'invalid-reset-profile' }, + })).toThrow('Unsupported procedural track profile: invalid-reset-profile'); + + expect(env.getActionSpec().controlledDrivers).toEqual(['alpha']); + expect(env.getObservation()).toBe(before.observation); + expect(env.getState()).toEqual(before.state); + expect(env.step(action).info.step).toBe(before.info.step + 1); + expect(env.reset().state.snapshot.cars.map((car) => car.id)).toEqual(['alpha', 'bravo']); + } finally { + env.destroy(); + } + }); +}); diff --git a/src/__tests__/gridWalk.test.js b/src/__tests__/gridWalk.test.js index aa77715..db16a8a 100644 --- a/src/__tests__/gridWalk.test.js +++ b/src/__tests__/gridWalk.test.js @@ -137,6 +137,29 @@ describe('Grid Walk presentation lifecycle', () => { }); describe('Grid Walk camera contract', () => { + test('initial Race view hides staging crew even when startup defers rendering', () => { + const world = new Container(); + const controller = Object.create(GridWalkController.prototype); + controller.session = { active: false, clearing: false, view: 'race', snapshot: { cars: [{ id: 'a', x: 0, y: 0, heading: 0 }] } }; + controller.app = { selectedId: 'a', runtimeSceneReady: false, options: { ui: {} }, + driverById: new Map([['a', {}]]), isRaceDataBannerEnabled: () => false, syncTimingPanelDisclosureState() {} }; + controller.crew = new GridWalkCrew(world, controller.session.snapshot.cars); + Object.assign(controller, { navigation: { sync() {} }, panel: { dataset: {} }, element: { dataset: {} }, + controls: { update() {} }, sceneLabels: {}, viewControls: { update() {} }, labelGroup: {}, + banner: { update() {} }, syncLayout() {} }); + try { + controller.sync({ updateTicker: false, render: false }); + controller.app.runtimeSceneReady = true; + controller.sync({ updateTicker: false, render: false }); + expect(controller.crew.container.visible).toBe(false); + expect(controller.tick(100)).toBe(false); + expect(controller.crew.container.visible).toBe(false); + } finally { + controller.crew.destroy(); + world.destroy(); + } + }); + test('uses actual aspect ratio with hysteresis around square dimensions', () => { expect(gridWalkOrientation(1100, 620)).toBe('horizontal'); expect(gridWalkOrientation(390, 760)).toBe('vertical'); @@ -239,7 +262,7 @@ describe('Grid Walk public inputs', () => { expect(resolveF1SimulatorOptions({ drivers }).gridWalk.enabled).toBe(false); const options = resolveF1SimulatorOptions({ drivers, gridWalk: { enabled: true } }); expect(options.gridWalk.initialView).toBe('grid-walk'); - expect(mergeRestartOptions(options, { gridWalk: { ambientMotion: false } }).gridWalk).toEqual({ enabled: true, initialView: 'grid-walk', ambientMotion: false }); + expect(mergeRestartOptions(options, { gridWalk: { ambientMotion: false } }).gridWalk).toEqual({ enabled: true, initialView: 'grid-walk', initialPosition: 'selected', ambientMotion: false }); expect(() => resolveF1SimulatorOptions({ drivers, gridWalk: { enabled: true }, expert: { enabled: true } })).toThrow('expert'); }); diff --git a/src/__tests__/gridWalkInitialPosition.test.js b/src/__tests__/gridWalkInitialPosition.test.js new file mode 100644 index 0000000..c6dee1b --- /dev/null +++ b/src/__tests__/gridWalkInitialPosition.test.js @@ -0,0 +1,119 @@ +import { describe, expect, test } from 'vitest'; +import { GridWalkCamera, projectGridPoint } from '../app/gridWalk/gridWalkCamera.js'; +import { resolveF1SimulatorOptions } from '../config/defaultOptions.js'; +import { mergeRestartOptions } from '../config/restartOptions.js'; +import { createRaceSimulation } from '../simulation/raceSimulation.js'; +import { pointAt } from '../simulation/track/trackModel.js'; +import { GridWalkSession } from '../app/gridWalk/gridWalkSession.js'; + +const heading = 0.65; +const point = (along, across = 0) => ({ + x: 240 + along * Math.cos(heading) - across * Math.sin(heading), + y: -170 + along * Math.sin(heading) + across * Math.cos(heading), +}); +const cars = Array.from({ length: 10 }, (_, index) => ({ + id: `entry-${index}`, heading, ...point(-80 - index * 100, index % 2 ? 20 : -20), +})); +const startLine = point(20); +const views = [ + { orientation: 'horizontal', width: 1120, height: 620, area: { left: 40, top: 110, right: 1080, bottom: 520 } }, + { orientation: 'vertical', width: 390, height: 760, area: { left: 20, top: 90, right: 370, bottom: 700 } }, +]; + +describe('Grid Walk initial position', () => { + test('defaults to the selected entry centered on the grid axis', () => { + for (const view of views) { + const camera = new GridWalkCamera(cars); + const frame = camera.update({ ...view, selectedId: cars[4].id }); + const selected = projectGridPoint(frame, cars[4]); + const axis = view.orientation === 'horizontal' ? 'x' : 'y'; + const center = axis === 'x' ? (view.area.left + view.area.right) / 2 : (view.area.top + view.area.bottom) / 2; + expect(selected[axis]).toBeCloseTo(center); + } + }); + + test.each(views)('aligns the actual start line at the safe $orientation edge', (view) => { + const before = JSON.stringify(cars); + const camera = new GridWalkCamera(cars, { initialPosition: 'start-line', startLine }); + const frame = camera.update({ ...view, selectedId: cars[4].id }); + const projected = projectGridPoint(frame, startLine); + if (view.orientation === 'horizontal') expect(projected.x).toBeCloseTo(view.area.right - 24); + else expect(projected.y).toBeCloseTo(view.area.top + 24); + expect(frame.position).toBeGreaterThanOrEqual(frame.minPosition); + expect(frame.position).toBeLessThanOrEqual(frame.maxPosition); + expect(JSON.stringify(cars)).toBe(before); + }); + + test.each([7110, 1971, 42])('aligns the seeded track line without changing race state (seed %i)', (trackSeed) => { + const drivers = cars.map(({ id }) => ({ id, name: id })); + const sim = createRaceSimulation({ drivers, seed: 71, trackSeed, warmup: false }); + const before = JSON.stringify(sim.snapshot()); + const grid = new GridWalkSession(sim, { initialView: 'grid-walk' }).snapshot.cars; + const actualStart = pointAt(sim.track, 0); + for (const view of views) { + const camera = new GridWalkCamera(grid, { initialPosition: 'start-line', startLine: actualStart }); + const frame = camera.update({ ...view, selectedId: grid[0].id }); + const projected = projectGridPoint(frame, actualStart); + if (view.orientation === 'horizontal') expect(projected.x).toBeCloseTo(view.area.right - 24); + else expect(projected.y).toBeCloseTo(view.area.top + 24); + } + expect(JSON.stringify(sim.snapshot())).toBe(before); + }); + + test('refreshes untouched initial framing after placeholder measurements and rotation', () => { + const camera = new GridWalkCamera(cars, { initialPosition: 'start-line', startLine }); + camera.update({ selectedId: cars[0].id, width: 1, height: 1, orientation: 'horizontal' }); + for (const view of views) { + const frame = camera.update({ ...view, selectedId: cars[4].id }); + const fresh = new GridWalkCamera(cars, { initialPosition: 'start-line', startLine }) + .update({ ...view, selectedId: cars[4].id }); + expect(frame).toEqual(fresh); + const projected = projectGridPoint(frame, startLine); + if (view.orientation === 'horizontal') expect(projected.x).toBeCloseTo(view.area.right - 24); + else expect(projected.y).toBeCloseTo(view.area.top + 24); + } + }); + + test.each(['pan', 'focus'])('preserves world position after user %s across selection and resize', (interaction) => { + const camera = new GridWalkCamera(cars, { initialPosition: 'start-line', startLine }); + camera.update({ ...views[0], selectedId: cars[0].id }); + if (interaction === 'pan') expect(camera.pan(50)).toBe(true); + else camera.focus(cars[7].id); + const before = camera.update({ ...views[0], selectedId: cars[0].id }); + for (const view of views) { + const frame = camera.update({ ...view, selectedId: cars[9].id }); + expect(frame.position).toBeCloseTo(before.position); + expect(frame.center).toEqual(before.center); + } + }); + + test.each([1, 2])('aligns a %i-car roster while keeping pan bounded and retaining resized position', (count) => { + for (const view of views) { + const camera = new GridWalkCamera(cars.slice(0, count), { initialPosition: 'start-line', startLine }); + const frame = camera.update({ ...view, selectedId: cars[0].id }); + const projected = projectGridPoint(frame, startLine); + if (view.orientation === 'horizontal') expect(projected.x).toBeCloseTo(view.area.right - 24); + else expect(projected.y).toBeCloseTo(view.area.top + 24); + for (const delta of [100000, -200000]) { + camera.pan(delta); + const bounded = camera.update({ ...view, selectedId: cars[0].id }); + expect([bounded.minPosition, bounded.maxPosition]).toContain(bounded.position); + const resized = camera.update({ ...views[1], selectedId: cars[0].id }); + expect(resized.position).toBeCloseTo(bounded.position); + } + } + }); + + test('normalizes initial position and preserves or replaces it on restart', () => { + const drivers = cars.map(({ id }) => ({ id, name: id })); + const initial = resolveF1SimulatorOptions({ drivers }); + expect(initial.gridWalk.initialPosition).toBe('selected'); + expect(resolveF1SimulatorOptions({ drivers, gridWalk: { initialPosition: 'unknown' } }).gridWalk.initialPosition).toBe('selected'); + const start = resolveF1SimulatorOptions(mergeRestartOptions(initial, { gridWalk: { enabled: true, initialPosition: 'start-line' } })); + expect(start.gridWalk.initialPosition).toBe('start-line'); + const retained = resolveF1SimulatorOptions(mergeRestartOptions(start, { gridWalk: { ambientMotion: false } })); + expect(retained.gridWalk).toMatchObject({ enabled: true, initialPosition: 'start-line', ambientMotion: false }); + const reset = resolveF1SimulatorOptions(mergeRestartOptions(retained, { gridWalk: { initialPosition: 'selected' } })); + expect(reset.gridWalk.initialPosition).toBe('selected'); + }); +}); diff --git a/src/__tests__/gridWalkLayout.test.js b/src/__tests__/gridWalkLayout.test.js new file mode 100644 index 0000000..3b6e32e --- /dev/null +++ b/src/__tests__/gridWalkLayout.test.js @@ -0,0 +1,27 @@ +import { describe, expect, test } from 'vitest'; +import { GridWalkLayout } from '../app/gridWalk/gridWalkLayout.js'; +import { GridWalkProjectBanner } from '../app/gridWalk/gridWalkProjectBanner.js'; + +describe('Grid Walk host coordinates', () => { + test.each([1, 0.985, 0.7, 1.2])('measures the same scene inside a host scaled by %s', (scale) => { + const layout = new GridWalkLayout({ + canvasHost: { clientWidth: 1120, clientHeight: 620, + getBoundingClientRect: () => ({ top: 100, width: 1120 * scale, height: 620 * scale }) }, + element: { querySelector: () => ({ getBoundingClientRect: () => ({ bottom: 100 + 70 * scale }) }) }, + }); + const area = layout.measure(132); + expect(area.left).toBe(16); + expect(area.right).toBe(1104); + expect(area.top).toBeCloseTo(82); + expect(area.bottom).toBe(472); + }); + + test.each([1, 0.985, 0.7, 1.2])('reserves banner space in canvas coordinates at host scale %s', (scale) => { + const banner = Object.create(GridWalkProjectBanner.prototype); + banner.enabled = true; + banner.element = { hidden: true, classList: { toggle() {} }, style: {}, + getBoundingClientRect: () => ({ height: 108 * scale }) }; + expect(banner.measure(1120, 620, scale)).toBeCloseTo(132); + expect(banner.element.hidden).toBe(true); + }); +}); diff --git a/src/__tests__/lapTelemetry.test.js b/src/__tests__/lapTelemetry.test.js index 9b356e5..056c035 100644 --- a/src/__tests__/lapTelemetry.test.js +++ b/src/__tests__/lapTelemetry.test.js @@ -3,6 +3,91 @@ import { createLapTelemetry, updateLapTelemetry } from '../simulation/timing/lap import { updateSectorPerformance } from '../simulation/timing/sectorPerformance.js'; describe('lap telemetry', () => { + test.each([7, 13, 14, 15])('uses the same representable line for later-lap sector %s timing and position', (boundaryNumber) => { + const track = { length: 2500.0588235294117 }; + const boundary = Math.floor(boundaryNumber / 3) * track.length + (boundaryNumber % 3) * (track.length / 3); + const initialDistance = boundary - 1; + const justBefore = boundary - boundary * Number.EPSILON; + const car = { + raceDistance: initialDistance, + lapTelemetry: createLapTelemetry(track, 0, initialDistance, 10), + }; + + car.raceDistance = justBefore; + expect(updateLapTelemetry(car, initialDistance, 0.5, track, 10)).toBe(false); + expect(car.lapTelemetry.currentSector).toBe((boundaryNumber - 1) % 3 + 1); + expect(car.lapTelemetry.completedLaps).toBe(Math.floor((boundaryNumber - 1) / 3)); + + car.raceDistance = boundary; + expect(updateLapTelemetry(car, justBefore, 1, track, 10)).toBe(true); + expect(car.lapTelemetry.currentSector).toBe(boundaryNumber % 3 + 1); + expect(car.lapTelemetry.completedLaps).toBe(Math.floor(boundaryNumber / 3)); + expect(car.lapTelemetry.bestSectors[(boundaryNumber - 1) % 3]).toBe(1); + if (boundaryNumber % 3 !== 0) { + expect(car.lapTelemetry.currentSectors[(boundaryNumber - 1) % 3]).toBe(1); + } + expect(updateLapTelemetry(car, boundary, 2, track, 10)).toBe(false); + expect(car.lapTelemetry.sectorPerformanceRevision).toBe(1); + }); + + test.each([1, 2, 3].flatMap((sector) => [0.0005, 0.0000005].flatMap((distanceBefore) => + [0, 10].map((distanceAfter) => ({ sector, distanceBefore, distanceAfter })), + )))('records sector $sector once from $distanceBefore before its line to $distanceAfter after it', ({ + sector, distanceBefore, distanceAfter, + }) => { + const track = { length: 12000 }; + const boundary = sector * 4000; + const previousDistance = boundary - distanceBefore; + const car = { + raceDistance: previousDistance, + lapTelemetry: createLapTelemetry(track, previousDistance / 100, previousDistance, 3), + }; + car.lapTelemetry.currentLapStartedAt = 0; + car.lapTelemetry.currentSectorStartedAt = (sector - 1) * 40; + for (let index = 0; index < sector - 1; index += 1) car.lapTelemetry.currentSectors[index] = 40; + + expect(updateLapTelemetry(car, previousDistance, previousDistance / 100, track, 3)).toBe(false); + expect(car.lapTelemetry.bestSectors[sector - 1]).toBeNull(); + + car.raceDistance = boundary + distanceAfter; + expect(updateLapTelemetry(car, previousDistance, car.raceDistance / 100, track, 3)).toBe(true); + expect(car.lapTelemetry.bestSectors[sector - 1]).toBeCloseTo(40, 8); + expect(car.lapTelemetry.sectorPerformanceRevision).toBe(1); + if (sector === 3) { + expect(car.lapTelemetry.lastSectors).toEqual([40, 40, 40]); + expect(car.lapTelemetry.lastLapTime).toBeCloseTo(120, 8); + expect(car.lapTelemetry.bestLapTime).toBeCloseTo(120, 8); + expect(car.lapTelemetry.completedLaps).toBe(1); + } else { + expect(car.lapTelemetry.currentSectors[sector - 1]).toBeCloseTo(40, 8); + expect(car.lapTelemetry.lastLapTime).toBeNull(); + } + + const crossingDistance = car.raceDistance; + expect(updateLapTelemetry(car, crossingDistance, crossingDistance / 100 + 1, track, 3)).toBe(false); + car.raceDistance += 10; + expect(updateLapTelemetry(car, crossingDistance, car.raceDistance / 100 + 1, track, 3)).toBe(false); + expect(car.lapTelemetry.bestSectors[sector - 1]).toBeCloseTo(40, 8); + expect(car.lapTelemetry.sectorPerformanceRevision).toBe(1); + if (sector === 3) expect(car.lapTelemetry.lastLapTime).toBeCloseTo(120, 8); + }); + + test('retains a complete lap when the previous sample is just before the timing line', () => { + const track = { length: 12000 }; + const car = { raceDistance: 0, lapTelemetry: createLapTelemetry(track, 0, 0, 3) }; + + for (const distance of [3990, 4010, 7990, 8010, 11999.9995, 12010]) { + const previousDistance = car.raceDistance; + car.raceDistance = distance; + updateLapTelemetry(car, previousDistance, distance / 100, track, 3); + } + + expect(car.lapTelemetry.completedLaps).toBe(1); + expect(car.lapTelemetry.lastLapTime).toBeCloseTo(120, 8); + expect(car.lapTelemetry.bestLapTime).toBeCloseTo(120, 8); + car.lapTelemetry.lastSectors.forEach((time) => expect(time).toBeCloseTo(40, 8)); + }); + test('reuses position buffers and updates only the active slot on same-sector progress', () => { const track = { length: 300 }; const car = { diff --git a/src/__tests__/paddockSimulatorController.test.js b/src/__tests__/paddockSimulatorController.test.js index cefe3ad..548f90f 100644 --- a/src/__tests__/paddockSimulatorController.test.js +++ b/src/__tests__/paddockSimulatorController.test.js @@ -63,11 +63,12 @@ describe('PaddockSimulatorController lifecycle', () => { test('prevents mounting view controls during startup and after runtime startup', async () => { let complete; const init = vi.spyOn(F1SimulatorApp.prototype, 'init') - .mockImplementation(() => new Promise((resolve) => { complete = resolve; })); + .mockImplementation(({ onInitialized }) => new Promise((resolve) => { complete = resolve; }).then(onInitialized)); const controller = new PaddockSimulatorController(OPTIONS); const root = { innerHTML: 'host content', querySelector: () => null, querySelectorAll: () => [] }; const pending = controller.start(); try { + await Promise.resolve(); expect(() => controller.mountViewControls(root)).toThrow('before calling start()'); expect(root.innerHTML).toBe('host content'); complete(); @@ -99,10 +100,10 @@ describe('PaddockSimulatorController lifecycle', () => { test('concurrent start calls await initialization before publishing the app', async () => { let finishInitialization; - const init = vi.spyOn(F1SimulatorApp.prototype, 'init').mockImplementation(() => ( + const init = vi.spyOn(F1SimulatorApp.prototype, 'init').mockImplementation(({ onInitialized }) => ( new Promise((resolve) => { finishInitialization = resolve; - }) + }).then(onInitialized) )); const controller = new PaddockSimulatorController(OPTIONS); @@ -135,7 +136,7 @@ describe('PaddockSimulatorController lifecycle', () => { test('restart during initialization preserves the mounted DOM and pending runtime options', async () => { let complete; - const init = vi.spyOn(F1SimulatorApp.prototype, 'init').mockImplementation(() => new Promise((resolve) => { complete = resolve; })); + const init = vi.spyOn(F1SimulatorApp.prototype, 'init').mockImplementation(({ onInitialized }) => new Promise((resolve) => { complete = resolve; }).then(onInitialized)); const controller = new PaddockSimulatorController(OPTIONS); const root = { innerHTML: '', querySelector: () => null, querySelectorAll: () => [] }; controller.mountRaceControls(root); @@ -143,6 +144,7 @@ describe('PaddockSimulatorController lifecycle', () => { const originalOptions = controller.options; const pending = controller.start(); try { + await Promise.resolve(); expect(() => controller.restart({ title: 'Replacement' })).toThrow('Await start() before restarting'); expect(root.innerHTML).toBe(originalMarkup); expect(controller.options).toBe(originalOptions); @@ -158,11 +160,14 @@ describe('PaddockSimulatorController lifecycle', () => { } }); - test('failed initialization clears lifecycle state and permits a clean retry', async () => { + test.each([false, true])('failed initialization clears lifecycle state and permits a clean retry after publication=%s', async (published) => { const failure = new Error('asset initialization failed'); const init = vi.spyOn(F1SimulatorApp.prototype, 'init') - .mockRejectedValueOnce(failure) - .mockResolvedValueOnce(); + .mockImplementationOnce(async ({ onInitialized }) => { + if (published) onInitialized(); + throw failure; + }) + .mockImplementationOnce(async ({ onInitialized }) => { onInitialized(); }); const destroy = vi.spyOn(F1SimulatorApp.prototype, 'destroy'); const controller = new PaddockSimulatorController(OPTIONS); diff --git a/src/__tests__/proceduralTrackAsset.test.js b/src/__tests__/proceduralTrackAsset.test.js index 2298bab..b58b5e2 100644 --- a/src/__tests__/proceduralTrackAsset.test.js +++ b/src/__tests__/proceduralTrackAsset.test.js @@ -10,10 +10,112 @@ import { } from '../rendering/proceduralTrackAsset.js'; import { buildTrackModel, offsetTrackPoint, TRACK, WORLD } from '../simulation/trackModel.js'; import { metersToSimUnits } from '../simulation/units.js'; +import { resetTrackQueryStats, snapshotTrackQueryStats } from '../simulation/track/trackQueryIndex.js'; const TRACK_RENDER_TEST_TIMEOUT_MS = 30000; +function trackDrawingSnapshot(asset) { + return asset.container.children.map((child) => ({ + label: child.label, + alpha: child.alpha, + renderable: child.renderable, + bounds: child.worldGrassBounds, + texture: child.texture?.label, + tileScale: child.tileScale && { x: child.tileScale.x, y: child.tileScale.y }, + maskIndex: asset.container.children.indexOf(child.mask), + instructions: child.context?.instructions.map(({ action, data }) => ({ + action, + style: data.style && { ...data.style, texture: data.style.texture?.label }, + path: data.path?.instructions, + hole: data.hole?.instructions, + })), + })); +} + describe('procedural track asset geometry', () => { + test('startup rendering preserves every drawing instruction and splits safety queries within kerbs and borders', async () => { + const track = buildTrackModel(TRACK); + const synchronous = new ProceduralTrackAsset(); + resetTrackQueryStats(track); + synchronous.render(track); + const synchronousQueries = snapshotTrackQueryStats(track).nearestQueries; + + const startup = new ProceduralTrackAsset(); + const pauses = []; + let workUntilPause = 64; + resetTrackQueryStats(track); + await startup.renderAsync(track, { + checkpoint() { + workUntilPause -= 1; + if (workUntilPause > 0) return null; + workUntilPause = 64; + pauses.push({ + layer: startup.container.children.at(-1)?.label, + queries: snapshotTrackQueryStats(track).nearestQueries, + }); + return Promise.resolve(); + }, + }); + + expect(trackDrawingSnapshot(startup)).toEqual(trackDrawingSnapshot(synchronous)); + expect(snapshotTrackQueryStats(track).nearestQueries).toBe(synchronousQueries); + for (const layer of ['track-kerbs', 'track-borders']) { + const layerPauses = pauses.filter((pause) => pause.layer === layer); + expect(layerPauses.length).toBeGreaterThan(3); + const queryIncrements = layerPauses.slice(1).map((pause, index) => pause.queries - layerPauses[index].queries); + expect(queryIncrements.filter((count) => count > 0).length).toBeGreaterThan(3); + // At most one segment's eight safety samples runs per work item. + expect(Math.max(...queryIncrements)).toBeLessThanOrEqual(64 * 8); + } + synchronous.container.destroy({ children: true }); + startup.container.destroy({ children: true }); + }, TRACK_RENDER_TEST_TIMEOUT_MS); + + test('startup cancellation checks before clearing or allocating display objects', async () => { + const track = buildTrackModel(TRACK); + const asset = new ProceduralTrackAsset(); + const previous = new Container(); + asset.container.addChild(previous); + const cancelled = new Error('startup cancelled'); + + await expect(asset.renderAsync(track, { checkpoint() { throw cancelled; } })).rejects.toBe(cancelled); + + expect(asset.container.children).toEqual([previous]); + expect(previous.destroyed).toBe(false); + asset.container.destroy({ children: true }); + }); + + test('destroying startup during a border pause owns partial graphics and prevents more drawing or queries', async () => { + const track = buildTrackModel(TRACK); + const asset = new ProceduralTrackAsset(); + const cancelled = new Error('startup destroyed'); + let releasePause; + let reachedPause; + const paused = new Promise((resolve) => { reachedPause = resolve; }); + const waiting = new Promise((resolve) => { releasePause = resolve; }); + let borderQueries = null; + const rendering = asset.renderAsync(track, { + checkpoint() { + if (asset.container.destroyed) throw cancelled; + if (asset.container.children.at(-1)?.label !== 'track-borders') return null; + const queries = snapshotTrackQueryStats(track).nearestQueries; + borderQueries ??= queries; + if (queries - borderQueries < 64) return null; + reachedPause(); + return waiting; + }, + }); + await paused; + const children = [...asset.container.children]; + const queriesAtDestroy = snapshotTrackQueryStats(track).nearestQueries; + asset.container.destroy({ children: true, texture: false, textureSource: false }); + releasePause(); + + await expect(rendering).rejects.toBe(cancelled); + expect(children.every((child) => child.destroyed)).toBe(true); + expect(snapshotTrackQueryStats(track).nearestQueries).toBe(queriesAtDestroy); + }, TRACK_RENDER_TEST_TIMEOUT_MS); + test('uses the default sampling step when offset stroke callers omit it', () => { const track = buildTrackModel(TRACK); const options = { side: 1, offset: track.width / 2 }; diff --git a/src/__tests__/proceduralTrackAsync.test.js b/src/__tests__/proceduralTrackAsync.test.js new file mode 100644 index 0000000..a304230 --- /dev/null +++ b/src/__tests__/proceduralTrackAsync.test.js @@ -0,0 +1,130 @@ +import { afterEach, describe, expect, test, vi } from 'vitest'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +async function coldTrackModules() { + vi.resetModules(); + const [procedural, builder, validation, cache, centerline] = await Promise.all([ + import('../simulation/track/proceduralTrack.js'), + import('../simulation/track/trackBuilder.js'), + import('../simulation/track/trackValidation.js'), + import('../simulation/track/trackModelCache.js'), + import('../simulation/track/proceduralCenterline.js'), + ]); + return { ...procedural, builder, validation, cache, centerline }; +} + +describe('async procedural track preparation', () => { + test.each([ + ['primary candidate', 71, {}, 71], + ['later primary candidate', 7110, {}, 387284027], + ['accepted fallback', 3, { attempts: { primary: 1, fallback: 4 } }, 2246822516], + ['safe fallback', 71, { + attempts: { primary: 1, fallback: 1 }, + length: { minMeters: 1, maxMeters: 2 }, + }, 71], + ['training profile overrides', 4101, { + profile: 'training-short', + length: { minMeters: 1, maxMeters: 10000 }, + validation: { + minClearanceMultiplier: 0, + minShapeVariation: 0, + minNonAdjacentArcMeters: 0, + maxLocalTurnRadians: 100, + maxSampleHeadingDeltaRadians: 100, + }, + attempts: { primary: 1, fallback: 1 }, + }, 4101], + ])('matches cold synchronous output for %s', async (path, seed, options, expectedSeed) => { + const sync = await coldTrackModules(); + const expected = sync.createProceduralTrack(seed, options); + const expectedModel = sync.builder.buildTrackModel(expected); + const async = await coldTrackModules(); + const checkpoint = vi.fn(() => null); + const actual = await async.createProceduralTrackAsync(seed, options, { checkpoint }); + + expect(actual).not.toBe(expected); + expect(actual).toEqual(expected); + expect(actual.seed).toBe(expectedSeed); + expect(async.builder.buildTrackModel(actual).samples).toEqual(expectedModel.samples); + expect(Object.isFrozen(actual)).toBe(true); + expect(Object.isFrozen(actual.centerlineControls[0])).toBe(true); + expect(async.createProceduralTrack(seed, options)).toBe(actual); + expect(checkpoint.mock.calls.length).toBeGreaterThan(2); + if (path === 'safe fallback') { + expect(actual.centerlineControls).toEqual(async.centerline.generateSafeFallbackCenterlineControls(seed, actual.generationOptions.shape)); + } + }); + + test('allows another event-loop task between every candidate build', async () => { + const modules = await coldTrackModules(); + const build = modules.builder.buildTrackModel; + let completedTasks = 0; + let resumed = false; + const candidateTasks = []; + vi.spyOn(modules.builder, 'buildTrackModel').mockImplementation((...args) => { + candidateTasks.push(completedTasks); + return build(...args); + }); + const checkpoint = vi.fn(() => { + if (resumed) { + resumed = false; + return null; + } + return new Promise((resolve) => { + setTimeout(() => { + completedTasks += 1; + resumed = true; + resolve(); + }, 0); + }); + }); + + const track = await modules.createProceduralTrackAsync(7110, {}, { checkpoint }); + + expect(track.seed).toBe(387284027); + expect(candidateTasks).toHaveLength(6); + expect(candidateTasks[0]).toBeGreaterThan(0); + expect(new Set(candidateTasks).size).toBe(candidateTasks.length); + expect(completedTasks).toBeGreaterThan(candidateTasks.at(-1)); + expect(modules.createProceduralTrack(7110)).toBe(track); + expect(candidateTasks).toHaveLength(6); + }); + + test.each(['before work', 'after build', 'before cache commit', 'while paused before cache commit'])('cancellation %s leaves no partial cached track', async (boundary) => { + const modules = await coldTrackModules(); + const builds = vi.spyOn(modules.builder, 'buildTrackModel'); + const validations = vi.spyOn(modules.validation, 'isValidProceduralTrackModel'); + const commits = vi.spyOn(modules.cache, 'cacheProceduralTrackDefinition'); + const cancelled = new Error('Preparation cancelled'); + let cancelledWhilePaused = false; + const checkpoint = () => { + if (cancelledWhilePaused) throw cancelled; + if (boundary === 'before work') throw cancelled; + if (boundary === 'after build' && builds.mock.calls.length > 0) throw cancelled; + if (boundary === 'before cache commit' && validations.mock.calls.length > 0) { + return Promise.reject(cancelled); + } + if (boundary === 'while paused before cache commit' && validations.mock.calls.length > 0) { + return Promise.resolve().then(() => { + cancelledWhilePaused = true; + }); + } + return null; + }; + + await expect(modules.createProceduralTrackAsync(71, {}, { checkpoint })).rejects.toBe(cancelled); + + expect(builds).toHaveBeenCalledTimes(boundary === 'before work' ? 0 : 1); + expect(validations).toHaveBeenCalledTimes(boundary.includes('cache commit') ? 1 : 0); + expect(commits).not.toHaveBeenCalled(); + const buildsBeforeRetry = builds.mock.calls.length; + const recovered = modules.createProceduralTrack(71); + expect(builds).toHaveBeenCalledTimes(buildsBeforeRetry + 1); + expect(commits).toHaveBeenCalledTimes(1); + expect(modules.createProceduralTrack(71)).toBe(recovered); + expect(await modules.createProceduralTrackAsync(71)).toBe(recovered); + }); +}); diff --git a/src/__tests__/publicApi.types.ts b/src/__tests__/publicApi.types.ts index b286ff1..2ea3eb7 100644 --- a/src/__tests__/publicApi.types.ts +++ b/src/__tests__/publicApi.types.ts @@ -179,6 +179,10 @@ void environmentThemeSelector; const invalidNumericThemeToken: PaddockThemeTokenValue = 720; void invalidNumericThemeToken; +// @ts-expect-error Initial Grid Walk positioning accepts only the supported presets. +const invalidGridWalkPosition: NonNullable['initialPosition'] = 'center'; +void invalidGridWalkPosition; + const root = document.createElement('div'); const resolvedPublicTheme: ResolvedPaddockTheme = resolvePaddockTheme({ @@ -260,7 +264,7 @@ const extraEntry: ChampionshipEntryBlueprint = { }; const options: F1SimulatorOptions = { - gridWalk: { enabled: true, initialView: 'grid-walk', ambientMotion: true }, + gridWalk: { enabled: true, initialView: 'grid-walk', initialPosition: 'start-line', ambientMotion: true }, preset: 'timing-overlay', drivers: DEMO_PROJECT_DRIVERS, entries: [...CHAMPIONSHIP_ENTRY_BLUEPRINTS, extraEntry], diff --git a/src/__tests__/readoutFormatters.test.js b/src/__tests__/readoutFormatters.test.js new file mode 100644 index 0000000..4045d21 --- /dev/null +++ b/src/__tests__/readoutFormatters.test.js @@ -0,0 +1,19 @@ +import { describe, expect, test } from 'vitest'; +import { formatTelemetryTime } from '../app/readouts/readoutFormatters.js'; + +describe('telemetry time formatting', () => { + test.each([ + [59.9994, '59.999s'], + [59.9999, '1:00.000'], + [60, '1:00.000'], + [119.9994, '1:59.999'], + [119.9999, '2:00.000'], + [120, '2:00.000'], + [120.001, '2:00.001'], + [-1, '0.000s'], + [NaN, '--'], + [Infinity, '--'], + ])('formats %s seconds as %s', (value, expected) => { + expect(formatTelemetryTime(value)).toBe(expected); + }); +}); diff --git a/src/__tests__/runtimeStartup.test.js b/src/__tests__/runtimeStartup.test.js index 509ef34..6c9a718 100644 --- a/src/__tests__/runtimeStartup.test.js +++ b/src/__tests__/runtimeStartup.test.js @@ -6,6 +6,9 @@ import { DEFAULT_F1_SIMULATOR_ASSETS } from '../config/defaultAssets.js'; import { runFrameLoopTick } from '../app/runtime/frameLoop.js'; import { configureRuntimeTicker } from '../app/runtime/runtimeTiming.js'; import { RuntimeStartupCancelledError } from '../app/runtime/pixiStartupLifecycle.js'; +import * as browserSimulationStartup from '../app/runtime/browserSimulationStartup.js'; +import * as startupTasks from '../app/runtime/startupTasks.js'; +import * as trackBuilder from '../simulation/track/trackBuilder.js'; import { FIXED_STEP } from '../simulation/raceSimulation.js'; // GPU/startup tests isolate the DOM input component; real wrapper cleanup and @@ -54,8 +57,14 @@ describe('browser startup resource lifecycle', () => { vi.stubGlobal('removeEventListener', vi.fn()); vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1)); vi.stubGlobal('cancelAnimationFrame', vi.fn()); + // GPU lifecycle cases isolate geometry; dedicated phase-cancellation cases + // below exercise the production preparation/checkpoint path. + vi.spyOn(browserSimulationStartup, 'prepareBrowserSimulation').mockImplementation(async (app, checkpoint) => { + await checkpoint(true); + return app.createRaceSimulation(); + }); vi.spyOn(F1SimulatorApp.prototype, 'createRaceSimulation').mockReturnValue({ snapshot: () => snapshot }); - for (const method of ['createCars', 'bindControls', 'syncTimingPanelDisclosureState', 'renderTrack', 'updateDom', 'renderInitialFrame', 'observeLayoutResize']) { + for (const method of ['createCars', 'bindControls', 'syncTimingPanelDisclosureState', 'renderTrack', 'renderStartupTrack', 'updateDom', 'renderInitialFrame', 'observeLayoutResize']) { vi.spyOn(F1SimulatorApp.prototype, method).mockImplementation(() => {}); } vi.spyOn(F1SimulatorApp.prototype, 'loadAssets').mockResolvedValue({}); @@ -78,6 +87,93 @@ describe('browser startup resource lifecycle', () => { return { init, renderers, applications }; } + test.each(['track preparation', 'partial track drawing'])('cancellation during %s preserves readiness boundaries and permits a clean retry', async (phase) => { + const { init, applications, renderers } = installPixiInit(); + F1SimulatorApp.prototype.createRaceSimulation.mockRestore(); + if (phase === 'track preparation') browserSimulationStartup.prepareBrowserSimulation.mockRestore(); + else F1SimulatorApp.prototype.renderStartupTrack.mockRestore(); + const gate = deferred(); + const entered = deferred(); + const builds = phase === 'track preparation' ? vi.spyOn(trackBuilder, 'buildTrackModel') : null; + const createCheckpoint = startupTasks.createStartupCheckpoint; + let held = false; + vi.spyOn(startupTasks, 'createStartupCheckpoint').mockImplementation((app) => { + const checkpoint = createCheckpoint(app); + return (force) => { + const atBoundary = phase === 'track preparation' + ? builds.mock.calls.length > 0 && app.sim === null + : app.trackAsset?.container.children.length > 0; + if (!held && atBoundary) { + held = true; + entered.resolve(app); + return gate.promise.then(() => checkpoint(force)); + } + return checkpoint(force); + }; + }); + const onReady = vi.fn(); + const onError = vi.fn(); + const simulator = new PaddockSimulatorController({ + seed: 17, trackSeed: 8910112, warmup: { enabled: false }, + drivers: [{ id: 'alpha', name: 'Alpha' }], onReady, onError, + }); + simulator.roots.set('race-canvas', createRoot()); + const pending = simulator.start(); + const rejection = expect(pending).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + const initializing = await entered.promise; + try { + expect(simulator.getSnapshot()).toBeNull(); + expect(simulator.expert).toBeNull(); + expect(simulator.setPitIntent('alpha', 1)).toBe(false); + expect(() => simulator.restart()).toThrow('Await start() before restarting'); + expect(initializing.runtimeSceneReady).toBe(false); + expect(initializing.bindControls).not.toHaveBeenCalled(); + expect(initializing.createCars).not.toHaveBeenCalled(); + expect(onReady).not.toHaveBeenCalled(); + let partialChildren = []; + if (phase === 'track preparation') { + expect(init).not.toHaveBeenCalled(); + expect(builds).toHaveBeenCalled(); + expect(initializing.sim).toBeNull(); + } else { + expect(applications[0].ticker.started).toBe(false); + expect(initializing.worldLayer.renderable).toBe(false); + partialChildren = [...initializing.trackAsset.container.children]; + expect(partialChildren.length).toBeGreaterThan(0); + } + + simulator.destroy(); + gate.resolve(); + await rejection; + expect(initializing.root).toBeNull(); + expect(initializing.sim).toBeNull(); + expect(initializing.worldLayer).toBeNull(); + expect(initializing.trackAsset).toBeNull(); + expect(partialChildren.every((child) => child.destroyed)).toBe(true); + expect(simulator.app).toBeNull(); + expect(simulator.startPromise).toBeNull(); + expect(simulator.initializingApp).toBeNull(); + expect(onReady).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + if (phase === 'partial track drawing') expect(renderers[0].destroy).toHaveBeenCalledTimes(1); + + simulator.roots.set('race-canvas', createRoot()); + await expect(simulator.start()).resolves.toBe(simulator); + expect(simulator.getSnapshot().cars.map((car) => car.id)).toEqual(['alpha']); + expect(simulator.app.runtimeSceneReady).toBe(true); + expect(simulator.app.worldLayer.renderable).toBe(true); + expect(simulator.app.app.ticker.started).toBe(true); + expect(simulator.app.bindControls).toHaveBeenCalledTimes(1); + expect(onReady).toHaveBeenCalledTimes(1); + expect(onError).not.toHaveBeenCalled(); + } finally { + simulator.destroy(); + gate.resolve(); + await pending.catch(() => {}); + } + expect(renderers.every((renderer) => renderer.destroy.mock.calls.length === 1)).toBe(true); + }); + test('destroy while GPU init is pending releases eventual resources without mounting or ready/error callbacks', async () => { const gate = deferred(); const { renderers, applications } = installPixiInit(gate.promise); @@ -87,6 +183,7 @@ describe('browser startup resource lifecycle', () => { const host = app.canvasHost; const pending = app.init(); const rejection = expect(pending).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + await vi.waitFor(() => expect(applications).toHaveLength(1)); expect(() => app.destroy()).not.toThrow(); app.destroy(); @@ -103,6 +200,27 @@ describe('browser startup resource lifecycle', () => { expect(app.app).toBeNull(); }); + test('cancellation as preparation resolves cannot reacquire simulation or GPU resources', async () => { + const { init, applications } = installPixiInit(); + const onReady = vi.fn(); + const onError = vi.fn(); + const app = createRuntime({ onReady, onError }); + F1SimulatorApp.prototype.createRaceSimulation.mockImplementationOnce(() => { + queueMicrotask(() => app.destroy()); + return { snapshot: () => snapshot }; + }); + + await expect(app.init()).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + + expect(init).not.toHaveBeenCalled(); + expect(applications).toHaveLength(0); + expect(app.sim).toBeNull(); + expect(app.app).toBeNull(); + expect(app.root).toBeNull(); + expect(onReady).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + }); + test('destroy during assets leaves textures and rendering references cleared after late resolution', async () => { const { renderers } = installPixiInit(); const assets = deferred(); @@ -134,6 +252,7 @@ describe('browser startup resource lifecycle', () => { const app = createRuntime({ onError, gridWalk: { enabled } }); const pending = app.init(); const rejection = expect(pending).rejects.toBe(failure); + await vi.waitFor(() => expect(applications).toHaveLength(1)); gate.reject(failure); await rejection; expect(applications[0].stage).toBeNull(); @@ -212,6 +331,7 @@ describe('browser startup resource lifecycle', () => { const app = createRuntime({ onError }); const pending = app.init(); const rejection = expect(pending).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + await vi.waitFor(() => expect(applications).toHaveLength(1)); app.destroy(); gate.reject(new Error('GPU failure after unmount')); await rejection; @@ -261,6 +381,7 @@ describe('browser startup resource lifecycle', () => { const app = createRuntime({ onError }); const pending = app.init(); const rejection = expect(pending).rejects.toBe(failure); + await vi.waitFor(() => expect(applications).toHaveLength(1)); vi.spyOn(applications[0].stage, 'destroy').mockImplementation(() => { throw cleanupFailure; }); gate.reject(failure); await rejection; @@ -286,7 +407,7 @@ describe('browser startup resource lifecycle', () => { expect(onError).toHaveBeenCalledWith(failure, { phase: 'destroy' }); }); - test('ready callbacks may destroy the runtime without later installing controls or a ticker', async () => { + test('ready callbacks may destroy the initialized runtime and release its controls and ticker', async () => { const { applications, renderers } = installPixiInit(); let app; app = createRuntime({ onReady: () => app.destroy() }); @@ -296,6 +417,212 @@ describe('browser startup resource lifecycle', () => { expect(app.resizeHandler).toBeNull(); }); + test('browser restart preserves filtered expert rosters until explicitly replaced', async () => { + installPixiInit(); + F1SimulatorApp.prototype.createRaceSimulation.mockRestore(); + const simulator = new PaddockSimulatorController({ + seed: 17, trackSeed: 31, warmup: false, + drivers: [{ id: 'alpha', name: 'Alpha' }, { id: 'beta', name: 'Beta' }], + expert: { enabled: true, controlledDrivers: ['alpha'] }, + }); + simulator.roots.set('race-canvas', createRoot()); + try { + await simulator.start(); + simulator.expert.reset({ scenario: { participants: 'controlled-only' } }); + simulator.app.restart(); + expect(simulator.expert.reset({ scenario: { participants: 'all' } }).state.snapshot.cars.map((car) => car.id)) + .toEqual(['alpha', 'beta']); + simulator.restart({ drivers: [{ id: 'alpha', name: 'Alpha' }] }); + expect(simulator.expert.reset({ scenario: { participants: 'all' } }).state.snapshot.cars.map((car) => car.id)) + .toEqual(['alpha']); + } finally { + simulator.destroy(); + } + }); + + test.each([ + [{ trackGeneration: { profile: 'invalid-restart-profile' } }, 'Unsupported procedural track profile: invalid-restart-profile'], + [{ drivers: [{ id: 'beta', name: 'Beta' }] }, 'controlled driver does not exist: alpha'], + ])('failed restart %j preserves the active runtime and expert adapter for retry', async (nextOptions, message) => { + installPixiInit(); + F1SimulatorApp.prototype.createRaceSimulation.mockRestore(); + const simulator = new PaddockSimulatorController({ + seed: 17, trackSeed: 31, warmup: false, + drivers: [{ id: 'alpha', name: 'Alpha' }], + expert: { enabled: true, controlledDrivers: ['alpha'] }, + }); + simulator.roots.set('race-canvas', createRoot()); + try { + await simulator.start(); + const previousOptions = simulator.app.options; + const previousSimulation = simulator.app.sim; + const previousExpert = simulator.expert; + expect(() => simulator.restart(nextOptions)).toThrow(message); + expect(simulator.app.options).toBe(previousOptions); + expect(simulator.app.sim).toBe(previousSimulation); + expect(simulator.expert).toBe(previousExpert); + expect(simulator.expert.reset().state.snapshot.cars.map((car) => car.id)).toEqual(['alpha']); + expect(() => simulator.restart()).not.toThrow(); + } finally { + simulator.destroy(); + } + }); + + test('composable ready callbacks can use the fully initialized runtime API', async () => { + installPixiInit(); + F1SimulatorApp.prototype.createRaceSimulation.mockRestore(); + const setView = vi.spyOn(F1SimulatorApp.prototype, 'setView').mockReturnValue(true); + const onError = vi.fn(); + let readyState; + const simulator = new PaddockSimulatorController({ + seed: 17, trackSeed: 31, warmup: { enabled: false }, + totalLaps: 3, rules: { modules: { pitStops: { enabled: true } } }, + trackGeneration: { pitLane: { enabled: true } }, + drivers: [{ id: 'alpha', name: 'Alpha' }, { id: 'beta', name: 'Beta' }], + expert: { enabled: true, controlledDrivers: ['beta'] }, + onError, + onReady: ({ snapshot: readySnapshot }) => { + readyState = { snapshot: simulator.getSnapshot(), expert: simulator.expert, readySnapshot }; + simulator.selectDriver('beta'); + readyState.selectedId = simulator.app?.selectedId; + readyState.pitApplied = simulator.setPitIntent('beta', 1); + readyState.pitIntent = simulator.getPitIntent('beta'); + readyState.viewApplied = simulator.setView('race'); + readyState.expertSnapshot = simulator.expert?.getState().snapshot; + }, + }); + simulator.roots.set('race-canvas', createRoot()); + try { + await simulator.start(); + expect(readyState.snapshot?.cars.map((car) => car.id)).toEqual(['alpha', 'beta']); + expect(readyState.expert).toBe(simulator.expert); + expect(readyState.expertSnapshot?.cars).toHaveLength(2); + expect(readyState.selectedId).toBe('beta'); + expect(readyState.pitApplied).toBe(true); + expect(readyState.pitIntent).toBe(1); + expect(readyState.viewApplied).toBe(true); + expect(setView).toHaveBeenCalledWith('race'); + expect(onError).not.toHaveBeenCalled(); + } finally { + simulator.destroy(); + } + }); + + test.each(['onReady', 'onLoadingChange'])('composable %s may destroy without publishing a destroyed runtime', async (callback) => { + const { renderers } = installPixiInit(); + const onReady = vi.fn(); + const simulator = new PaddockSimulatorController({ + drivers: [{ id: 'alpha', name: 'Alpha' }], + onReady, + [callback]: (payload) => { + if (callback === 'onLoadingChange' && payload.phase !== 'ready') return; + simulator.destroy(); + }, + }); + simulator.roots.set('race-canvas', createRoot()); + await expect(simulator.start()).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + expect(simulator.app).toBeNull(); + expect(simulator.initializingApp).toBeNull(); + expect(simulator.startPromise).toBeNull(); + expect(renderers[0].destroy).toHaveBeenCalledTimes(1); + expect(onReady).not.toHaveBeenCalled(); + }); + + test.each(['onReady', 'onLoadingChange'])('composable %s may restart without stale startup state or ready data', async (callback) => { + installPixiInit(); + F1SimulatorApp.prototype.createRaceSimulation.mockRestore(); + const onError = vi.fn(); + let readySnapshot; + const simulator = new PaddockSimulatorController({ + seed: 17, trackSeed: 31, warmup: { enabled: false }, + drivers: [{ id: 'alpha', name: 'Alpha' }], totalLaps: 1, + onError, + onReady: ({ snapshot: value }) => { readySnapshot = value; }, + [callback]: (payload) => { + if (callback === 'onLoadingChange' && payload.phase !== 'ready') return; + simulator.restart({ totalLaps: 3 }); + if (callback === 'onReady') readySnapshot = payload.snapshot; + }, + }); + simulator.roots.set('race-canvas', createRoot()); + try { + await simulator.start(); + expect(onError).not.toHaveBeenCalled(); + expect(simulator.getSnapshot().totalLaps).toBe(3); + expect(readySnapshot.totalLaps).toBe(callback === 'onReady' ? 1 : 3); + expect(simulator.app.app.ticker.started).toBe(true); + expect(simulator.app.resizeHandler).toBeTypeOf('function'); + } finally { + simulator.destroy(); + } + }); + + test('an initializing loading callback shares the pending start and cannot use runtime methods', async () => { + const gate = deferred(); + const { init } = installPixiInit(gate.promise); + let nestedStart; + let earlyState; + let calls = 0; + const simulator = new PaddockSimulatorController({ + drivers: [{ id: 'alpha', name: 'Alpha' }], + onLoadingChange: ({ phase }) => { + if (phase !== 'initializing' || calls++ > 0) return; + nestedStart = simulator.start(); + earlyState = { snapshot: simulator.getSnapshot(), expert: simulator.expert, + pitApplied: simulator.setPitIntent('alpha', 1), viewApplied: simulator.setView('race') }; + try { simulator.restart(); } catch (error) { earlyState.restartError = error.message; } + }, + }); + simulator.roots.set('race-canvas', createRoot()); + const pending = simulator.start(); + try { + await vi.waitFor(() => expect(init).toHaveBeenCalled()); + expect(init).toHaveBeenCalledTimes(1); + expect(earlyState).toEqual({ snapshot: null, expert: null, pitApplied: false, viewApplied: false, + restartError: expect.stringContaining('Await start() before restarting') }); + gate.resolve(); + await expect(pending).resolves.toBe(simulator); + await expect(nestedStart).resolves.toBe(simulator); + } finally { + gate.resolve(); + await Promise.allSettled([pending, nestedStart]); + simulator.destroy(); + } + }); + + test.each(['destroy', 'restart'])('restart stops stale rendering when a snapshot callback calls %s', async (action) => { + installPixiInit(); + F1SimulatorApp.prototype.createRaceSimulation.mockRestore(); + F1SimulatorApp.prototype.updateDom.mockRestore(); + const createSimulation = F1SimulatorApp.prototype.createRaceSimulation; + let generation = 0; + vi.spyOn(F1SimulatorApp.prototype, 'createRaceSimulation').mockImplementation(function (...args) { + const simulation = createSimulation.apply(this, args); + if (++generation === 2) simulation.events.push({ type: 'restart-boundary', at: 0 }); + return simulation; + }); + const onError = vi.fn(); + const onRaceEvent = vi.fn((event) => { + if (event.type === 'restart-boundary') simulator[action](); + }); + const simulator = new PaddockSimulatorController({ + seed: 17, trackSeed: 31, warmup: { enabled: false }, + drivers: [{ id: 'alpha', name: 'Alpha' }], onRaceEvent, onError, + }); + simulator.roots.set('race-canvas', createRoot()); + try { + await simulator.start(); + F1SimulatorApp.prototype.renderInitialFrame.mockClear(); + expect(() => simulator.restart()).not.toThrow(); + expect(onRaceEvent).toHaveBeenCalledWith(expect.objectContaining({ type: 'restart-boundary' }), expect.any(Object)); + expect(onError).not.toHaveBeenCalled(); + expect(F1SimulatorApp.prototype.renderInitialFrame).toHaveBeenCalledTimes(action === 'destroy' ? 0 : 1); + expect(simulator.app === null).toBe(action === 'destroy'); + } finally { + simulator.destroy(); + } + }); + test('composable cancellation settles before a new start can initialize normally', async () => { const gate = deferred(); const { init, renderers } = installPixiInit(gate.promise); @@ -303,7 +630,9 @@ describe('browser startup resource lifecycle', () => { simulator.roots.set('race-canvas', createRoot()); const pending = simulator.start(); const rejection = expect(pending).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + await vi.waitFor(() => expect(init).toHaveBeenCalledTimes(1)); simulator.destroy(); + expect(() => simulator.restart()).toThrow('Await start() before restarting'); gate.resolve(); await rejection; expect(simulator.startPromise).toBeNull(); diff --git a/src/__tests__/startupTasks.test.js b/src/__tests__/startupTasks.test.js new file mode 100644 index 0000000..8bfa200 --- /dev/null +++ b/src/__tests__/startupTasks.test.js @@ -0,0 +1,75 @@ +import { describe, expect, test, vi } from 'vitest'; +import { createStartupCheckpoint } from '../app/runtime/startupTasks.js'; +import { RuntimeStartupCancelledError } from '../app/runtime/pixiStartupLifecycle.js'; + +describe('browser startup task checkpoints', () => { + test('forced checkpoints cross a real timer task instead of only yielding microtasks', async () => { + const order = []; + const checkpoint = createStartupCheckpoint({ destroyed: false }); + setTimeout(() => order.push('other browser task'), 0); + const pending = checkpoint(true).then(() => order.push('startup resumed')); + + await Promise.resolve(); + expect(order).toEqual([]); + await pending; + expect(order).toEqual(['other browser task', 'startup resumed']); + }); + + test('yields at the budget and resets the budget when the task resumes', async () => { + let now = 0; + let resume; + const yieldTask = vi.fn(() => new Promise((resolve) => { resume = resolve; })); + const checkpoint = createStartupCheckpoint({ destroyed: false }, { now: () => now, yieldTask }); + + now = 7.99; + expect(checkpoint()).toBeNull(); + expect(yieldTask).not.toHaveBeenCalled(); + now = 8; + const pending = checkpoint(); + expect(yieldTask).toHaveBeenCalledTimes(1); + now = 100; + resume(); + await pending; + + now = 107; + expect(checkpoint()).toBeNull(); + now = 108; + const next = checkpoint(); + expect(yieldTask).toHaveBeenCalledTimes(2); + resume(); + await next; + }); + + test('an explicit budget and forced yield govern short startup phases', async () => { + let now = 0; + const yieldTask = vi.fn(() => Promise.resolve()); + const checkpoint = createStartupCheckpoint({ destroyed: false }, { budgetMs: 3, now: () => now, yieldTask }); + now = 2; + expect(checkpoint()).toBeNull(); + await checkpoint(true); + expect(yieldTask).toHaveBeenCalledTimes(1); + now = 5; + await checkpoint(); + expect(yieldTask).toHaveBeenCalledTimes(2); + }); + + test('cancellation rejects before scheduling work even when the budget remains', () => { + const app = { destroyed: false }; + const yieldTask = vi.fn(); + const checkpoint = createStartupCheckpoint(app, { now: () => 0, yieldTask }); + app.destroyed = true; + expect(() => checkpoint()).toThrow(RuntimeStartupCancelledError); + expect(() => checkpoint(true)).toThrow(RuntimeStartupCancelledError); + expect(yieldTask).not.toHaveBeenCalled(); + }); + + test('cancellation during the task boundary prevents startup from resuming', async () => { + const app = { destroyed: false }; + const checkpoint = createStartupCheckpoint(app); + const resumed = vi.fn(); + const pending = checkpoint(true).then(resumed); + app.destroyed = true; + await expect(pending).rejects.toBeInstanceOf(RuntimeStartupCancelledError); + expect(resumed).not.toHaveBeenCalled(); + }); +}); diff --git a/src/api/PaddockSimulatorController.js b/src/api/PaddockSimulatorController.js index e62d5c0..8567339 100644 --- a/src/api/PaddockSimulatorController.js +++ b/src/api/PaddockSimulatorController.js @@ -1,5 +1,6 @@ import { createViewControlsMarkup } from '../ui/viewControlsTemplate.js'; import { F1SimulatorApp } from '../app/F1SimulatorApp.js'; +import { RuntimeStartupCancelledError } from '../app/runtime/pixiStartupLifecycle.js'; import { MountedSimulatorComponents } from './MountedSimulatorComponents.js'; import { createRaceDataPanelMarkup, @@ -132,20 +133,26 @@ export class PaddockSimulatorController { this.compositeRoot.applyCssVariables(); const app = new F1SimulatorApp(this.compositeRoot, this.options); this.initializingApp = app; - const startPromise = (async () => { + // Publish the pending operation before init can call back into the host. + const startPromise = Promise.resolve().then(async () => { try { - await app.init(); - if (this.initializingApp !== app) { - throw new Error('PaddockJS start() was cancelled before initialization completed.'); + await app.init({ + onInitialized: () => { + if (this.initializingApp !== app) throw new RuntimeStartupCancelledError(); + this.app = app; + this.initializingApp = null; + }, + }); + if (this.app !== app) { + throw new RuntimeStartupCancelledError(); } - this.app = app; - this.initializingApp = null; return this; } catch (error) { + if (this.app === app) this.app = null; app.destroy(); throw error; } - })(); + }); this.startPromise = startPromise; try { return await startPromise; @@ -186,7 +193,7 @@ export class PaddockSimulatorController { } restart(nextOptions = {}) { - if (this.startPromise || this.initializingApp) { + if (this.initializingApp || (this.startPromise && !this.app)) { throw new Error('Cannot restart PaddockJS while start() is initializing. Await start() before restarting.'); } const currentOptions = this.app ? this.syncOptionsFromRunningApp() : this.options; diff --git a/src/app/BrowserExpertAdapter.js b/src/app/BrowserExpertAdapter.js index e55e431..c1f9d6f 100644 --- a/src/app/BrowserExpertAdapter.js +++ b/src/app/BrowserExpertAdapter.js @@ -2,27 +2,28 @@ import { createEnvironmentRuntime } from '../environment/runtime.js'; import { resolveEnvironmentOptions } from '../environment/options.js'; import { createBrowserExpertExternalRendererBridge } from './BrowserExpertExternalRenderer.js'; +export function resolveBrowserExpertOptions(appOptions, expertOptions = {}) { + const options = resolveEnvironmentOptions({ + ...appOptions, + ...expertOptions, + drivers: expertOptions.drivers ?? appOptions.configuredDrivers ?? appOptions.drivers, + controlledDrivers: expertOptions.controlledDrivers, + }); + if (options.result.stateOutput !== 'none') return options; + return { + ...options, + result: { + ...options.result, + stateOutput: 'minimal', + }, + }; +} + export function createBrowserExpertAdapter(app, expertOptions = {}) { let resolvedOptions = resolveBrowserExpertOptions(app.options, expertOptions); let frameRenderSuppressed = false; const externalRenderer = createBrowserExpertExternalRendererBridge(app); - function resolveBrowserExpertOptions(appOptions, nextExpertOptions = {}) { - const options = resolveEnvironmentOptions({ - ...appOptions, - ...nextExpertOptions, - controlledDrivers: nextExpertOptions.controlledDrivers, - }); - if (options.result.stateOutput !== 'none') return options; - return { - ...options, - result: { - ...options.result, - stateOutput: 'minimal', - }, - }; - } - function renderableSnapshot(result) { return result?.state?.snapshot ?? app.sim?.snapshotObservation?.() ?? app.sim?.snapshot?.() ?? null; } @@ -46,8 +47,9 @@ export function createBrowserExpertAdapter(app, expertOptions = {}) { app.sim = nextSim; }, createSimulation(nextOptions) { + const sim = app.createRaceSimulation(nextOptions); app.applyExpertOptions(nextOptions); - return app.createRaceSimulation(nextOptions); + return sim; }, getOptions: () => resolvedOptions, setOptions(nextOptions) { diff --git a/src/app/F1SimulatorApp.js b/src/app/F1SimulatorApp.js index e6e203a..792acd5 100644 --- a/src/app/F1SimulatorApp.js +++ b/src/app/F1SimulatorApp.js @@ -17,7 +17,7 @@ import { isTimingPanelDisclosureMode, syncTimingPanelDisclosureState, } from './controls/workbenchDisclosure.js'; -import { createBrowserExpertAdapter } from './BrowserExpertAdapter.js'; +import { createBrowserExpertAdapter, resolveBrowserExpertOptions } from './BrowserExpertAdapter.js'; import { HostLifecycleEmitter } from './HostLifecycleEmitter.js'; import { installLayoutSupport } from './layoutSupport.js'; import { installRaceOverlayClearanceSupport } from './raceOverlayClearanceSupport.js'; @@ -28,7 +28,7 @@ import { DrsTrailRenderer } from './rendering/drsTrailRenderer.js'; import { renderExpertSensorRays } from './rendering/expertSensorRenderer.js'; import { PitLaneStatusRenderer } from './rendering/pitLaneStatusRenderer.js'; import { ReplayGhostRenderer } from './rendering/replayGhostRenderer.js'; -import { renderTrackSurface } from './rendering/trackRenderer.js'; +import { renderTrackSurface, renderTrackSurfaceAsync } from './rendering/trackRenderer.js'; import { getTimingOrderKey, getTimingPenaltyKey, @@ -65,6 +65,8 @@ import { observeRuntimeVisibility, syncRuntimeTicker } from './runtime/runtimeVi import { configureRuntimeTicker, domUpdateIntervalForSpeed, timingUpdateIntervalForSpeed } from './runtime/runtimeTiming.js'; import { assertRuntimeStartupActive, createPixiStartupLifecycle, RuntimeStartupCancelledError } from './runtime/pixiStartupLifecycle.js'; import { normalizeWarmupOptions } from '../simulation/warmup/runtimeWarmup.js'; +import { createStartupCheckpoint } from './runtime/startupTasks.js'; +import { prepareBrowserSimulation } from './runtime/browserSimulationStartup.js'; const SIMULATION_SPEED_STEPS = [1, 2, 3, 4, 5, 10]; @@ -151,6 +153,7 @@ export class F1SimulatorApp { Object.assign(this, querySimulatorDom(root)); this.abortController = new AbortController(); this.destroyed = false; + this.runtimeSceneReady = false; this.resizeHandler = null; this.layoutResizeObserver = null; this.layoutSupportCleanup = installLayoutSupport(root); @@ -246,7 +249,7 @@ export class F1SimulatorApp { ); } - async init() { + async init({ onInitialized } = {}) { this.emitHostCallback('onLoadingChange', { loading: true, phase: 'initializing' }); try { assertRuntimeStartupActive(this); @@ -254,7 +257,10 @@ export class F1SimulatorApp { throw new Error('F1 simulator canvas host is missing.'); } - this.sim = this.createRaceSimulation(); + const checkpoint = createStartupCheckpoint(this); + const simulation = await prepareBrowserSimulation(this, checkpoint); + assertRuntimeStartupActive(this); + this.sim = simulation; const application = new Application(); const lifecycleEmitter = this.hostLifecycle; const startup = createPixiStartupLifecycle(application, (error) => { @@ -277,6 +283,7 @@ export class F1SimulatorApp { this.sceneScroll = new SceneScrollController(this, this.abortController.signal); this.worldLayer = new Container(); + this.worldLayer.renderable = false; this.drsLayer = new Container(); this.trailLayer = new Graphics(); this.sensorLayer = new Graphics(); @@ -298,26 +305,29 @@ export class F1SimulatorApp { this.replayGhostLayer, this.carLayer, ); + await checkpoint(true); + await this.renderStartupTrack(checkpoint); + await checkpoint(true); this.createCars(); if (this.options.gridWalk?.enabled) { this.gridWalk = new GridWalkController(this); - this.gridWalk.sync({ updateTicker: false }); + this.gridWalk.sync({ updateTicker: false, render: false }); } + await checkpoint(true); this.bindControls(); this.syncTimingPanelDisclosureState(); - this.renderTrack(); const snapshot = this.sim.snapshot(); this.updateDom(snapshot); + assertRuntimeStartupActive(this); this.lastDomUpdateTime = performance.now(); if (this.expertMode) { this.expert = createBrowserExpertAdapter(this, this.options.expert); } + this.runtimeSceneReady = true; + this.worldLayer.renderable = true; + this.gridWalk?.sync({ updateTicker: false, render: false }); this.renderInitialFrame(snapshot); this.completeComponentLoading(); - this.emitHostCallback('onLoadingChange', { loading: false, phase: 'ready' }); - assertRuntimeStartupActive(this); - this.emitHostCallback('onReady', { snapshot }); - assertRuntimeStartupActive(this); this.resizeHandler = () => { this.syncTimingPanelDisclosureState(); this.renderSourceSnapshotBuffer ??= {}; @@ -333,6 +343,13 @@ export class F1SimulatorApp { this.app.ticker.add(this.tickerCallback); this.observeRuntimeVisibility(); } + // Ready callbacks can operate or restart the runtime. Finish setup and + // let its owner publish it before invoking host code. + onInitialized?.(); + this.emitHostCallback('onLoadingChange', { loading: false, phase: 'ready' }); + assertRuntimeStartupActive(this); + this.emitHostCallback('onReady', { snapshot: this.sim.snapshot() }); + assertRuntimeStartupActive(this); } catch (error) { const cancelled = this.destroyed; if (!(error instanceof RuntimeStartupCancelledError) && !this.destroyed) { @@ -523,6 +540,10 @@ export class F1SimulatorApp { } renderInitialFrame(snapshot) { + if (this.gridWalk?.active) { + this.gridWalk.render(); + return; + } const renderSnapshot = interpolateRenderSnapshotInto(this.renderSnapshotBuffer, snapshot, 0); this.resizeRendererToCanvasHost(); this.sceneScroll?.sync(); @@ -645,6 +666,16 @@ export class F1SimulatorApp { }); } + async renderStartupTrack(checkpoint) { + this.pitLaneStatusRenderer.reset(); + this.cameraController.invalidateTrackCaches(); + await renderTrackSurfaceAsync({ + drsLayer: this.drsLayer, sensorLayer: this.sensorLayer, + pitLaneStatusLayer: this.pitLaneStatusLayer, trackAsset: this.trackAsset, + snapshot: this.sim.snapshot(), + }, checkpoint); + } + renderPitLaneStatus(snapshot) { this.pitLaneStatusRenderer.render(snapshot, this.pitLaneStatusLayer); } @@ -1108,6 +1139,7 @@ export class F1SimulatorApp { this.options = { ...this.options, ...nextOptions, + configuredDrivers: nextOptions.configuredDrivers ?? nextOptions.drivers ?? this.options.configuredDrivers, ui: { ...this.options.ui, ...(nextOptions.ui ?? {}), @@ -1146,9 +1178,21 @@ export class F1SimulatorApp { if (hasOwnOption(nextOptions, 'expert') && expertOptionsChanged(nextOptions.expert, this.options.expert)) { throw new Error('PaddockJS restart() does not support changing expert mode. Destroy and mount a new simulator with the new expert options.'); } + const trackSeed = hasOwnOption(nextOptions, 'trackSeed') + ? nextOptions.trackSeed ?? createRuntimeSeed() + : this.trackSeed; + const nextAppOptions = { + ...this.options, + ...nextOptions, + trackSeed, + configuredDrivers: nextOptions.configuredDrivers ?? nextOptions.drivers ?? this.options.configuredDrivers, + }; + if (this.expertMode) resolveBrowserExpertOptions(nextAppOptions, nextAppOptions.expert); + // Validate and construct the replacement before releasing the active race. + const nextSimulation = this.createRaceSimulation(nextAppOptions); this.expert?.destroy?.(); this.expert = null; - this.applyExpertOptions(nextOptions); + this.applyExpertOptions(hasOwnOption(nextOptions, 'trackSeed') ? { ...nextOptions, trackSeed } : nextOptions); this.raceDataBannerConfig = this.options.ui?.raceDataBanners ?? this.raceDataBannerConfig; this.penaltyBannerEnabled = Boolean(this.options.ui?.penaltyBanners); this.timingPenaltyBadgesEnabled = Boolean(this.options.ui?.timingPenaltyBadges); @@ -1158,7 +1202,7 @@ export class F1SimulatorApp { this.selectedId = this.drivers[0]?.id ?? null; this.lastThemeContextKey = null; this.syncThemeContext(); - this.sim = this.createRaceSimulation(); + this.sim = nextSimulation; this.gridWalk?.destroy(); this.gridWalk = null; this.gridWalk = this.options.gridWalk?.enabled ? new GridWalkController(this) : null; @@ -1179,8 +1223,10 @@ export class F1SimulatorApp { this.lastStewardMessageKey = null; this.hostLifecycle.reset(); this.renderTrack(); - const snapshot = this.sim.snapshot(); + const simulation = this.sim; + const snapshot = simulation.snapshot(); this.updateDom(snapshot); + if (this.destroyed || this.sim !== simulation) return; this.lastDomUpdateTime = performance.now(); // Restart may create fresh surfaces around the already-ready renderer. // Complete their loading state before measuring the final display frame. @@ -1238,6 +1284,7 @@ export class F1SimulatorApp { destroy() { if (this.destroyed) return; this.destroyed = true; + this.runtimeSceneReady = false; const lifecycleEmitter = this.hostLifecycle; const cleanupErrors = []; this.destroyCleanupErrors = cleanupErrors; @@ -1267,6 +1314,9 @@ export class F1SimulatorApp { if (this.app && this.tickerCallback) { cleanup(() => this.app.ticker.remove(this.tickerCallback)); } + this.tickerCallback = null; + this.resizeHandler = null; + this.visibilityChangeHandler = null; cleanup(() => this.expert?.destroy?.()); this.expert = null; cleanup(() => this.replayGhostRenderer?.destroy?.()); diff --git a/src/app/controls/SimulatorViewControls.js b/src/app/controls/SimulatorViewControls.js index 9e88894..fcebe20 100644 --- a/src/app/controls/SimulatorViewControls.js +++ b/src/app/controls/SimulatorViewControls.js @@ -1,29 +1,31 @@ // Separately mounted controls share one runtime view; they never own race state. export class SimulatorViewControls { - constructor(root, onView, signal) { + constructor(root, onView, signal, enabled = true) { this.surfaces = [...root.querySelectorAll('[data-paddock-component="view-controls"]')]; this.buttons = this.surfaces.flatMap((surface) => [...surface.querySelectorAll('[data-grid-view]')]); this.toggles = this.surfaces.flatMap((surface) => [...surface.querySelectorAll('[data-grid-toggle]')]); this.view = this.buttons.find((button) => button.getAttribute('aria-pressed') === 'true')?.dataset.gridView ?? 'race'; for (const button of this.buttons) { button.addEventListener('click', () => onView(button.dataset.gridView), { signal }); - button.disabled = false; + button.disabled = !enabled; } for (const button of this.toggles) { button.addEventListener('click', () => onView(this.view === 'race' ? 'grid-walk' : 'race'), { signal }); - button.disabled = false; + button.disabled = !enabled; } for (const surface of this.surfaces) surface.hidden = false; } - update(view, variant = 'switch') { + update(view, variant = 'switch', enabled = true) { this.view = view; const toggle = variant === 'toggle'; for (const button of this.buttons) { + button.disabled = !enabled; button.hidden = toggle; button.setAttribute('aria-pressed', String(button.dataset.gridView === view)); } for (const button of this.toggles) { + button.disabled = !enabled; button.hidden = !toggle; button.dataset.gridAction = view === 'grid-walk' ? 'start' : 'stop'; const label = button.querySelector?.('[data-control-label]') ?? button; diff --git a/src/app/gridWalk/GridWalkController.js b/src/app/gridWalk/GridWalkController.js index afdb67c..c01c67f 100644 --- a/src/app/gridWalk/GridWalkController.js +++ b/src/app/gridWalk/GridWalkController.js @@ -8,6 +8,7 @@ import { GridWalkLabels } from './gridWalkLabels.js'; import { GridWalkProjectBanner } from './gridWalkProjectBanner.js'; import { GridWalkLayout } from './gridWalkLayout.js'; import { SimulatorViewControls } from '../controls/SimulatorViewControls.js'; +import { pointAt } from '../../simulation/track/trackModel.js'; // Coordinates lifecycle and scene presentation. Each UI/input component owns // its own actions and geometry; none owns or steps the simulation. @@ -23,9 +24,9 @@ export class GridWalkController { const cars = this.session.snapshot.cars; wrapper.innerHTML = createGridWalkMarkup(app.drivers, cars, app.options.ui); this.element = wrapper.firstElementChild; - const select = (id) => app.selectCar(id, { focus: true }); + const select = (id) => { if (app.runtimeSceneReady !== false) app.selectCar(id, { focus: true }); }; const { signal } = this.abort; - this.viewControls = new SimulatorViewControls(app.root, (view) => this.setView(view), signal); + this.viewControls = new SimulatorViewControls(app.root, (view) => this.setView(view), signal, app.runtimeSceneReady !== false); this.controls = new GridWalkControls(this.element, { onSelect: select, onMove: (direction) => this.move(direction), }, signal); @@ -36,10 +37,13 @@ export class GridWalkController { this.sceneLabels.appendChild(this.labelGroup); app.sceneScroll.surface.viewport.appendChild(this.sceneLabels); this.banner = new GridWalkProjectBanner(this.element, () => this.closeProjectBanner(), signal, this.panel); - this.camera = new GridWalkCamera(cars); + this.camera = new GridWalkCamera(cars, { + initialPosition: app.options.gridWalk.initialPosition, + startLine: pointAt(app.sim.track, 0), + }); this.layout = new GridWalkLayout({ element: this.element, panel: this.panel, canvasHost: app.canvasHost, root: app.root }); this.navigation = new GridWalkNavigation({ host: app.canvasHost, surface: this.panel, - isEnabled: () => this.active && !this.session.clearing, + isEnabled: () => app.runtimeSceneReady !== false && this.active && !this.session.clearing, getOrientation: () => this.orientation, onPan: (delta) => { if (!this.camera.pan(delta)) return false; @@ -55,6 +59,7 @@ export class GridWalkController { }, { signal }); this.crew = new GridWalkCrew(app.worldLayer, cars); this.panel.appendChild(this.element); + this.layout.observe(() => { if (this.active && app.runtimeSceneReady !== false) this.render(); }); } get active() { return this.session.active; } @@ -62,6 +67,7 @@ export class GridWalkController { get needsAnimation() { return this.active && this.motion; } setView(view) { + if (this.app.runtimeSceneReady === false) return false; if (!this.session.setView(view, this.motion)) return false; this.navigation.cancel(); // Preserve the fixed-step remainder; only discard time spent browsing. @@ -94,28 +100,34 @@ export class GridWalkController { } move(direction) { + if (this.app.runtimeSceneReady === false) return; const cars = this.session.snapshot.cars; const index = cars.findIndex((car) => car.id === this.app.selectedId); this.app.selectCar(cars[(index + direction + cars.length) % cars.length].id, { focus: true }); } - sync({ updateTicker = true } = {}) { + sync({ updateTicker = true, render = true } = {}) { const { app, session } = this; this.navigation.sync(); this.panel.dataset.gridWalkActive = String(this.active); this.element.dataset.view = session.view; this.controls.update(session, app.selectedId); - this.viewControls.update(session.view, app.options.ui.viewControls); + const ready = app.runtimeSceneReady !== false; + this.element.inert = !ready; + this.sceneLabels.inert = !ready; + this.viewControls.update(session.view, app.options.ui.viewControls, ready); this.labelGroup.hidden = !this.active || session.clearing; this.banner.update({ active: this.active, clearing: session.clearing, enabled: app.isRaceDataBannerEnabled('project'), car: session.snapshot.cars.find((car) => car.id === app.selectedId), drivers: app.drivers, options: app.options, presentation: app.driverById.get(app.selectedId).presentation }); for (const layer of [app.trailLayer, app.sensorLayer, app.pitLaneStatusLayer]) if (layer) layer.visible = !this.active; this.syncLayout(); - if (!this.active) app.syncTimingPanelDisclosureState(); - if (this.active) this.render(); - else { + if (!this.active) { this.crew.container.visible = false; + app.syncTimingPanelDisclosureState(); + } + if (render && this.active) this.render(); + else if (render) { app.sceneScroll.sync(); app.syncRendererToCurrentLayout({ render: true }); } @@ -135,7 +147,8 @@ export class GridWalkController { this.orientation = orientation; this.element.dataset.orientation = this.orientation; this.element.dataset.compactControls = String(width < 600 && height < 420); - const area = this.layout.measure(this.banner.measure(width, height)); + const scale = app.canvasHost.getBoundingClientRect().height / height || 1; + const area = this.layout.measure(this.banner.measure(width, height, scale)); this.element.dataset.compactLabels = String(area.bottom - area.top < 164); this.sceneLabels.dataset.compactLabels = this.element.dataset.compactLabels; this.frame = this.camera.update({ selectedId: app.selectedId, width, height, orientation: this.orientation, area }); diff --git a/src/app/gridWalk/gridWalkCamera.js b/src/app/gridWalk/gridWalkCamera.js index 26212c2..0c8887a 100644 --- a/src/app/gridWalk/gridWalkCamera.js +++ b/src/app/gridWalk/gridWalkCamera.js @@ -14,10 +14,9 @@ function gridAxes(cars) { return { heading, cos, sin, along, across }; } -// A camera has one position along the original grid. Selection, orientation and -// container sizing never introduce a second axis or a different framing mode. +// Framing and panning share one position along the original grid. export function gridWalkCameraFrame({ cars, selectedId, width, height, orientation, bannerSize = 0, area, - position = null }) { + position = null, initialPosition = 'selected', startLine = null, bounds = null }) { const { heading, cos, sin, along, across } = gridAxes(cars); const horizontal = orientation === 'horizontal'; area ??= { left: 16, top: width < 600 ? 144 : 82, right: width - 16, bottom: height - 16 - bannerSize }; @@ -30,9 +29,13 @@ export function gridWalkCameraFrame({ cars, selectedId, width, height, orientati (horizontal ? availableHeight : availableWidth) / (crossSpan + (horizontal ? 180 : 210)), 2.4, )); const selected = Math.max(0, cars.findIndex((car) => car.id === selectedId)); - const minPosition = Math.min(...along) - spacing; - const maxPosition = Math.max(...along) + spacing; - const activePosition = Math.max(minPosition, Math.min(maxPosition, position ?? along[selected])); + const startAligned = initialPosition === 'start-line' && startLine + ? startLine.x * cos + startLine.y * sin - ((horizontal ? availableWidth : availableHeight) / 2 - 24) / scale + : null; + // Short grids may need extra camera travel to place the line at the edge. + const minPosition = Math.min(Math.min(...along) - spacing, startAligned ?? Infinity, bounds?.minPosition ?? Infinity); + const maxPosition = Math.max(Math.max(...along) + spacing, startAligned ?? -Infinity, bounds?.maxPosition ?? -Infinity); + const activePosition = Math.max(minPosition, Math.min(maxPosition, position ?? startAligned ?? along[selected])); const cross = (Math.min(...across) + Math.max(...across)) / 2; const center = { x: activePosition * cos - cross * sin, y: activePosition * sin + cross * cos }; const rotation = (horizontal ? 0 : -Math.PI / 2) - heading; @@ -62,16 +65,29 @@ export function projectGridPoint(frame, point) { } export class GridWalkCamera { - constructor(cars) { this.cars = cars; this.position = null; } + constructor(cars, { initialPosition = 'selected', startLine = null } = {}) { + this.cars = cars; + this.initialPosition = initialPosition; + this.startLine = startLine; + this.position = null; + this.interacted = false; + this.bounds = null; + } update(input) { - this.frame = gridWalkCameraFrame({ ...input, cars: this.cars, position: this.position }); + const alignStart = this.initialPosition === 'start-line'; + this.frame = gridWalkCameraFrame({ ...input, cars: this.cars, + initialPosition: this.initialPosition, startLine: this.startLine, bounds: this.bounds, + position: alignStart && !this.interacted ? null : this.position }); this.position = this.frame.position; + if (alignStart && this.interacted) this.bounds = { minPosition: this.frame.minPosition, maxPosition: this.frame.maxPosition }; return this.frame; } pan(delta) { if (!this.frame || !Number.isFinite(delta) || !delta) return false; + this.interacted = true; + if (this.initialPosition === 'start-line') this.bounds = { minPosition: this.frame.minPosition, maxPosition: this.frame.maxPosition }; const sign = this.frame.orientation === 'horizontal' ? -1 : 1; const position = Math.max(this.frame.minPosition, Math.min(this.frame.maxPosition, this.position + sign * delta / this.frame.scale)); @@ -83,6 +99,7 @@ export class GridWalkCamera { focus(id) { const index = this.cars.findIndex((car) => car.id === id); if (index < 0) return; + this.interacted = true; this.position = gridAxes(this.cars).along[index]; } } diff --git a/src/app/gridWalk/gridWalkLayout.js b/src/app/gridWalk/gridWalkLayout.js index 425759c..df870f0 100644 --- a/src/app/gridWalk/gridWalkLayout.js +++ b/src/app/gridWalk/gridWalkLayout.js @@ -1,3 +1,5 @@ +import { createRafScheduler } from '../layoutScheduler.js'; + // Owns overlay geometry and restoration of any Race chrome it covers. export class GridWalkLayout { constructor({ element, panel, canvasHost, root }) { @@ -5,6 +7,16 @@ export class GridWalkLayout { this.coveredTowers = new Map(); } + observe(onResize) { + if (typeof ResizeObserver !== 'function') return; + this.scheduler = createRafScheduler(onResize); + this.resizeObserver = new ResizeObserver(this.scheduler.queue); + for (const selector of ['[data-grid-header]', '[data-grid-project-banner]']) { + const element = this.element.querySelector(selector); + if (element) this.resizeObserver.observe(element); + } + } + update(active) { this.active = active; this.syncCoveredTowers(); @@ -13,8 +25,10 @@ export class GridWalkLayout { measure(bannerSize) { const canvas = this.canvasHost.getBoundingClientRect(); const header = this.element.querySelector('[data-grid-header]').getBoundingClientRect(); - return { left: 16, right: canvas.width - 16, - top: Math.max(16, header.bottom - canvas.top + 12), bottom: canvas.height - 16 - bannerSize }; + const scale = canvas.height / this.canvasHost.clientHeight || 1; + return { left: 16, right: this.canvasHost.clientWidth - 16, + top: Math.max(16, (header.bottom - canvas.top) / scale + 12), + bottom: this.canvasHost.clientHeight - 16 - bannerSize }; } syncCoveredTowers() { @@ -37,6 +51,8 @@ export class GridWalkLayout { } destroy() { + this.resizeObserver?.disconnect(); + this.scheduler?.cancel(); for (const [tower, wasInert] of this.coveredTowers) { tower.classList.remove('is-grid-walk-covered'); if (!wasInert) tower.removeAttribute('inert'); diff --git a/src/app/gridWalk/gridWalkProjectBanner.js b/src/app/gridWalk/gridWalkProjectBanner.js index abd0c9d..423eba0 100644 --- a/src/app/gridWalk/gridWalkProjectBanner.js +++ b/src/app/gridWalk/gridWalkProjectBanner.js @@ -26,7 +26,7 @@ export class GridWalkProjectBanner { renderRaceData({ car, drivers, options, presentation, readouts: this.bindings }); } - measure(width, height) { + measure(width, height, scale = 1) { if (!this.enabled) return 0; this.element.classList.toggle('race-data-panel--standalone', width < 600); this.element.style.maxHeight = `${Math.max(72, height * 0.34)}px`; @@ -34,7 +34,7 @@ export class GridWalkProjectBanner { // zoom or shift the grid under the newly restored focus. const hidden = this.element.hidden; this.element.hidden = false; - const size = this.element.getBoundingClientRect().height; + const size = this.element.getBoundingClientRect().height / scale; this.element.hidden = hidden; return size + 24; } diff --git a/src/app/readouts/readoutFormatters.js b/src/app/readouts/readoutFormatters.js index 0fadca4..07ca9b6 100644 --- a/src/app/readouts/readoutFormatters.js +++ b/src/app/readouts/readoutFormatters.js @@ -8,13 +8,13 @@ export function getTireClass(tire) { export function formatTelemetryTime(value) { if (!Number.isFinite(value)) return '--'; - const clamped = Math.max(0, value); - if (clamped >= 60) { - const minutes = Math.floor(clamped / 60); - const seconds = clamped - minutes * 60; + const rounded = Number(Math.max(0, value).toFixed(3)); + if (rounded >= 60) { + const minutes = Math.floor(rounded / 60); + const seconds = rounded - minutes * 60; return `${minutes}:${seconds.toFixed(3).padStart(6, '0')}`; } - return `${clamped.toFixed(3)}s`; + return `${rounded.toFixed(3)}s`; } export function setPerformanceClass(node, status) { diff --git a/src/app/rendering/displayUtils.js b/src/app/rendering/displayUtils.js index 2e0013a..ba217e1 100644 --- a/src/app/rendering/displayUtils.js +++ b/src/app/rendering/displayUtils.js @@ -1,9 +1,15 @@ +import { Color } from 'pixi.js'; + const TINT_BY_COLOR = new Map(); export function colorToTint(color) { if (TINT_BY_COLOR.has(color)) return TINT_BY_COLOR.get(color); - const tint = Number.parseInt(String(color ?? '').replace('#', ''), 16); - const normalizedTint = Number.isFinite(tint) ? tint : 0xffffff; + let normalizedTint = 0xffffff; + try { + normalizedTint = new Color(color ?? 0xffffff).toNumber(); + } catch { + // Keep unavailable or context-dependent CSS colors on the visible fallback. + } TINT_BY_COLOR.set(color, normalizedTint); return normalizedTint; } diff --git a/src/app/rendering/trackRenderer.js b/src/app/rendering/trackRenderer.js index 7f32593..0dd323e 100644 --- a/src/app/rendering/trackRenderer.js +++ b/src/app/rendering/trackRenderer.js @@ -10,6 +10,20 @@ export function renderTrackSurface({ drsLayer, sensorLayer, pitLaneStatusLayer, trackAsset.render(track); + renderDrsZones(drsLayer, track); +} + +export async function renderTrackSurfaceAsync({ drsLayer, sensorLayer, pitLaneStatusLayer, trackAsset, snapshot }, checkpoint) { + destroyDisplayChildren(drsLayer); + sensorLayer?.clear(); + pitLaneStatusLayer?.clear(); + await trackAsset.renderAsync(snapshot.track, { checkpoint }); + const pending = checkpoint(); + if (pending) await pending; + renderDrsZones(drsLayer, snapshot.track); +} + +function renderDrsZones(drsLayer, track) { track.drsZones.forEach((zone) => { const zoneLine = new Graphics(); const steps = 44; diff --git a/src/app/runtime/browserSimulationStartup.js b/src/app/runtime/browserSimulationStartup.js new file mode 100644 index 0000000..453e69b --- /dev/null +++ b/src/app/runtime/browserSimulationStartup.js @@ -0,0 +1,11 @@ +import { createProceduralTrackAsync } from '../../simulation/track/proceduralTrack.js'; + +export async function prepareBrowserSimulation(app, checkpoint) { + await checkpoint(true); + // Populate the existing immutable geometry cache cooperatively. The normal + // simulation factory still owns warmup, RNG and mutable per-race state. + await createProceduralTrackAsync(app.options.trackSeed ?? app.trackSeed, + app.options.trackGeneration, { checkpoint }); + await checkpoint(true); + return app.createRaceSimulation(); +} diff --git a/src/app/runtime/startupTasks.js b/src/app/runtime/startupTasks.js new file mode 100644 index 0000000..a638301 --- /dev/null +++ b/src/app/runtime/startupTasks.js @@ -0,0 +1,18 @@ +import { assertRuntimeStartupActive } from './pixiStartupLifecycle.js'; + +// A browser task boundary allows input and rendering; a microtask does not. +export function createStartupCheckpoint(app, { + budgetMs = 8, + now = () => performance.now(), + yieldTask = () => new Promise((resolve) => setTimeout(resolve, 0)), +} = {}) { + let startedAt = now(); + return (force = false) => { + assertRuntimeStartupActive(app); + if (!force && now() - startedAt < budgetMs) return null; + return Promise.resolve(yieldTask()).then(() => { + assertRuntimeStartupActive(app); + startedAt = now(); + }); + }; +} diff --git a/src/config/defaultOptions.js b/src/config/defaultOptions.js index a215f44..42c0cdf 100644 --- a/src/config/defaultOptions.js +++ b/src/config/defaultOptions.js @@ -73,6 +73,7 @@ export function resolveF1SimulatorOptions(options = {}) { gridWalk: { enabled: options.gridWalk?.enabled === true, initialView: options.gridWalk?.initialView === 'race' ? 'race' : 'grid-walk', + initialPosition: options.gridWalk?.initialPosition === 'start-line' ? 'start-line' : 'selected', ambientMotion: options.gridWalk?.ambientMotion !== false, }, ui, diff --git a/src/config/simulatorDefaults.js b/src/config/simulatorDefaults.js index a6a82e8..240bfc0 100644 --- a/src/config/simulatorDefaults.js +++ b/src/config/simulatorDefaults.js @@ -10,7 +10,7 @@ export const DEFAULT_F1_SIMULATOR_OPTIONS = { }, totalLaps: 10, initialCameraMode: 'leader', - gridWalk: { enabled: false, initialView: 'grid-walk', ambientMotion: true }, + gridWalk: { enabled: false, initialView: 'grid-walk', initialPosition: 'selected', ambientMotion: true }, title: 'F1 Simulator Lab', kicker: 'Race Control', backLinkHref: 'projects.html', diff --git a/src/environment/options.js b/src/environment/options.js index a16a0ef..6327020 100644 --- a/src/environment/options.js +++ b/src/environment/options.js @@ -66,6 +66,8 @@ export function resolveEnvironmentOptions(options = {}) { ...resolved, physicsMode: normalizePhysicsMode(options.physicsMode), warmup: normalizeWarmupOptions(options.warmup, 'environment'), + // Partial resets must reselect participants from the full configured roster. + configuredDrivers: normalizedDrivers, drivers: participantDrivers, controlledDrivers, frameSkip: normalizePositiveInteger(options.frameSkip, DEFAULT_FRAME_SKIP, 'frameSkip'), diff --git a/src/environment/resetOptions.js b/src/environment/resetOptions.js index 0717063..7f0877d 100644 --- a/src/environment/resetOptions.js +++ b/src/environment/resetOptions.js @@ -1,7 +1,10 @@ import { mergeRayOptionOverrides } from './sensors/rayConfig.js'; export function mergeEnvironmentResetOptions(currentOptions, nextOptions = {}) { - return mergePlainObjects(currentOptions, nextOptions); + return mergePlainObjects({ + ...currentOptions, + drivers: currentOptions.configuredDrivers ?? currentOptions.drivers, + }, nextOptions); } const REPLACE_OBJECT_PATHS = new Set([ diff --git a/src/environment/runtime.js b/src/environment/runtime.js index b0c5d8a..3757610 100644 --- a/src/environment/runtime.js +++ b/src/environment/runtime.js @@ -40,8 +40,9 @@ export function createEnvironmentRuntime(host) { function reset(nextOptions = {}) { const options = resolveEnvironmentOptions(mergeEnvironmentResetOptions(host.getOptions(), nextOptions)); + const sim = host.createSimulation(options); host.setOptions(options); - host.setSimulation(host.createSimulation(options)); + host.setSimulation(sim); initializeControlledPitIntent(host); episodeState.step = 0; episodeState.previousSnapshot = null; diff --git a/src/index.d.ts b/src/index.d.ts index e599ca7..be78741 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -806,6 +806,7 @@ export type PaddockView = 'grid-walk' | 'race'; export interface GridWalkOptions { enabled?: boolean; initialView?: PaddockView; + initialPosition?: 'selected' | 'start-line'; ambientMotion?: boolean; } diff --git a/src/rendering/proceduralTrackAsset.js b/src/rendering/proceduralTrackAsset.js index 6852ce4..7eddda2 100644 --- a/src/rendering/proceduralTrackAsset.js +++ b/src/rendering/proceduralTrackAsset.js @@ -1,7 +1,8 @@ import { Container } from 'pixi.js'; import { WORLD } from '../simulation/track/trackModel.js'; import { destroyDisplayChildren } from './displayLifecycle.js'; -import { addAsphalt, addBarriers, addBorders, addBoundaryUnderlay, addGrass, addGravelRunoff, addKerbs } from './track/trackMaterialRenderer.js'; +import { addAsphalt, addBarriers, addBorderSteps, addBoundaryUnderlay, addGrass, addGravelRunoff, addKerbSteps } from './track/trackMaterialRenderer.js'; +import { finishTrackRenderSteps, finishTrackRenderStepsAsync } from './track/trackRenderSteps.js'; import { addPitLane, addPitLaneRunoff } from './track/pitLaneRenderer.js'; import { addStartingGrid } from './track/gridRenderer.js'; import { addFinishLine } from './track/finishLineRenderer.js'; @@ -17,17 +18,35 @@ export class ProceduralTrackAsset { } render(track) { + finishTrackRenderSteps(this.renderSteps(track)); + } + + async renderAsync(track, { checkpoint }) { + await finishTrackRenderStepsAsync(this.renderSteps(track), checkpoint); + } + + *renderSteps(track) { destroyDisplayChildren(this.container); + yield; addGrass(this); + yield; addGravelRunoff(this, track); + yield; addBoundaryUnderlay(this, track); + yield; addPitLaneRunoff(this, track); + yield; addPitLane(this, track); + yield; addAsphalt(this, track); - addKerbs(this, track); - addBorders(this, track); + yield; + yield* addKerbSteps(this, track); + yield* addBorderSteps(this, track); + yield; addStartingGrid(this, track); + yield; addFinishLine(this, track); + yield; addBarriers(this, track); } } diff --git a/src/rendering/track/offsetStrokeSafety.js b/src/rendering/track/offsetStrokeSafety.js index 6a1fdd1..ffc2c7a 100644 --- a/src/rendering/track/offsetStrokeSafety.js +++ b/src/rendering/track/offsetStrokeSafety.js @@ -3,6 +3,7 @@ import { queryNearbyTrackProjections } from '../../simulation/track/trackQueryIn import { metersToSimUnits } from '../../simulation/units.js'; import { NON_LOCAL_SAMPLE_STEP, OFFSET_GAP_SAMPLE_COUNT, OFFSET_SEGMENT_SAMPLE_COUNT, SEGMENTED_STROKE_STEP } from './trackRenderConstants.js'; import { arcDistance, interpolatedSegmentPoint, pointDistance } from './trackRenderGeometry.js'; +import { finishTrackRenderSteps } from './trackRenderSteps.js'; export function offsetPointIsLocal(track, source, point, offset) { const state = nearestTrackState(track, point); @@ -87,50 +88,71 @@ export function getOffsetStrokeSegments(track, { side, offset, step = SEGMENTED_STROKE_STEP, +}) { + return finishTrackRenderSteps(getOffsetStrokeSegmentSteps(track, { side, offset, step })); +} + +export function* getOffsetStrokeSegmentSteps(track, { + side, + offset, + step = SEGMENTED_STROKE_STEP, }) { const samples = track.samples.slice(0, -1); const signedOffset = side * offset; + const segments = []; - return samples.map((current, index) => { - if (index % step !== 0) return null; + for (let index = 0; index < samples.length; index += 1) { + if (index % step !== 0) continue; + yield; + const current = samples[index]; const next = samples[(index + step) % samples.length]; const start = offsetTrackPoint(current, signedOffset); const end = offsetTrackPoint(next, signedOffset); - return { + segments.push({ current, next, start, end, safe: offsetSegmentIsSafe(track, current, next, start, end, signedOffset), - }; - }).filter(Boolean); + }); + } + return segments; } export function getOffsetGapBridges(track, segments, width) { + return finishTrackRenderSteps(getOffsetGapBridgeSteps(track, segments, width)); +} + +export function* getOffsetGapBridgeSteps(track, segments, width) { if (segments.length < 2) return []; + const bridges = []; - return segments.flatMap((segment, index) => { - if (!segment.safe) return []; + for (let index = 0; index < segments.length; index += 1) { + yield; + const segment = segments[index]; + if (!segment.safe) continue; const previousIndex = (index - 1 + segments.length) % segments.length; - if (segments[previousIndex].safe) return []; + if (segments[previousIndex].safe) continue; let previousSafe = null; for (let lookup = 2; lookup <= segments.length; lookup += 1) { + yield; const candidate = segments[(index - lookup + segments.length) % segments.length]; if (!candidate.safe) continue; previousSafe = candidate; break; } - if (!previousSafe || previousSafe === segment) return []; - if (!offsetGapBridgeIsSafe(track, previousSafe.end, segment.start, width)) return []; + if (!previousSafe || previousSafe === segment) continue; + if (!offsetGapBridgeIsSafe(track, previousSafe.end, segment.start, width)) continue; - return [{ + bridges.push({ start: previousSafe.end, end: segment.start, - }]; - }); + }); + } + return bridges; } diff --git a/src/rendering/track/trackMaterialRenderer.js b/src/rendering/track/trackMaterialRenderer.js index ac8b4b8..c232314 100644 --- a/src/rendering/track/trackMaterialRenderer.js +++ b/src/rendering/track/trackMaterialRenderer.js @@ -2,7 +2,8 @@ import { Graphics, TilingSprite } from 'pixi.js'; import { offsetTrackPoint } from '../../simulation/track/trackModel.js'; import { ASPHALT_COLOR, BARRIER_WALL_WIDTH, EDGE_REVEAL_OFFSET, EDGE_REVEAL_WIDTH, GRASS_COLOR, GRAVEL_COLOR, KERB_CURVATURE_THRESHOLD, KERB_OFFSET, KERB_STEP, KERB_WIDTH, MATERIAL_TILE_SCALE, OUTER_BOUNDARY_OFFSET, OUTER_BOUNDARY_WIDTH, RUNOFF_GRASS_COLOR, SEGMENTED_STROKE_STEP, WORLD_BACKGROUND_PADDING_MULTIPLIER } from './trackRenderConstants.js'; import { makeTrackPath, textureOrWhite } from './trackRenderGeometry.js'; -import { getOffsetGapBridges, getOffsetStrokeSegments, offsetSegmentIsSafe } from './offsetStrokeSafety.js'; +import { getOffsetGapBridgeSteps, getOffsetStrokeSegmentSteps, offsetSegmentIsSafe } from './offsetStrokeSafety.js'; +import { finishTrackRenderSteps } from './trackRenderSteps.js'; export function drawOffsetSegment(graphics, start, end, { width, @@ -48,7 +49,11 @@ export function drawContinuousOffsetStroke(graphics, track, { }); } -export function drawSegmentedOffsetStroke(graphics, track, { +export function drawSegmentedOffsetStroke(graphics, track, options) { + finishTrackRenderSteps(drawSegmentedOffsetStrokeSteps(graphics, track, options)); +} + +function* drawSegmentedOffsetStrokeSteps(graphics, track, { side, offset, width, @@ -57,26 +62,29 @@ export function drawSegmentedOffsetStroke(graphics, track, { step = SEGMENTED_STROKE_STEP, cap = 'round', }) { - const segments = getOffsetStrokeSegments(track, { side, offset, step }); + const segments = yield* getOffsetStrokeSegmentSteps(track, { side, offset, step }); - segments.forEach((segment) => { - if (!segment.safe) return; + for (const segment of segments) { + yield; + if (!segment.safe) continue; drawOffsetSegment(graphics, segment.start, segment.end, { width, color, alpha, cap, }); - }); + } - getOffsetGapBridges(track, segments, width).forEach((bridge) => { + const bridges = yield* getOffsetGapBridgeSteps(track, segments, width); + for (const bridge of bridges) { + yield; drawOffsetSegment(graphics, bridge.start, bridge.end, { width, color, alpha, cap: 'round', }); - }); + } } export function addGrass(asset) { @@ -215,20 +223,26 @@ export function getTrackMaterialBands(track) { } export function drawKerbStripes(kerbs, track, { clipUnsafeSegments }) { + finishTrackRenderSteps(drawKerbStripeSteps(kerbs, track, { clipUnsafeSegments })); +} + +function* drawKerbStripeSteps(kerbs, track, { clipUnsafeSegments }) { const samples = track.samples.slice(0, -1); for (let index = 0; index < samples.length; index += KERB_STEP) { + yield; const sample = samples[index]; const next = samples[(index + KERB_STEP) % samples.length]; const curvature = Math.max(sample.curvature, next.curvature); if (curvature < KERB_CURVATURE_THRESHOLD) continue; const color = Math.floor(index / KERB_STEP) % 2 === 0 ? 0xe10600 : 0xf8fafc; - [-1, 1].forEach((side) => { + for (const side of [-1, 1]) { + yield; const offset = side * (track.width / 2 + KERB_OFFSET); const start = offsetTrackPoint(sample, offset); const end = offsetTrackPoint(next, offset); - if (clipUnsafeSegments && !offsetSegmentIsSafe(track, sample, next, start, end, offset)) return; + if (clipUnsafeSegments && !offsetSegmentIsSafe(track, sample, next, start, end, offset)) continue; kerbs.moveTo(start.x, start.y); kerbs.lineTo(end.x, end.y); kerbs.stroke({ @@ -238,7 +252,7 @@ export function drawKerbStripes(kerbs, track, { clipUnsafeSegments }) { join: 'round', cap: 'butt', }); - }); + } } } @@ -290,11 +304,16 @@ export function addAsphalt(asset, track) { } export function addBorders(asset, track) { + finishTrackRenderSteps(addBorderSteps(asset, track)); +} + +export function* addBorderSteps(asset, track) { const borders = new Graphics(); borders.label = 'track-borders'; + asset.container.addChild(borders); - [-1, 1].forEach((side) => { - drawSegmentedOffsetStroke(borders, track, { + for (const side of [-1, 1]) { + yield* drawSegmentedOffsetStrokeSteps(borders, track, { side, offset: track.width / 2, width: 5, @@ -303,7 +322,7 @@ export function addBorders(asset, track) { step: 4, }); - drawSegmentedOffsetStroke(borders, track, { + yield* drawSegmentedOffsetStrokeSteps(borders, track, { side, offset: track.width / 2 + 15, width: 7, @@ -311,16 +330,18 @@ export function addBorders(asset, track) { alpha: 0.56, step: 4, }); - }); - - asset.container.addChild(borders); + } } export function addKerbs(asset, track) { + finishTrackRenderSteps(addKerbSteps(asset, track)); +} + +export function* addKerbSteps(asset, track) { const kerbs = new Graphics(); kerbs.label = 'track-kerbs'; - drawKerbStripes(kerbs, track, { clipUnsafeSegments: true }); asset.container.addChild(kerbs); + yield* drawKerbStripeSteps(kerbs, track, { clipUnsafeSegments: true }); } diff --git a/src/rendering/track/trackRenderSteps.js b/src/rendering/track/trackRenderSteps.js new file mode 100644 index 0000000..8ef693d --- /dev/null +++ b/src/rendering/track/trackRenderSteps.js @@ -0,0 +1,23 @@ +// Both render paths consume the same ordered work; only startup may pause it. +export function finishTrackRenderSteps(steps) { + let result = steps.next(); + while (!result.done) result = steps.next(); + return result.value; +} + +export async function finishTrackRenderStepsAsync(steps, checkpoint) { + try { + while (true) { + // Recheck after a pause: destruction may have happened while yielding. + let pause; + do { + pause = checkpoint(); + if (pause) await pause; + } while (pause); + const result = steps.next(); + if (result.done) return result.value; + } + } finally { + steps.return(); + } +} diff --git a/src/simulation/timing/lapTelemetry.js b/src/simulation/timing/lapTelemetry.js index 692bb60..d1c3e00 100644 --- a/src/simulation/timing/lapTelemetry.js +++ b/src/simulation/timing/lapTelemetry.js @@ -12,23 +12,35 @@ function getSectorLength(track) { return track.length / TELEMETRY_SECTOR_COUNT; } +function getSectorBoundaryDistance(track, boundary) { + return Math.floor(boundary / TELEMETRY_SECTOR_COUNT) * track.length + + (boundary % TELEMETRY_SECTOR_COUNT) * getSectorLength(track); +} + +function getSectorBoundaryNumber(track, distance) { + let boundary = Math.floor(distance / getSectorLength(track)); + // Keep timing and position on the same representable line when division rounds. + if (boundary > 0 && getSectorBoundaryDistance(track, boundary) > distance) boundary -= 1; + else if (getSectorBoundaryDistance(track, boundary + 1) <= distance) boundary += 1; + return boundary; +} + function writeLapTelemetryPosition(target, track, raceDistance, totalLaps = Infinity) { const positiveDistance = Math.max(0, raceDistance ?? 0); + const boundary = getSectorBoundaryNumber(track, positiveDistance); + const completedLaps = Math.floor(boundary / TELEMETRY_SECTOR_COUNT); const lapIndex = Math.min( - Math.floor(positiveDistance / track.length), + completedLaps, Math.max(0, totalLaps - 1), ); - const lapProgress = positiveDistance >= track.length * totalLaps - ? track.length - : positiveDistance - lapIndex * track.length; const sectorLength = getSectorLength(track); - const sectorIndex = Math.min(TELEMETRY_SECTOR_COUNT - 1, Math.floor(lapProgress / sectorLength)); - const sectorStart = sectorIndex * sectorLength; + const sectorIndex = Math.min(TELEMETRY_SECTOR_COUNT - 1, boundary - lapIndex * TELEMETRY_SECTOR_COUNT); + const sectorStart = getSectorBoundaryDistance(track, lapIndex * TELEMETRY_SECTOR_COUNT + sectorIndex); - target.completedLaps = Math.min(Math.floor(positiveDistance / track.length), totalLaps); + target.completedLaps = Math.min(completedLaps, totalLaps); target.currentLap = Math.max(1, lapIndex + 1); target.currentSector = sectorIndex + 1; - target.currentSectorProgress = clamp((lapProgress - sectorStart) / sectorLength, 0, 1); + target.currentSectorProgress = clamp((positiveDistance - sectorStart) / sectorLength, 0, 1); return target; } @@ -115,15 +127,14 @@ export function updateLapTelemetry(car, previousRaceDistance, currentTime, track return false; } - const sectorLength = getSectorLength(track); let crossedBoundary = false; - if (travelled > 1e-6) { - const firstBoundary = Math.floor(previousDistance / sectorLength) + 1; - const lastBoundary = Math.floor(currentDistance / sectorLength); + if (travelled > 0) { + const firstBoundary = getSectorBoundaryNumber(track, previousDistance) + 1; + const lastBoundary = getSectorBoundaryNumber(track, currentDistance); for (let boundary = firstBoundary; boundary <= lastBoundary; boundary += 1) { - const boundaryDistance = boundary * sectorLength; - if (boundaryDistance <= previousDistance + 1e-3 || boundaryDistance > currentDistance + 1e-3) continue; + const boundaryDistance = getSectorBoundaryDistance(track, boundary); + if (boundaryDistance <= previousDistance || boundaryDistance > currentDistance) continue; crossedBoundary = true; const boundaryRatio = clamp((boundaryDistance - previousDistance) / travelled, 0, 1); @@ -198,22 +209,11 @@ function syncLiveSectorTelemetry(telemetry, { preserveCompletedSectors = false } } function syncInProgressLapTelemetry(telemetry, currentTime, currentRaceDistance, track, totalLaps) { - const positiveDistance = Math.max(0, currentRaceDistance ?? 0); - const maxLapIndex = Math.max(0, totalLaps - 1); - const lapIndex = Math.min(Math.floor(positiveDistance / track.length), maxLapIndex); - const lapProgress = positiveDistance >= track.length * totalLaps - ? track.length - : positiveDistance - lapIndex * track.length; - const sectorLength = getSectorLength(track); - const activeIndex = Math.min(TELEMETRY_SECTOR_COUNT - 1, Math.floor(lapProgress / sectorLength)); - const sectorStart = activeIndex * sectorLength; + writeLapTelemetryPosition(telemetry, track, currentRaceDistance, totalLaps); + const activeIndex = telemetry.currentSector - 1; const sectorProgress = ensureSectorTimesArray(telemetry.sectorProgress); const liveSectors = ensureSectorTimesArray(telemetry.liveSectors); - telemetry.completedLaps = Math.min(Math.floor(positiveDistance / track.length), totalLaps); - telemetry.currentLap = Math.max(1, lapIndex + 1); - telemetry.currentSector = activeIndex + 1; - telemetry.currentSectorProgress = clamp((lapProgress - sectorStart) / sectorLength, 0, 1); telemetry.currentLapTime = Math.max(0, currentTime - telemetry.currentLapStartedAt); telemetry.currentSectorElapsed = Math.max(0, currentTime - telemetry.currentSectorStartedAt); for (let index = activeIndex; index < TELEMETRY_SECTOR_COUNT; index += 1) { diff --git a/src/simulation/track/proceduralTrack.js b/src/simulation/track/proceduralTrack.js index b6645ff..4c9264b 100644 --- a/src/simulation/track/proceduralTrack.js +++ b/src/simulation/track/proceduralTrack.js @@ -6,6 +6,28 @@ import { resolveProceduralTrackOptions } from './trackGenerationOptions.js'; import { cacheProceduralTrackDefinition, getCachedProceduralTrack } from './trackModelCache.js'; export function createProceduralTrack(seed = Date.now(), options = {}) { + const preparation = prepareProceduralTrack(seed, options); + let step = preparation.next(); + while (!step.done) step = preparation.next(); + return step.value; +} + +export async function createProceduralTrackAsync(seed = Date.now(), options = {}, { checkpoint = () => null } = {}) { + const preparation = prepareProceduralTrack(seed, options); + while (true) { + let pending = checkpoint(); + while (pending) { + await pending; + pending = checkpoint(); + } + const step = preparation.next(); + if (step.done) return step.value; + } +} + +// Both entrypoints drain the same candidate sequence. Each build stays atomic; +// async callers can yield or cancel before builds, validation, and cache commit. +function* prepareProceduralTrack(seed, options) { const normalizedSeed = normalizeSeed(seed); const generationOptions = resolveProceduralTrackOptions(options); const cacheKey = `${normalizedSeed}:${generationOptions.cacheKey}`; @@ -13,6 +35,7 @@ export function createProceduralTrack(seed = Date.now(), options = {}) { if (cached) return cached; for (let attempt = 0; attempt < generationOptions.attempts.primary; attempt += 1) { + yield; const candidateSeed = (normalizedSeed + Math.imul(attempt, 2654435761)) >>> 0; const candidate = { ...TRACK, @@ -25,11 +48,13 @@ export function createProceduralTrack(seed = Date.now(), options = {}) { ...(generationOptions.pitLane.enabled === false ? { pitLane: { enabled: false } } : {}), }; const model = buildTrackModel(candidate); + yield; if (isValidProceduralTrackModel(model, generationOptions)) { const trackDefinition = { ...candidate, drsZones: model.drsZones.map(({ id, startRatio, endRatio }) => ({ id, startRatio, endRatio })), }; + yield; return cacheProceduralTrackDefinition(cacheKey, trackDefinition, model); } } @@ -37,6 +62,7 @@ export function createProceduralTrack(seed = Date.now(), options = {}) { let fallback = null; let fallbackModel = null; for (let attempt = 0; attempt < generationOptions.attempts.fallback; attempt += 1) { + yield; const candidateSeed = (normalizedSeed ^ Math.imul(attempt + 1, 2246822519)) >>> 0; const candidate = { ...TRACK, @@ -49,6 +75,7 @@ export function createProceduralTrack(seed = Date.now(), options = {}) { ...(generationOptions.pitLane.enabled === false ? { pitLane: { enabled: false } } : {}), }; const model = buildTrackModel(candidate); + yield; if (isValidProceduralTrackModel(model, generationOptions)) { fallback = candidate; fallbackModel = model; @@ -57,6 +84,7 @@ export function createProceduralTrack(seed = Date.now(), options = {}) { } if (!fallback || !fallbackModel) { + yield; fallback = { ...TRACK, name: `Generated GP ${normalizedSeed.toString(36).toUpperCase().padStart(6, '0').slice(-6)}`, @@ -68,10 +96,12 @@ export function createProceduralTrack(seed = Date.now(), options = {}) { ...(generationOptions.pitLane.enabled === false ? { pitLane: { enabled: false } } : {}), }; fallbackModel = buildTrackModel(fallback); + yield; } const fallbackDefinition = { ...fallback, drsZones: fallbackModel.drsZones.map(({ id, startRatio, endRatio }) => ({ id, startRatio, endRatio })), }; + yield; return cacheProceduralTrackDefinition(cacheKey, fallbackDefinition, fallbackModel); }