diff --git a/.gitignore b/.gitignore index 6e16cbe..04d0a8c 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ local-preview/dist/ .playwright/ .env +.claude/ .playwright-mcp/ .vite/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 344efa8..22ef2a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,47 @@ # Changelog +## 4.2.0 + +### Minor Changes + +- Tighten the package boundary around supported simulator, environment, display, data, and Python policy-server example surfaces. Local JavaScript training experiments now live outside the published package surface, and release-facing docs no longer advertise the removed local starter trainer as packaged guidance. +- Keep browser expert resets aligned with the resolved `physicsMode` and harden unsupported physics-mode handling so documented hosts continue to use only `arcade` or `advanced`. +- Add stricter CLI validation for release and diagnostic scripts. Browser smoke, consumer smoke, bundle-boundary checks, runtime benchmarks, track-query benchmarks, and hotspot profiling now provide clean help output and reject unknown or conflicting arguments before running expensive work. +- Clean up showcase/package-boundary examples so rendered snippets import only public package symbols and leave preview-local policy adapters as host-owned code. + +### Performance And Runtime + +- Reduce hot-loop allocations in built-in driver control by reusing racing-line profiles, traffic scan entries, lookahead sample objects, and target-point scratch while preserving the same steering/throttle/brake action contract. +- Add allocation-light track sampling helpers and a prepared sample-index lookup table so repeated `pointAt`/heading/curvature queries avoid binary-search and temporary-object churn on the common simulation paths. +- Reuse vehicle geometry, body AABB, swept AABB, and interpolated body-shape containers across collision and render paths instead of rebuilding geometry wrappers and axis objects every step. +- Reuse participant-interaction serialization for render snapshots and avoid repeated spread/object reconstruction in participant interaction resolution. +- Reduce per-step race/rules/timing churn by replacing transient race-order maps, steward review spreads, repeated inactive-steward state objects, and sector serialization maps with pooled or direct loop paths. +- Keep advanced/simulator-mode checks behind one helper so browser expert resets, red-flag release, collision damping, driver stabilization, and external state placement stay aligned with the documented `physicsMode` contract. + +### Fixes And Hardening + +- Preserve the resolved advanced physics mode when the browser expert adapter resets its environment, so expert-controlled browser runs do not silently fall back to arcade behavior. +- Keep unsupported browser and headless `physicsMode` values normalized to `arcade`, including explicit regression coverage for both surfaces. +- Carry optional `driverModel` metadata from driver or vehicle input into runtime car state for host-owned model/controller bookkeeping without adding a package-owned model loader. +- Tighten the environment performance characterization threshold for vector/object observation runs so ray-enabled physical-driver observations remain under the fixed local timing budget. + +### Showcase And Tooling + +- Add a playable-preview physics selector so the keyboard workbench can switch between arcade and advanced physics through the same documented query-parameter path as the rest of the preview. +- Add the `scripts/profile-hotspots.mjs` local profiling helper for advanced-mode race hot spots, with validated `--steps`, `--help`, and extra-argument handling. +- Split browser-smoke and runtime-benchmark argument parsing into focused helpers with direct unit coverage, and extend script coverage across consumer smoke, bundle-boundary, track-query benchmark, and profiler entrypoints. +- Keep the packed release contents focused on published package assets, docs, Python policy-server examples, source modules, public styles, and placeholder assets. + +### Migration Notes + +- No breaking host migration is required from `4.1.0`. +- Supported browser mounts, composable mounts, `@inventure71/paddockjs/environment`, `@inventure71/paddockjs/data`, and `@inventure71/paddockjs/placeholder` keep their documented public import contracts. +- Hosts should not depend on removed repository-local JavaScript training scripts or preview-only policy helper names. Use the documented environment API, custom model controller guide, or Python policy-server bridge for external training and policy integration. + +### Verification Notes + +- The final release gate is `npm run check:release`. + ## 4.1.0 ### Minor Changes diff --git a/INSTALL_AND_UPDATE.md b/INSTALL_AND_UPDATE.md index fa52d75..17b1424 100644 --- a/INSTALL_AND_UPDATE.md +++ b/INSTALL_AND_UPDATE.md @@ -114,16 +114,22 @@ npm run check Install a specific version when the host needs a controlled upgrade: ```bash -npm install @inventure71/paddockjs@4.1.0 +npm install @inventure71/paddockjs@4.2.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.2.0 Migration Notes + +- No breaking host migration is required from `4.1.0`. +- Browser mounts, composable mounts, `@inventure71/paddockjs/environment`, `@inventure71/paddockjs/data`, and `@inventure71/paddockjs/placeholder` keep their documented public import contracts. +- Do not rely on repository-local JavaScript trainer scripts or preview-only policy helper names as package API. Local model experiments belong outside the package surface; production integrations should use the documented environment API, custom model controller guide, or Python policy-server bridge. + ### 4.1.0 Migration Notes - No breaking host migration is required from `4.0.0`. -- Hosts that want visible simulator startup UI before the full PaddockJS browser bundle downloads can render the new `@inventure71/paddockjs/placeholder` HTML helper with the optional `@inventure71/paddockjs/placeholder.css` stylesheet. This placeholder subpath is intentionally independent of PixiJS, simulator assets, root runtime CSS, and the browser mount. +- Hosts that want visible simulator startup UI before the full PaddockJS browser bundle downloads can render the new `@inventure71/paddockjs/placeholder` HTML helper with the optional `@inventure71/paddockjs/placeholder.css` stylesheet. This placeholder subpath is intentionally independent of PixiJS, simulator assets, root runtime CSS, and the browser mount. Static HTML hosts should generate the placeholder HTML during their build and copy the CSS into their static output; see [Startup Loading](docs/loading.md). - Existing `mountF1Simulator()` and composable `mount*()` integrations keep their normal automatic package loading overlays after PaddockJS JavaScript starts. ### 4.0.0 Migration Notes @@ -151,6 +157,7 @@ The package repo owns its release process: - `npm run check` runs docs checks, fast runtime tests, public type verification, dry-pack verification, packed-consumer install/build verification, the tracked showcase build, and a quick Chromium browser smoke test. - `npm run check:release` runs the exhaustive release gate, including slow characterization tests and the full Chromium browser smoke matrix. - `npm run consumer:smoke` packs the package, installs the tarball into a fresh temporary Vite app, and builds that app through public package imports. +- `npm run consumer:bundle-boundaries` packs the package, installs the tarball into a fresh temporary Vite app, and verifies the root browser import remains the CSS/asset-owning simulator bundle while `/placeholder`, `/data`, and `/environment` stay CSS-free or lightweight according to their documented roles. - `npm run browser:smoke` builds `local-preview`, starts a local preview server, and checks desktop/mobile canvas rendering, overflow constraints, API buttons, and visual policy-runner stepping in Chromium. Use `npm run browser:smoke:quick` for the smaller local browser pass and `npm run browser:smoke:full` for the full matrix. - `npm run changeset` records the next version bump and changelog note. - `npm run version-packages` applies pending Changesets locally. diff --git a/README.md b/README.md index 06782f1..68ecaea 100644 --- a/README.md +++ b/README.md @@ -82,11 +82,12 @@ if ('requestIdleCallback' in window) { } ``` -`@inventure71/paddockjs/placeholder` does not import PixiJS, simulator assets, package runtime CSS, or the root browser mount. It is intended for the pre-JS/network gap. The full simulator mount replaces that placeholder and then uses the built-in package overlays while PixiJS and the race runtime finish booting. +`@inventure71/paddockjs/placeholder` does not import PixiJS, simulator assets, package runtime CSS, or the root browser mount. It is intended for the pre-JS/network gap. The full simulator mount replaces that placeholder and then uses the built-in package overlays while PixiJS and the race runtime finish booting. Static HTML hosts should run the placeholder helper in their build step and copy `@inventure71/paddockjs/placeholder.css` into their static output instead of expecting a plain browser page to resolve bare npm imports. Start here: - [Getting Started](docs/getting-started.md): install, browser mount, CSS, assets, host responsibilities, and container sizing. +- [Startup Loading](docs/loading.md): pre-JS placeholders, package loading overlays, and static-host build-time integration. - [Data Contract](docs/data_contract.md): driver, entry, callback, rules, and option shapes. - [Troubleshooting](docs/troubleshooting.md): common integration failures and supported checks. @@ -176,11 +177,12 @@ npm run docs:check npm run check npm run check:release npm run consumer:smoke +npm run consumer:bundle-boundaries npm run browser:smoke:quick -- --skip-build npm run showcase:dev ``` -`npm run check` is the normal local gate: docs checks, fast runtime tests, public declarations, dry package contents, packed-package consumption in a fresh Vite app, the showcase build, and a quick Chromium smoke against the showcase. `npm run check:release` adds slow characterization tests and the full browser smoke matrix. +`npm run check` is the normal local gate: docs checks, fast runtime tests, public declarations, dry package contents, packed-package consumption in a fresh Vite app, packed subpath bundle-boundary checks, the showcase build, and a quick Chromium smoke against the showcase. `npm run check:release` adds slow characterization tests and the full browser smoke matrix. ## License diff --git a/docs/architecture.md b/docs/architecture.md index c57ed94..2f9bf67 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -281,6 +281,8 @@ Timing maintenance is also kept allocation-light now. Runtime timing writes in ` `src/simulation/vehicle/vehicleState.js` owns external state mutation from simulator and environment reset APIs. It rejects non-finite numeric partial state and resynchronizes advanced-mode velocity from speed/heading when callers do not provide an explicit velocity vector, so scenario placement and `resetDrivers()` cannot leave stale physics velocity behind. +Local model training experiments belong outside the committed package surface. The ignored `training-lab/` folder may hold local trainer scripts, checkpoints, model loaders, and research harnesses, but package modules, preview routes, public exports, published types, and consumer docs must stay focused on simulator/environment/display contracts. + `src/simulation/rules/pitLaneSpeedingSteward.js` owns pit-speed-limit review. `raceSimulation.js` calls it after authoritative race-state recalculation so it reads the same pit-lane part classification as snapshots and track-limit stewarding. The steward only checks speed-limited pit-lane parts (`fast-lane`, `working-lane`, service areas, and garage boxes), leaving pit-entry and pit-exit connector roads legal but not speed-limited. Browser mounts generate a fresh procedural seed when `trackSeed` is omitted; explicit procedural track seeds are cached by seed plus resolved generation options so repeated mounts with the same procedural contract do not regenerate or rebuild the same model. The canonical generator owns both the default `race` profile and the smaller training profiles. Profile resolution lives beside the track model, merges `race` defaults, selected profile defaults, and explicit overrides, then feeds the same centerline, validation, start-straight, spatial-query, surface, and physics pipeline. Procedural generation starts from seeded connected coarse region masks, traces the outer boundary, smooths and warps the boundary into centerline controls, validates shape, clearance, local turn accumulation, length, and per-sample heading jumps, and retries with another region-derived control set instead of immediately falling back to an oval control ring when attempts fail. diff --git a/docs/component_inventory.md b/docs/component_inventory.md index 54fa87f..09a0be0 100644 --- a/docs/component_inventory.md +++ b/docs/component_inventory.md @@ -34,7 +34,7 @@ This inventory maps package-owned UI surfaces to their shared bases, owner modul | Telemetry sector times | `mountTelemetrySectorTimes()` and telemetry stack | `src/ui/telemetryTemplates.js` | Telemetry module class helper, loading overlay, unsupported overlay | `telemetryRenderer.js` | Last/best sector table only. | | Car/driver overview | `mountCarDriverOverview()` and optional telemetry stack embed | `src/ui/carOverviewTemplate.js` | Component surface frame helper, overview field slots, loading overlay, unsupported overlay | `domBindings.js` cached field bindings, `carOverviewRenderer.js` | Standalone and stack-embedded variants share identical markup. Runtime toggles vehicle vs driver fields without remounting and updates cached label/value bindings instead of querying each field during render. | | Race telemetry drawer | `mountRaceTelemetryDrawer()` and complete preview template | `src/ui/telemetryDrawerTemplate.js` | Component surface frame helper, loading overlay, camera controls, compact safety-car control, race canvas with timing/data panel, telemetry stack, unsupported overlay | `F1SimulatorApp.setTelemetryDrawerOpen()`, `controlStateRenderer.js`, normal race/telemetry renderers | Higher-level mixed template. It intentionally owns toolbar placement, drawer ids, open/closed inert state, and responsive narrow drawer behavior. | -| Loading overlay | All public startup-capable mounted surfaces, including all-in-one shell children and composable roots | `src/ui/templateUtils.js` | `createLoadingMarkup(label)` | `F1SimulatorApp.completeComponentLoading()` | Removed after startup after the initial frame. Component labels remain surface-specific for accessibility. Pre-JS placeholders are host-owned, not package-owned. | +| Loading overlay | All public startup-capable mounted surfaces, including all-in-one shell children and composable roots | `src/ui/templateUtils.js` | `createLoadingMarkup(label)` | `F1SimulatorApp.completeComponentLoading()` | Removed after startup after the initial frame. Component labels remain surface-specific for accessibility. Pre-JS placeholders are rendered by the host before package runtime starts, not by `F1SimulatorApp`. | | Pre-JS startup placeholder | `@inventure71/paddockjs/placeholder` and `@inventure71/paddockjs/placeholder.css` | `src/placeholder/index.js`, `src/placeholder.css` | Escaped inert HTML helper, optional tiny CSS start-light animation | Host page before root simulator import | Covers the network/import gap before the root package can render. It must stay independent of PixiJS, simulator assets, root runtime CSS, and app modules. | | Unsupported-size overlay | Public mount roots, shell, drawer, race/data/telemetry surfaces | `src/ui/templateUtils.js` | `createUnsupportedSizeMarkup(label)` | `installLayoutSupport()` | Display is driven by measured support state. Minimum size thresholds remain centralized in `layoutSupport.js`. | diff --git a/docs/getting-started.md b/docs/getting-started.md index 3875761..ac19b6e 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -68,6 +68,8 @@ await mountF1Simulator(root, { drivers, entries }); That placeholder covers the time before the full PaddockJS bundle executes. Once the bundle runs, PaddockJS owns the root markup and shows its package loading overlays until the first real simulator frame is ready. +Plain static HTML pages cannot resolve bare npm imports such as `@inventure71/paddockjs/placeholder` directly in the browser without a bundler or import map. Static hosts should run `createPaddockLoadingPlaceholder()` in the site build script, inject the generated HTML into the static page, and copy `@inventure71/paddockjs/placeholder.css` into the static output. See [Startup Loading](loading.md) for the bundled and static-host patterns. + ## CSS Most browser bundlers consume the root package stylesheet automatically. If your host build does not, import the stylesheet explicitly from a browser entry: @@ -100,6 +102,7 @@ If a package surface is constrained below its supported size, PaddockJS shows an ## Where To Go Next - Use [Composable Layouts](composable-layouts.md) when the host needs separate package-owned surfaces. +- Use [Startup Loading](loading.md) when the host needs instant first paint, static HTML integration, or a clearer split between placeholders and runtime overlays. - Use [Theming](theming.md) for runtime light/dark sync and token customization. - Use [Data Contract](data_contract.md) for full driver, entry, rule, UI, callback, and asset option shapes. - Use [Troubleshooting](troubleshooting.md) when a host build or browser smoke fails. diff --git a/docs/index.md b/docs/index.md index a566880..fb2a838 100644 --- a/docs/index.md +++ b/docs/index.md @@ -7,6 +7,7 @@ Code snippets in the documentation are illustrative host integration fragments u Start with the consumer task docs: - [Getting Started](getting-started.md): install, browser mount, package CSS, bundled assets, host responsibilities, and container sizing. +- [Startup Loading](loading.md): pre-JS placeholders, package loading overlays, static-host build-time integration, and unsupported-size placeholders. - [Composable Layouts](composable-layouts.md): building host layouts from package-owned simulator surfaces. - [Headless Environment](headless-environment.md): browser-free environment imports, expert-mode boundary, and basic stepping. - [Data Helpers](data-helpers.md): CSS-free data/tooling imports and procedural track helpers. @@ -25,16 +26,17 @@ Reference docs: - [Custom Model Controller Guide](custom_model_controller.md): how to wrap a trained model as a batched driver controller for browser playback or headless loops. - [Architecture](architecture.md): module ownership and data/control flow. - [Component Inventory](component_inventory.md): package-owned UI surfaces, shared bases, derived/mixed variants, and remaining intentional duplication. +- [Testing Reliability Guide](testing-reliability-guide.md): risk-driven test selection, behavior maps, required gates, and audit reporting standards. - [Data Model Notes](data_model.md): lower-level simulator data model notes kept with package docs. - [Learnings](learnings.md): implementation lessons and layout verification rules learned from simulator integration issues. Common paths: -- Installing PaddockJS into a browser host: read [Getting Started](getting-started.md), then [Data Contract](data_contract.md) for full option shapes. +- Installing PaddockJS into a browser host: read [Getting Started](getting-started.md), [Startup Loading](loading.md), then [Data Contract](data_contract.md) for full option shapes. - Upgrading an existing browser host from 2.x-era usage: read [Upgrading Hosts to 4.x](upgrading-hosts-to-3.md), then [Troubleshooting](troubleshooting.md) if the host build fails. - Building a package-owned composable layout: read [Composable Layouts](composable-layouts.md), then the sizing and UI options in [Data Contract](data_contract.md). - Enabling pits, penalties, tire requirements, safety car, or stalled off-track DNF: read [Rules](rules.md) first. Pit stops require `rules.modules.pitStops.enabled`; `tireStrategy` alone only controls compounds, tire-requirement stewarding, and pit target choices. - Connecting a trained model: read [Headless Environment](headless-environment.md), [Bring Your Own Model](training.md), then [Custom Model Controller Guide](custom_model_controller.md). PaddockJS owns observations, actions, specs, scenarios, and browser playback; the host owns the model, reward, storage, and training framework. -- Changing internals: read [Architecture](architecture.md) before editing source so new code lands in the feature-owned module instead of a facade or compatibility barrel. +- Changing internals: read [Architecture](architecture.md) before editing source so new code lands in the feature-owned module instead of a facade or compatibility barrel. Read [Testing Reliability Guide](testing-reliability-guide.md) before adding or changing tests. When simulator behavior changes, update the relevant doc in this folder in the same change. diff --git a/docs/loading.md b/docs/loading.md new file mode 100644 index 0000000..8d6fed5 --- /dev/null +++ b/docs/loading.md @@ -0,0 +1,141 @@ +# Startup Loading + +PaddockJS has two different startup loading surfaces. They solve different timing problems and should not be treated as interchangeable. + +## The Two Phases + +| Phase | When it can appear | Owner | Purpose | +| --- | --- | --- | --- | +| Pre-JS placeholder | Before the full PaddockJS browser bundle has downloaded, parsed, and imported | Host page, using the optional package placeholder helper/CSS | Give the user immediate lightweight visual feedback during the network/import gap | +| Package loading overlays | After `mountF1Simulator()` or a composable `mount*()` call starts | PaddockJS runtime | Cover PixiJS setup, asset loading, control binding, simulation creation, readout initialization, and the first real frame | + +The pre-JS placeholder exists because PaddockJS cannot render anything before PaddockJS code exists on the page. The package loading overlays exist because, once the package has started, the runtime still needs time to build the simulator. + +## Phase 1: Pre-JS Placeholder + +Use the optional placeholder subpath when a host wants visible simulator UI before importing the full browser runtime: + +```js +import { createPaddockLoadingPlaceholder } from '@inventure71/paddockjs/placeholder'; +import '@inventure71/paddockjs/placeholder.css'; + +root.innerHTML = createPaddockLoadingPlaceholder({ + label: 'Loading simulator', + detail: 'Preparing race control', +}); +``` + +`@inventure71/paddockjs/placeholder` is intentionally separate from the root package. It does not import PixiJS, simulator assets, package runtime CSS, `F1SimulatorApp`, or the browser mount. The stylesheet at `@inventure71/paddockjs/placeholder.css` is a tiny standalone stylesheet for the default start-light placeholder. + +The helper returns inert escaped HTML. It does not mount the simulator, register event listeners, fetch assets, or start any timers. The default `lights` variant uses CSS animation only. + +## Bundled Browser Hosts + +In Vite, Rollup, Webpack, or another browser bundler, render the placeholder first, then dynamically import the full simulator: + +```js +import { createPaddockLoadingPlaceholder } from '@inventure71/paddockjs/placeholder'; +import '@inventure71/paddockjs/placeholder.css'; + +const root = document.getElementById('f1-simulator-root'); + +root.innerHTML = createPaddockLoadingPlaceholder({ + label: 'Loading simulator', +}); + +const startSimulator = async () => { + const { mountF1Simulator } = await import('@inventure71/paddockjs'); + await mountF1Simulator(root, { drivers, entries }); +}; + +if ('requestIdleCallback' in window) { + window.requestIdleCallback(startSimulator); +} else { + setTimeout(startSimulator, 0); +} +``` + +The dynamic root import lets the page paint the placeholder before paying for the full browser simulator bundle. The full mount replaces the placeholder root content when PaddockJS starts. + +## Static HTML Hosts + +Plain static HTML pages cannot resolve bare npm imports such as `@inventure71/paddockjs/placeholder` directly in the browser unless the page also provides a bundler output or import map. Do not add a runtime bundling step only to render the placeholder. + +For static hosts with a build script, run the helper at build time and inject the generated HTML into the static page: + +```js +import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname } from 'node:path'; +import { createPaddockLoadingPlaceholder } from '@inventure71/paddockjs/placeholder'; + +const require = createRequire(import.meta.url); + +const placeholderHtml = createPaddockLoadingPlaceholder({ + label: 'Loading simulator', + detail: 'Preparing race preview', +}); + +const cssSource = require.resolve('@inventure71/paddockjs/placeholder.css'); +const cssTarget = 'dist/f1-simulator/paddock-placeholder.css'; + +mkdirSync(dirname(cssTarget), { recursive: true }); +copyFileSync(cssSource, cssTarget); + +const html = readFileSync('projects.html', 'utf8') + .replace('', placeholderHtml) + .replace( + '', + ' \n', + ); + +writeFileSync('dist/projects.html', html); +``` + +That pattern keeps the first paint static and cheap while avoiding manual markup drift. The HTML still comes from the package helper, and the CSS still comes from the package stylesheet. + +If a static host cannot run the helper during its build, copying the generated placeholder markup contract is acceptable as a fallback, but it is weaker. Manual markup can drift if the package changes the placeholder structure in a later release. + +## Phase 2: Package Loading Overlays + +After PaddockJS JavaScript starts, `mountF1Simulator(root, options)` synchronously writes a lightweight package shell into the mount root. The shell includes package-owned loading overlays for startup-capable surfaces such as the race canvas, controls, timing tower, race-data panel, telemetry stack, and composable component roots. + +Composable hosts get the same behavior per mounted surface: + +```js +const simulator = createPaddockSimulator(options); + +simulator.mountRaceCanvas(canvasRoot); +simulator.mountTimingTower(timingRoot); +simulator.mountTelemetryPanel(telemetryRoot); + +await simulator.start(); +``` + +Each `mount*()` call writes static package markup and a surface-specific `data-paddock-loading` overlay immediately. `start()` removes those overlays only after PixiJS, assets, controls, initial DOM readouts, and the first frame have initialized. + +These overlays are automatic. Hosts should not recreate them, query them for simulator state, or patch package internals to hide them. If a host needs a different pre-PaddockJS first paint, use the phase-1 placeholder around or inside the same root before calling the package mount. + +## Replacement Flow + +A typical lazy startup flow is: + +1. Host HTML/CSS paints the page and optional pre-JS placeholder. +2. Host code imports the full PaddockJS browser bundle. +3. `mountF1Simulator()` or composable `mount*()` calls replace the placeholder with package startup markup. +4. PaddockJS shows package loading overlays while runtime setup finishes. +5. PaddockJS removes those overlays after the first real simulator frame is ready. + +The pre-JS placeholder and package overlays can look similar, but they are intentionally separate. The first is a host-rendered shell for the network/import gap. The second is package runtime UI for simulator boot. + +## What Not To Do + +- Do not expect a plain static HTML page to resolve `@inventure71/paddockjs/placeholder` as a browser import without a bundler or import map. +- Do not eagerly import the root `@inventure71/paddockjs` package just to show a loading screen; that defeats the payload split. +- Do not copy simulator assets or PixiJS into the pre-JS placeholder. +- Do not manually maintain copied placeholder markup when the host has a build step that can call `createPaddockLoadingPlaceholder()`. +- Do not style package runtime internals such as `.start-lights`, `.timing-list`, or `.race-data-panel` from host CSS. Size the host root and let PaddockJS own runtime layout. + +## Related Placeholders + +PaddockJS also shows an `Unsupported size` placeholder when a shell or component is constrained below its supported bounds. That is not a startup loader. It is a layout safety state that tells the host to fix the container size rather than letting package controls overlap or clip. diff --git a/docs/system_specs.md b/docs/system_specs.md index 14b75c4..210a641 100644 --- a/docs/system_specs.md +++ b/docs/system_specs.md @@ -367,7 +367,7 @@ Full public race snapshots include `car.trackState` as the serialized car-center - `pixi.js` available through the package dependency graph. Raw Node imports of the package root are not a supported runtime check because the browser component entry imports CSS and image assets. The `@inventure71/paddockjs/environment` subpath is the supported browser-free import path for headless JavaScript training. -The repository starter loop is executable with `node examples/train-basic-policy.mjs`. It imports the public environment subpath and self-contained example data from `examples/trainingData.mjs`. It is a dependency-free example that trains/evaluates a tiny policy against the environment contract; it is not a packaged Gymnasium bridge or a recommended final RL algorithm. The package exposes a JSON-serializable worker protocol wrapper so external processes can bridge to the JavaScript environment without PaddockJS choosing Python, Gymnasium, PettingZoo, model storage, or training infrastructure. +The package exposes a JSON-serializable worker protocol wrapper so external processes can bridge to the JavaScript environment without PaddockJS choosing Python, Gymnasium, PettingZoo, model storage, training algorithms, checkpoint formats, or training infrastructure. ## Verification @@ -382,9 +382,12 @@ Expected: - Fast Vitest tests pass in the normal local gate. Slow characterization tests run under `npm run check:release`. - `npm pack --dry-run` succeeds and includes source files plus bundled assets. - A packed tarball installs and builds inside a fresh temporary Vite consumer app. +- Packed subpath bundle-boundary checks verify that the root import remains the CSS/asset-owning browser simulator bundle while `/placeholder`, `/data`, and `/environment` stay CSS-free or lightweight according to their documented roles. - The tracked showcase host builds. - The quick Chromium browser smoke verifies showcase canvas rendering, overflow constraints, one public API action, and live customization theme switching. The release browser smoke verifies the desktop/mobile matrix, package-panel overflow constraints, customization route interactions, public API buttons, and visual policy-runner stepping across generation and race configurations. +Use [Testing Reliability Guide](testing-reliability-guide.md) to choose the smallest behavior-focused proof for a change before relying on the broad package gate. The guide is authoritative for mapping package/API, simulation, environment, browser, performance, and docs changes to focused tests and required broader verification. + For internal runtime-efficiency development only, also run: ```bash diff --git a/docs/testing-reliability-guide.md b/docs/testing-reliability-guide.md new file mode 100644 index 0000000..dcec2f3 --- /dev/null +++ b/docs/testing-reliability-guide.md @@ -0,0 +1,62 @@ +# Testing Reliability Guide + +PaddockJS reliability work is risk-driven. Do not add tests for coverage vanity. Add or change tests when they protect a package contract, a simulator state transition, a browser lifecycle path, or a performance invariant that can silently regress. + +## Confidence Model + +Use the smallest verification layer that proves the behavior, then run the broader gate before claiming package quality. + +- Unit tests in `src/__tests__/` prove deterministic simulation, data normalization, sensor math, controller loops, and focused UI rendering helpers. +- Public type tests in `src/__tests__/publicApi.types.ts` prove the TypeScript consumer contract for root, `/data`, `/environment`, and `/placeholder` imports. +- `npm run consumer:smoke` proves the packed tarball installs and builds in a fresh Vite consumer through public package imports. +- `npm run consumer:bundle-boundaries` proves the packed root browser import remains the CSS/asset-owning simulator bundle while `/placeholder`, `/data`, and `/environment` stay CSS-free or lightweight according to their documented roles. +- `npm run showcase:ci` proves the tracked browser showcase still builds. +- `npm run browser:smoke:quick -- --skip-build` proves the built showcase can mount, paint a nonblank canvas, avoid key overflow regressions, exercise public controls, and keep live customization paths working. +- `npm run browser:smoke:full -- --skip-build` is required for broad browser/showcase/layout behavior and release handoff. +- `npm run benchmark:runtime -- --profile=standard --verify --json` proves simulation, sensor, rendering-data, snapshot, DOM-readout, and compact-transport performance contracts. + +## Change Matrix + +| Change area | Required focused proof | Required broader proof | +| --- | --- | --- | +| Public root, `/data`, `/environment`, or `/placeholder` API/types | `npm run types:check` plus a public API type assertion when the contract changes | `npm run check` | +| Package install, exports, files, CSS/assets, subpath bundle boundaries, or build assumptions | `npm run pack:dry`, `npm run consumer:smoke`, or `npm run consumer:bundle-boundaries` | `npm run check` | +| Race rules, ordering, DRS, starts, safety car, red flag, pits, penalties, collisions, or finish/classification | Focused Vitest file for the changed rule path | `npm run check`; use `npm run check:release` for broad behavior | +| Track geometry, query index, wheel surfaces, runoff, contact patches, or sensor rays | Focused geometry/sensor tests plus benchmark verification when hot paths change | `npm run check`; benchmark command required for performance-sensitive edits | +| Headless environment, controller loop, worker protocol, Policy Runner, observation/vector/schema contract | Focused environment/controller/transport tests and active observation contract assertions | `npm run check`; benchmark if compact/vector/snapshot cost changes | +| 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 | + +## 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. +- Include negative, stale-state, restart/remount, and partial-update cases for lifecycle code. +- For deterministic simulation changes, fix the seed, track seed, drivers, entries, rules, and scenario inputs in the test. +- For model-facing senses, assert the active observation/vector/schema contract. Debug overlays may have extra data, but no model-sense panel should display a recomputed or more precise value as model input. +- For performance-sensitive paths, assert counters that explain the cost, such as fallback counts, allocation counters, or compact payload sizes. Do not rely only on elapsed time. +- For package boundary work, prove public imports from the packed package, not internal relative paths. +- For browser layout work, prove rendered behavior with browser smoke or a focused DOM/canvas check. Static markup snapshots are not enough when resize observers, canvas painting, or runtime CSS state are involved. + +## High-Risk Behaviors To Map In Audits + +- `mountF1Simulator()` and `createPaddockSimulator()` lifecycle: initial shell, loading overlays, start, restart, theme sync, destroy, and repeated mount behavior. +- Public subpath boundaries: root imports browser/CSS runtime, `/environment` stays browser-free and CSS-free, `/data` stays CSS-free, `/placeholder` stays tiny and inert. +- Determinism: same seed, track seed, drivers, entries, rules, and scenario produce stable simulation behavior. +- Track query index propagation: built runtime tracks keep the internal non-enumerable index, while public JSON snapshots do not leak engine helpers. +- Race state transitions: start sequence, safety car, red flag, pit-lane open/closed, pit stops, penalties, DNF, finish, and final classification. +- Model-facing observations: object/vector/schema alignment, per-driver overrides, compact/vector-only outputs, reset-only observations, and external renderer frames. +- Rendering and layout: nonblank canvas, timing tower constraints, unsupported-size placeholders, lower-third/timing clearance, theme variables, and composable roots. +- Package consumption: dry pack contents, fresh consumer install/build, browser showcase build, and documented host update path. + +## Reporting Standard + +Every reliability audit should report: + +- current confidence: what is proven and what remains unproven; +- findings ranked by user impact and regression likelihood; +- exact files and behavior paths affected; +- smallest test or verification change that would close each gap; +- commands run, with the gate level they prove; +- any rejected critique, with the technical reason it is not accepted. + +If a required command is blocked by the environment, report the command, failure text, retry state, and the exact proof still missing. Do not replace a broad required gate with a narrow check. diff --git a/examples/train-basic-policy.mjs b/examples/train-basic-policy.mjs deleted file mode 100755 index 5408cb1..0000000 --- a/examples/train-basic-policy.mjs +++ /dev/null @@ -1,276 +0,0 @@ -#!/usr/bin/env node - -import { createPaddockEnvironment, createProgressReward } from '@inventure71/paddockjs/environment'; -import { TRAINING_DEMO_DRIVERS, TRAINING_DEMO_ENTRIES } from './trainingData.mjs'; - -const DEFAULT_OPTIONS = Object.freeze({ - generations: 4, - candidates: 5, - episodes: 1, - steps: 240, - frameSkip: 4, - seed: 71, - traffic: false, - evalOnly: false, -}); - -const INITIAL_POLICY = Object.freeze({ - steeringHeading: -1.2, - steeringOffset: -0.35, - steeringRayBalance: 0.45, - throttleBias: 0.72, - throttleFrontClearance: 0.28, - throttleSpeedDamping: 0.18, - brakeBias: 0, - brakeFrontDanger: 0.65, - brakeOffTrack: 0.2, -}); - -const POLICY_KEYS = Object.keys(INITIAL_POLICY); - -main(); - -function main() { - const options = parseCliArgs(process.argv.slice(2)); - if (options.help) { - printHelp(); - return; - } - - const driverId = TRAINING_DEMO_DRIVERS[0].id; - const rng = createSeededRandom(options.seed); - const reward = createProgressReward(); - const evaluate = (policy, seedOffset = 0) => evaluatePolicy({ - policy, - driverId, - reward, - options, - seedOffset, - }); - - if (options.evalOnly) { - const baseline = evaluate(INITIAL_POLICY); - printSummary({ options, driverId, bestPolicy: INITIAL_POLICY, best: baseline }); - return; - } - - let bestPolicy = { ...INITIAL_POLICY }; - let best = evaluate(bestPolicy); - - console.log(formatGenerationLine(0, best)); - - for (let generation = 1; generation <= options.generations; generation += 1) { - const mutationScale = 0.45 / Math.sqrt(generation); - const candidates = [{ policy: bestPolicy, scoreSeedOffset: generation * 1000 }]; - - for (let index = 1; index < options.candidates; index += 1) { - candidates.push({ - policy: mutatePolicy(bestPolicy, rng, mutationScale), - scoreSeedOffset: generation * 1000 + index * 100, - }); - } - - for (const candidate of candidates) { - const score = evaluate(candidate.policy, candidate.scoreSeedOffset); - if (score.averageReward > best.averageReward) { - best = score; - bestPolicy = candidate.policy; - } - } - - console.log(formatGenerationLine(generation, best)); - } - - printSummary({ options, driverId, bestPolicy, best }); -} - -function evaluatePolicy({ policy, driverId, reward, options, seedOffset = 0 }) { - let totalReward = 0; - let totalDistanceMeters = 0; - let totalCollisions = 0; - let totalOffTrackSteps = 0; - let completedEpisodes = 0; - - for (let episode = 0; episode < options.episodes; episode += 1) { - const env = createTrainingEnvironment({ driverId, reward, options, episode, seedOffset }); - let result = env.reset(); - let episodeReward = 0; - - for (let step = 0; step < options.steps && !result.done; step += 1) { - const observation = result.observation[driverId]; - const action = chooseAction(policy, observation); - result = env.step({ [driverId]: action }); - episodeReward += result.reward?.[driverId] ?? 0; - totalCollisions += result.events.filter((event) => event.type === 'collision').length; - if (result.observation[driverId]?.object?.self?.onTrack === false) totalOffTrackSteps += 1; - } - - const car = result.state.snapshot.cars.find((entry) => entry.id === driverId); - totalReward += episodeReward; - totalDistanceMeters += Number(car?.distanceMeters ?? 0); - completedEpisodes += 1; - env.destroy(); - } - - return { - averageReward: totalReward / Math.max(1, completedEpisodes), - averageDistanceMeters: totalDistanceMeters / Math.max(1, completedEpisodes), - collisions: totalCollisions, - offTrackSteps: totalOffTrackSteps, - }; -} - -function createTrainingEnvironment({ driverId, reward, options, episode, seedOffset }) { - const drivers = options.traffic ? TRAINING_DEMO_DRIVERS.slice(0, 8) : TRAINING_DEMO_DRIVERS.slice(0, 1); - return createPaddockEnvironment({ - drivers, - entries: TRAINING_DEMO_ENTRIES, - controlledDrivers: [driverId], - seed: options.seed + seedOffset + episode, - trackSeed: options.seed + 2026 + seedOffset + episode, - totalLaps: 3, - frameSkip: options.frameSkip, - scenario: { - participants: options.traffic ? 'all' : 'controlled-only', - nonControlled: 'ai', - }, - episode: { - maxSteps: options.steps, - endOnRaceFinish: true, - }, - rules: { - standingStart: false, - }, - reward, - }); -} - -function chooseAction(policy, observation) { - const self = observation.object.self; - const frontRay = getRayDistance(observation, 0); - const leftRay = getRayDistance(observation, -60); - const rightRay = getRayDistance(observation, 60); - const frontDanger = clamp01((35 - frontRay) / 35); - const rayBalanceMeters = rightRay - leftRay; - - const steering = clamp( - policy.steeringHeading * self.trackHeadingErrorRadians + - policy.steeringOffset * (self.trackOffsetMeters / 12) + - policy.steeringRayBalance * (rayBalanceMeters / 120), - -1, - 1, - ); - const throttle = clamp01( - policy.throttleBias + - policy.throttleFrontClearance * (frontRay / 120) - - policy.throttleSpeedDamping * (self.speedKph / 320) - - (self.onTrack ? 0 : 0.35), - ); - const brake = clamp01( - policy.brakeBias + - policy.brakeFrontDanger * frontDanger + - (self.onTrack ? 0 : policy.brakeOffTrack), - ); - - return { steering, throttle, brake }; -} - -function getRayDistance(observation, angleDegrees) { - const ray = observation.object.rays.find((entry) => entry.angleDegrees === angleDegrees); - return Number(ray?.track?.distanceMeters ?? ray?.lengthMeters ?? 120); -} - -function mutatePolicy(policy, rng, scale) { - return Object.fromEntries(POLICY_KEYS.map((key) => [ - key, - policy[key] + randomNormal(rng) * scale, - ])); -} - -function parseCliArgs(argv) { - const options = { ...DEFAULT_OPTIONS }; - - for (const arg of argv) { - const [name, rawValue] = arg.split('='); - if (name === '--help' || name === '-h') options.help = true; - else if (name === '--eval-only') options.evalOnly = true; - else if (name === '--traffic') options.traffic = true; - else if (name === '--no-traffic') options.traffic = false; - else if (name === '--generations') options.generations = parsePositiveInt(rawValue, name); - else if (name === '--candidates') options.candidates = parsePositiveInt(rawValue, name); - else if (name === '--episodes') options.episodes = parsePositiveInt(rawValue, name); - else if (name === '--steps') options.steps = parsePositiveInt(rawValue, name); - else if (name === '--frame-skip') options.frameSkip = parsePositiveInt(rawValue, name); - else if (name === '--seed') options.seed = parsePositiveInt(rawValue, name); - else throw new Error(`Unknown option: ${name}`); - } - - return options; -} - -function parsePositiveInt(value, optionName) { - const parsed = Number.parseInt(value, 10); - if (!Number.isFinite(parsed) || parsed <= 0) { - throw new Error(`${optionName} requires a positive integer value.`); - } - return parsed; -} - -function createSeededRandom(seed) { - let state = seed >>> 0; - return function random() { - state += 0x6D2B79F5; - let value = state; - value = Math.imul(value ^ (value >>> 15), value | 1); - value ^= value + Math.imul(value ^ (value >>> 7), value | 61); - return ((value ^ (value >>> 14)) >>> 0) / 4294967296; - }; -} - -function randomNormal(rng) { - const a = Math.max(Number.EPSILON, rng()); - const b = Math.max(Number.EPSILON, rng()); - return Math.sqrt(-2 * Math.log(a)) * Math.cos(2 * Math.PI * b); -} - -function clamp(value, min, max) { - return Math.min(max, Math.max(min, value)); -} - -function clamp01(value) { - return clamp(value, 0, 1); -} - -function formatGenerationLine(generation, score) { - return [ - `generation=${generation}`, - `reward=${score.averageReward.toFixed(2)}`, - `distanceMeters=${score.averageDistanceMeters.toFixed(1)}`, - `collisions=${score.collisions}`, - `offTrackSteps=${score.offTrackSteps}`, - ].join(' '); -} - -function printSummary({ options, driverId, bestPolicy, best }) { - console.log(JSON.stringify({ - driverId, - options, - best, - bestPolicy, - }, null, 2)); -} - -function printHelp() { - console.log(`Usage: node examples/train-basic-policy.mjs [options] - -Options: - --generations=N Random-search generations. Default: ${DEFAULT_OPTIONS.generations} - --candidates=N Candidate policies per generation. Default: ${DEFAULT_OPTIONS.candidates} - --episodes=N Episodes per policy evaluation. Default: ${DEFAULT_OPTIONS.episodes} - --steps=N Maximum manual environment steps per episode. Default: ${DEFAULT_OPTIONS.steps} - --frame-skip=N Simulator frames advanced by each step(action). Default: ${DEFAULT_OPTIONS.frameSkip} - --seed=N Deterministic random seed. Default: ${DEFAULT_OPTIONS.seed} - --traffic Keep built-in AI traffic on track during training. - --eval-only Evaluate the starter policy without training. -`); -} diff --git a/examples/trainingData.mjs b/examples/trainingData.mjs deleted file mode 100644 index 5bd8e25..0000000 --- a/examples/trainingData.mjs +++ /dev/null @@ -1,133 +0,0 @@ -export const TRAINING_DEMO_DRIVERS = [ - { - id: 'budget', - code: 'BUD', - icon: 'BB', - name: 'Budget Buddy', - color: '#ff2d55', - tire: 'M', - raceData: ['AI finance coach', 'Python + LLM', 'Budget guardrails'], - }, - { - id: 'noir', - code: 'NOI', - icon: 'NN', - name: 'Neural Noir', - color: '#ffb000', - tire: 'M', - raceData: ['Procedural mystery', 'Gemini storytelling', 'Unreal loop'], - }, - { - id: 'vinyl', - code: 'HOL', - icon: 'HV', - name: 'HoloVinyl', - color: '#00c2a8', - tire: 'H', - raceData: ['Touchless DJ control', 'Computer vision', 'Hand tracking'], - }, - { - id: 'drsorriso', - code: 'DRS', - icon: 'DR', - name: 'DrSorrisoDonations', - color: '#e10600', - tire: 'S', - raceData: ['Donation intake', 'Database workflow', 'Automation tool'], - }, - { - id: 'victoria', - code: 'VIC', - icon: 'VI', - name: 'VictorIA', - color: '#00a3ff', - tire: 'M', - raceData: ['Game AI sandbox', 'Robotics ideas', 'Vision systems'], - }, - { - id: 'reminderz', - code: 'REM', - icon: 'RZ', - name: 'ReminderZ', - color: '#a3e635', - tire: 'H', - raceData: ['Knowledge workflow', 'Personal graph', 'Capture tool'], - }, - { - id: 'clipclop', - code: 'CLP', - icon: 'CC', - name: 'ClipClop', - color: '#f97316', - tire: 'S', - raceData: ['Mac + Android sync', 'Local clipboard', 'Productivity app'], - }, - { - id: 'core', - code: 'COR', - icon: 'AI', - name: 'Core Conflict', - color: '#38bdf8', - tire: 'M', - raceData: ['Runtime AI agents', 'Multiplayer state', 'Game systems'], - }, -]; - -export const TRAINING_DEMO_ENTRIES = [ - { - driverId: 'budget', - driverNumber: 71, - timingName: 'Budget', - driver: { pace: 52, racecraft: 74, aggression: 38, riskTolerance: 47, patience: 81, consistency: 86 }, - vehicle: { id: 'budget-bb01', name: 'BB-01 Ledger', power: 48, braking: 72, aero: 55, dragEfficiency: 66, mechanicalGrip: 63, weightControl: 58, tireCare: 82 }, - }, - { - driverId: 'noir', - driverNumber: 13, - timingName: 'Noir', - driver: { pace: 68, racecraft: 83, aggression: 61, riskTolerance: 72, patience: 57, consistency: 64 }, - vehicle: { id: 'noir-nn13', name: 'NN-13 Shadow', power: 64, braking: 60, aero: 73, dragEfficiency: 57, mechanicalGrip: 69, weightControl: 54, tireCare: 51 }, - }, - { - driverId: 'vinyl', - driverNumber: 33, - timingName: 'HoloVinyl', - driver: { pace: 71, racecraft: 66, aggression: 52, riskTolerance: 59, patience: 62, consistency: 58 }, - vehicle: { id: 'vinyl-hv33', name: 'HV-33 Groove', power: 70, braking: 49, aero: 58, dragEfficiency: 74, mechanicalGrip: 52, weightControl: 68, tireCare: 46 }, - }, - { - driverId: 'drsorriso', - driverNumber: 55, - timingName: 'DrSorriso', - driver: { pace: 46, racecraft: 69, aggression: 44, riskTolerance: 43, patience: 76, consistency: 73 }, - vehicle: { id: 'sorriso-ds55', name: 'DS-55 Intake', power: 54, braking: 67, aero: 62, dragEfficiency: 49, mechanicalGrip: 71, weightControl: 45, tireCare: 69 }, - }, - { - driverId: 'victoria', - driverNumber: 11, - timingName: 'VictorIA', - driver: { pace: 78, racecraft: 79, aggression: 58, riskTolerance: 65, patience: 55, consistency: 68 }, - vehicle: { id: 'victoria-vi11', name: 'VI-11 Vector', power: 76, braking: 58, aero: 65, dragEfficiency: 63, mechanicalGrip: 61, weightControl: 60, tireCare: 48 }, - }, - { - driverId: 'reminderz', - driverNumber: 7, - timingName: 'ReminderZ', - driver: { pace: 41, racecraft: 61, aggression: 34, riskTolerance: 39, patience: 85, consistency: 80 }, - vehicle: { id: 'reminderz-rz07', name: 'RZ-07 Recall', power: 42, braking: 76, aero: 50, dragEfficiency: 72, mechanicalGrip: 58, weightControl: 63, tireCare: 88 }, - }, - { - driverId: 'clipclop', - driverNumber: 14, - timingName: 'ClipClop', - driver: { pace: 73, racecraft: 88, aggression: 76, riskTolerance: 78, patience: 48, consistency: 61 }, - vehicle: { id: 'clipclop-cc14', name: 'CC-14 Sync', power: 68, braking: 63, aero: 59, dragEfficiency: 61, mechanicalGrip: 78, weightControl: 56, tireCare: 44 }, - }, - { - driverId: 'core', - driverNumber: 91, - timingName: 'Core', - driver: { pace: 82, racecraft: 85, aggression: 67, riskTolerance: 74, patience: 53, consistency: 72 }, - vehicle: { id: 'core-ai91', name: 'AI-91 Core', power: 80, braking: 61, aero: 72, dragEfficiency: 59, mechanicalGrip: 75, weightControl: 51, tireCare: 50 }, - }, -]; diff --git a/local-preview/package-lock.json b/local-preview/package-lock.json index e46d555..43534f1 100644 --- a/local-preview/package-lock.json +++ b/local-preview/package-lock.json @@ -7,12 +7,12 @@ "name": "paddockjs-showcase", "dependencies": { "@inventure71/paddockjs": "file:..", - "vite": "8.0.10" + "vite": "8.0.16" } }, "..": { "name": "@inventure71/paddockjs", - "version": "2.0.0", + "version": "4.2.0", "license": "Apache-2.0", "dependencies": { "pixi.js": "8.18.1" @@ -63,13 +63,13 @@ "link": true }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", - "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==", + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", + "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", "license": "MIT", "optional": true, "dependencies": { - "@tybys/wasm-util": "^0.10.1" + "@tybys/wasm-util": "^0.10.2" }, "funding": { "type": "github", @@ -81,18 +81,18 @@ } }, "node_modules/@oxc-project/types": { - "version": "0.127.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.127.0.tgz", - "integrity": "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==", + "version": "0.133.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.133.0.tgz", + "integrity": "sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/Boshen" } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.17.tgz", - "integrity": "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz", + "integrity": "sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==", "cpu": [ "arm64" ], @@ -106,9 +106,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.17.tgz", - "integrity": "sha512-4ksWc9n0mhlZpZ9PMZgTGjeOPRu8MB1Z3Tz0Mo02eWfWCHMW1zN82Qz/pL/rC+yQa+8ZnutMF0JjJe7PjwasYw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.3.tgz", + "integrity": "sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==", "cpu": [ "arm64" ], @@ -122,9 +122,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.17.tgz", - "integrity": "sha512-SUSDOI6WwUVNcWxd02QEBjLdY1VPHvlEkw6T/8nYG322iYWCTxRb1vzk4E+mWWYehTp7ERibq54LSJGjmouOsw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.3.tgz", + "integrity": "sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==", "cpu": [ "x64" ], @@ -138,9 +138,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.17.tgz", - "integrity": "sha512-hwnz3nw9dbJ05EDO/PvcjaaewqqDy7Y1rn1UO81l8iIK1GjenME75dl16ajbvSSMfv66WXSRCYKIqfgq2KCfxw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.3.tgz", + "integrity": "sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==", "cpu": [ "x64" ], @@ -154,9 +154,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.17.tgz", - "integrity": "sha512-IS+W7epTcwANmFSQFrS1SivEXHtl1JtuQA9wlxrZTcNi6mx+FDOYrakGevvvTwgj2JvWiK8B29/qD9BELZPyXQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.3.tgz", + "integrity": "sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==", "cpu": [ "arm" ], @@ -170,12 +170,15 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-e6usGaHKW5BMNZOymS1UcEYGowQMWcgZ71Z17Sl/h2+ZziNJ1a9n3Zvcz6LdRyIW5572wBCTH/Z+bKuZouGk9Q==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.3.tgz", + "integrity": "sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==", "cpu": [ "arm64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -186,12 +189,15 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.17.tgz", - "integrity": "sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.3.tgz", + "integrity": "sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==", "cpu": [ "arm64" ], + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -202,12 +208,15 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.3.tgz", + "integrity": "sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==", "cpu": [ "ppc64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -218,12 +227,15 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.3.tgz", + "integrity": "sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==", "cpu": [ "s390x" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -234,12 +246,15 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.3.tgz", + "integrity": "sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==", "cpu": [ "x64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -250,12 +265,15 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.17.tgz", - "integrity": "sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.3.tgz", + "integrity": "sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==", "cpu": [ "x64" ], + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -266,9 +284,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.17.tgz", - "integrity": "sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.3.tgz", + "integrity": "sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==", "cpu": [ "arm64" ], @@ -282,9 +300,9 @@ } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.17.tgz", - "integrity": "sha512-LEXei6vo0E5wTGwpkJ4KoT3OZJRnglwldt5ziLzOlc6qqb55z4tWNq2A+PFqCJuvWWdP53CVhG1Z9NtToDPJrA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.3.tgz", + "integrity": "sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==", "cpu": [ "wasm32" ], @@ -300,9 +318,9 @@ } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.17.tgz", - "integrity": "sha512-gUmyzBl3SPMa6hrqFUth9sVfcLBlYsbMzBx5PlexMroZStgzGqlZ26pYG89rBb45Mnia+oil6YAIFeEWGWhoZA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.3.tgz", + "integrity": "sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==", "cpu": [ "arm64" ], @@ -316,9 +334,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.17.tgz", - "integrity": "sha512-3hkiolcUAvPB9FLb3UZdfjVVNWherN1f/skkGWJP/fgSQhYUZpSIRr0/I8ZK9TkF3F7kxvJAk0+IcKvPHk9qQg==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.3.tgz", + "integrity": "sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==", "cpu": [ "x64" ], @@ -332,15 +350,15 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.17.tgz", - "integrity": "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "license": "MIT" }, "node_modules/@tybys/wasm-util": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", - "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "version": "0.10.2", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", + "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", "license": "MIT", "optional": true, "dependencies": { @@ -637,9 +655,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "version": "3.3.12", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", + "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", "funding": [ { "type": "github", @@ -673,9 +691,9 @@ } }, "node_modules/postcss": { - "version": "8.5.12", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.12.tgz", - "integrity": "sha512-W62t/Se6rA0Az3DfCL0AqJwXuKwBeYg6nOaIgzP+xZ7N5BFCI7DYi1qs6ygUYT6rvfi6t9k65UMLJC+PHZpDAA==", + "version": "8.5.15", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", + "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", "funding": [ { "type": "opencollective", @@ -692,7 +710,7 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.11", + "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -701,13 +719,13 @@ } }, "node_modules/rolldown": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.17.tgz", - "integrity": "sha512-ZrT53oAKrtA4+YtBWPQbtPOxIbVDbxT0orcYERKd63VJTF13zPcgXTvD4843L8pcsI7M6MErt8QtON6lrB9tyA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz", + "integrity": "sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==", "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.127.0", - "@rolldown/pluginutils": "1.0.0-rc.17" + "@oxc-project/types": "=0.133.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { "rolldown": "bin/cli.mjs" @@ -716,21 +734,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.17", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.17", - "@rolldown/binding-darwin-x64": "1.0.0-rc.17", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.17", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.17", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.17", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.17", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.17", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.17", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.17", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.17" + "@rolldown/binding-android-arm64": "1.0.3", + "@rolldown/binding-darwin-arm64": "1.0.3", + "@rolldown/binding-darwin-x64": "1.0.3", + "@rolldown/binding-freebsd-x64": "1.0.3", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", + "@rolldown/binding-linux-arm64-gnu": "1.0.3", + "@rolldown/binding-linux-arm64-musl": "1.0.3", + "@rolldown/binding-linux-ppc64-gnu": "1.0.3", + "@rolldown/binding-linux-s390x-gnu": "1.0.3", + "@rolldown/binding-linux-x64-gnu": "1.0.3", + "@rolldown/binding-linux-x64-musl": "1.0.3", + "@rolldown/binding-openharmony-arm64": "1.0.3", + "@rolldown/binding-wasm32-wasi": "1.0.3", + "@rolldown/binding-win32-arm64-msvc": "1.0.3", + "@rolldown/binding-win32-x64-msvc": "1.0.3" } }, "node_modules/source-map-js": { @@ -743,9 +761,9 @@ } }, "node_modules/tinyglobby": { - "version": "0.2.16", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", - "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "license": "MIT", "dependencies": { "fdir": "^6.5.0", @@ -766,16 +784,16 @@ "optional": true }, "node_modules/vite": { - "version": "8.0.10", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.10.tgz", - "integrity": "sha512-rZuUu9j6J5uotLDs+cAA4O5H4K1SfPliUlQwqa6YEwSrWDZzP4rhm00oJR5snMewjxF5V/K3D4kctsUTsIU9Mw==", + "version": "8.0.16", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz", + "integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==", "license": "MIT", "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", - "postcss": "^8.5.10", - "rolldown": "1.0.0-rc.17", - "tinyglobby": "^0.2.16" + "postcss": "^8.5.15", + "rolldown": "1.0.3", + "tinyglobby": "^0.2.17" }, "bin": { "vite": "bin/vite.js" @@ -791,7 +809,7 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.1.0", + "@vitejs/devtools": "^0.1.18", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", diff --git a/local-preview/package.json b/local-preview/package.json index 9be98ba..18cec51 100644 --- a/local-preview/package.json +++ b/local-preview/package.json @@ -9,6 +9,6 @@ }, "dependencies": { "@inventure71/paddockjs": "file:..", - "vite": "8.0.10" + "vite": "8.0.16" } } diff --git a/local-preview/playable.html b/local-preview/playable.html index 1631d74..83b829e 100644 --- a/local-preview/playable.html +++ b/local-preview/playable.html @@ -33,6 +33,13 @@

Keyboard drive

+ diff --git a/local-preview/src/main.js b/local-preview/src/main.js index d535602..0d8f34d 100644 --- a/local-preview/src/main.js +++ b/local-preview/src/main.js @@ -272,10 +272,12 @@ function previewPhysicsMode() { return explicitPreviewPhysicsMode() ?? 'arcade'; } +const PREVIEW_PHYSICS_MODES = ['arcade', 'advanced']; + function explicitPreviewPhysicsMode() { const params = new URLSearchParams(window.location.search); const value = params.get('physicsMode'); - return value === 'advanced' || value === 'arcade' ? value : null; + return PREVIEW_PHYSICS_MODES.includes(value) ? value : null; } function previewRouteHref(href) { @@ -1380,6 +1382,15 @@ async function mountPlayablePage() { const pitIntentButtons = [...document.querySelectorAll('[data-playable-pit-intent]')]; const compoundButtons = [...document.querySelectorAll('[data-playable-compound]')]; const pitState = document.querySelector('[data-playable-pit-state]'); + const physicsSelect = document.querySelector('[data-playable-physics]'); + if (physicsSelect) { + physicsSelect.value = previewPhysicsMode(); + physicsSelect.addEventListener('change', () => { + const url = new URL(window.location.href); + url.searchParams.set('physicsMode', physicsSelect.value); + window.location.href = url.toString(); + }); + } const keyNodes = new Map([...document.querySelectorAll('[data-playable-key]')].map((node) => [ node.dataset.playableKey, node, @@ -1420,7 +1431,7 @@ async function mountPlayablePage() { ...commonOptions('playable'), title: 'Playable Complete Race Workbench', kicker: 'keyboard -> normalized controls', - physicsMode: 'arcade', + physicsMode: previewPhysicsMode(), seed: 71, trackSeed: COMPLETE_WORKBENCH_TRACK_SEED, totalLaps: 8, @@ -2132,6 +2143,11 @@ async function mountPolicyRunnerPage() { const now = performance.now(); lastPolicyDiagnosticRenderAt = now; const observation = activePrimaryDriver ? result?.observation?.[activePrimaryDriver] : null; + const snapshot = simulator?.getSnapshot?.() ?? result?.state?.snapshot ?? null; + const trackDiagnostics = snapshot?.track ? { + hasTrackIndex: Boolean(snapshot.track.queryIndex), + queryIndexEnumerable: Object.keys(snapshot.track).includes('queryIndex'), + } : null; const shouldRenderSenses = activePrimaryDriver !== lastPolicySensesDriverId || now - lastPolicySensesRenderAt >= POLICY_SENSES_RENDER_INTERVAL_MS; if (shouldRenderSenses) { @@ -2173,6 +2189,7 @@ async function mountPolicyRunnerPage() { visualFrameSkip: POLICY_ACTION_HOLD_FRAMES, heldFramesRemaining, frameMetrics: currentFrameMetrics(), + trackDiagnostics, metadata: activeControllerKind() === 'distilled-policy' && activePayload ? { format: activePayload.format, stage: activePayload.stage, diff --git a/local-preview/src/showcaseCatalog.js b/local-preview/src/showcaseCatalog.js index 1217a5d..614f508 100644 --- a/local-preview/src/showcaseCatalog.js +++ b/local-preview/src/showcaseCatalog.js @@ -598,24 +598,25 @@ const wheelSurface = calculateWheelSurfaceState(trackLimits, wheelContact);`, summary: 'Example code', hint: 'Browser-loaded distilled policy', code: `import { - createDistilledPolicyController, createPaddockDriverControllerLoop, + createPaddockSimulator, } from '@inventure71/paddockjs'; const policy = await loadCheckpointPolicyPayload('/local-checkpoints/latest-distilled-policy.json'); +const policyController = createPolicyController(policy); const simulator = createPaddockSimulator({ drivers, entries, physicsMode: 'advanced' }); const loop = createPaddockDriverControllerLoop({ simulator, controlledDrivers: [drivers[0].id], - controller: createDistilledPolicyController(policy), + controller: policyController, });`, - note: 'The repo preview uses a local helper around the public controller loop to load the browser-side distilled payload.', + note: 'The repo preview uses a local createPolicyController() adapter around the public controller loop to run the browser-side distilled payload.', }, 'policy-runner.policy-server': { summary: 'Example code', hint: 'Browser simulator + external policy server', - code: `const serverController = createPolicyServerController({ + code: `const serverController = createHostPolicyServerController({ url: 'http://127.0.0.1:8787', }); @@ -624,12 +625,12 @@ const loop = createPaddockDriverControllerLoop({ controlledDrivers: [drivers[0].id], controller: serverController, });`, - note: 'The browser owns the simulator. The server receives protocol v2 compact vectors per decision; specs/configuration are sent on reset only.', + note: 'createHostPolicyServerController() is host-owned adapter code. The browser owns the simulator, and the server receives protocol v2 compact vectors per decision.', }, 'policy-runner.live-node-view': { summary: 'Example code', hint: 'Live preview stream', - code: `const liveController = createLiveNodeViewController({ + code: `const liveController = createHostLivePreviewController({ url: 'ws://127.0.0.1:8787/preview', }); @@ -638,7 +639,7 @@ const loop = createPaddockDriverControllerLoop({ controlledDrivers: [drivers[0].id], controller: liveController, });`, - note: 'In live preview mode the remote source is authoritative for the rendered frames, and the browser follows that stream.', + note: 'createHostLivePreviewController() is host-owned adapter code. In live preview mode the remote source is authoritative for rendered frames.', }, }; diff --git a/local-preview/src/styles.css b/local-preview/src/styles.css index fd13ac5..9b8d4e5 100644 --- a/local-preview/src/styles.css +++ b/local-preview/src/styles.css @@ -1522,6 +1522,26 @@ body[data-page='customization'][data-preview-theme-mode='light'] .example-code p white-space: nowrap; } +.playable-physics-select { + display: flex; + gap: 0.4rem; + align-items: center; + color: #f4f1ea; + font-size: 0.85rem; + font-weight: 700; + white-space: nowrap; +} + +.playable-physics-select select { + min-height: 2.5rem; + padding: 0.45rem 0.6rem; + color: #f4f1ea; + border: 1px solid rgba(244, 241, 234, 0.16); + border-radius: 8px; + background: rgba(16, 17, 19, 0.9); + font-weight: 700; +} + .playable-controls button.is-active, .playable-compounds button.is-active { color: #101113; diff --git a/package-lock.json b/package-lock.json index 43168c4..0a6260e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@inventure71/paddockjs", - "version": "4.1.0", + "version": "4.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@inventure71/paddockjs", - "version": "4.1.0", + "version": "4.2.0", "license": "Apache-2.0", "dependencies": { "pixi.js": "8.18.1" @@ -275,33 +275,10 @@ "prettier": "^2.7.1" } }, - "node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", "dev": true, "license": "MIT", "optional": true, @@ -706,6 +683,40 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", + "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", + "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { "version": "1.0.0-rc.17", "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.17.tgz", @@ -1949,6 +1960,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -2496,6 +2508,7 @@ "integrity": "sha512-rZuUu9j6J5uotLDs+cAA4O5H4K1SfPliUlQwqa6YEwSrWDZzP4rhm00oJR5snMewjxF5V/K3D4kctsUTsIU9Mw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", diff --git a/package.json b/package.json index fcc3ffa..7639fc5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@inventure71/paddockjs", - "version": "4.1.0", + "version": "4.2.0", "type": "module", "description": "A data-driven browser F1 simulator component for host websites.", "license": "Apache-2.0", @@ -68,8 +68,6 @@ "examples/python/README.md", "examples/python/base_policy_server.py", "examples/python/requirements.txt", - "examples/train-basic-policy.mjs", - "examples/trainingData.mjs", "src/api", "src/app", "src/config", @@ -90,10 +88,11 @@ "test:fast": "node scripts/run-vitest.mjs", "types:check": "tsc -p tsconfig.types.json --noEmit", "docs:check": "node scripts/docs-check.mjs", - "check": "npm run docs:check && npm run test:fast && npm run types:check && npm run pack:dry && npm run consumer:smoke && npm run showcase:ci && npm run browser:smoke:quick -- --skip-build", - "check:release": "npm run docs:check && npm test && npm run types:check && npm run pack:dry && npm run consumer:smoke && npm run showcase:ci && npm run browser:smoke:full -- --skip-build", + "check": "npm run docs:check && npm run test:fast && npm run types:check && npm run pack:dry && npm run consumer:smoke && npm run consumer:bundle-boundaries && npm run showcase:ci && npm run browser:smoke:quick -- --skip-build", + "check:release": "npm run docs:check && npm test && npm run types:check && npm run pack:dry && npm run consumer:smoke && npm run consumer:bundle-boundaries && npm run showcase:ci && npm run browser:smoke:full -- --skip-build", "pack:dry": "npm pack --dry-run", "consumer:smoke": "node scripts/consumer-package-smoke.mjs", + "consumer:bundle-boundaries": "node scripts/consumer-bundle-boundaries.mjs", "browser:smoke": "node smoke/browser-smoke.mjs", "browser:smoke:quick": "node smoke/browser-smoke.mjs --quick", "browser:smoke:full": "node smoke/browser-smoke.mjs --full", @@ -104,8 +103,7 @@ "showcase:ci": "npm --prefix local-preview ci && npm --prefix local-preview run build", "changeset": "changeset", "version-packages": "changeset version", - "release": "npm publish --provenance", - "example:train": "node examples/train-basic-policy.mjs" + "release": "npm publish --provenance" }, "dependencies": { "pixi.js": "8.18.1" diff --git a/scripts/benchmark-runtime-efficiency.mjs b/scripts/benchmark-runtime-efficiency.mjs index a37ca18..3cce4fa 100644 --- a/scripts/benchmark-runtime-efficiency.mjs +++ b/scripts/benchmark-runtime-efficiency.mjs @@ -5,11 +5,21 @@ import { runRuntimeEfficiencyBenchmarks, validateRuntimeEfficiencyBenchmarkResults, } from './runtimeEfficiencyBenchmarks.mjs'; +import { parseRuntimeBenchmarkArgs, runtimeBenchmarkUsage } from './benchmarkRuntimeArgs.mjs'; -const args = process.argv.slice(2); -const json = args.includes('--json'); -const verify = args.includes('--verify'); -const profile = readOption('profile', args) ?? 'standard'; +let cliOptions; +try { + cliOptions = parseRuntimeBenchmarkArgs(process.argv.slice(2)); +} catch (error) { + console.error(`${runtimeBenchmarkUsage()}\n\n${error.message}`); + process.exit(1); +} + +const { json, verify, profile } = cliOptions; +if (cliOptions.help) { + console.log(runtimeBenchmarkUsage()); + process.exit(0); +} const results = runRuntimeEfficiencyBenchmarks({ profile, verify }); if (verify) validateRuntimeEfficiencyBenchmarkResults(results); @@ -19,12 +29,3 @@ if (json) { } else { process.stdout.write(formatRuntimeEfficiencyBenchmarkMarkdown(results)); } - -function readOption(name, values) { - const prefix = `--${name}=`; - const inline = values.find((value) => value.startsWith(prefix)); - if (inline) return inline.slice(prefix.length); - const index = values.indexOf(`--${name}`); - if (index >= 0) return values[index + 1]; - return null; -} diff --git a/scripts/benchmark-track-query-index.mjs b/scripts/benchmark-track-query-index.mjs index 25c0967..a08293d 100644 --- a/scripts/benchmark-track-query-index.mjs +++ b/scripts/benchmark-track-query-index.mjs @@ -9,6 +9,27 @@ import { import { metersToSimUnits, simUnitsToMeters } from '../src/simulation/units.js'; import { applyWheelSurfaceState } from '../src/simulation/vehicle/wheelSurface.js'; +function usage() { + return 'Usage: node scripts/benchmark-track-query-index.mjs [--help]'; +} + +function parseArgs(args = process.argv.slice(2)) { + if (args.some((arg) => arg === '--help' || arg === '-h')) { + console.log(usage()); + process.exit(0); + } + if (args.length > 0) { + throw new Error(`Unknown track benchmark argument: ${args[0]}`); + } +} + +try { + parseArgs(); +} catch (error) { + console.error(`${usage()}\n\n${error.message}`); + process.exit(1); +} + const DEFAULT_DRIVERS = Array.from({ length: 20 }, (_, index) => ({ id: `agent-${index}`, code: `A${index}`, diff --git a/scripts/benchmarkRuntimeArgs.mjs b/scripts/benchmarkRuntimeArgs.mjs new file mode 100644 index 0000000..a6f914a --- /dev/null +++ b/scripts/benchmarkRuntimeArgs.mjs @@ -0,0 +1,43 @@ +const SUPPORTED_PROFILES = new Set(['standard', 'smoke']); +const HELP_FLAGS = new Set(['--help', '-h']); +const SUPPORTED_FLAGS = new Set(['--json', '--verify', ...HELP_FLAGS]); + +export function parseRuntimeBenchmarkArgs(args = []) { + let profile = 'standard'; + let json = false; + let verify = false; + let help = false; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (HELP_FLAGS.has(arg)) { + help = true; + } else if (arg === '--json') { + json = true; + } else if (arg === '--verify') { + verify = true; + } else if (arg === '--profile') { + index += 1; + profile = args[index]; + } else if (arg?.startsWith('--profile=')) { + profile = arg.slice('--profile='.length); + } else if (!SUPPORTED_FLAGS.has(arg)) { + throw new Error(`Unknown runtime benchmark argument: ${arg}`); + } + } + + if (help) return { json, verify, profile, help }; + + if (!SUPPORTED_PROFILES.has(profile)) { + throw new Error(`profile must be one of: ${[...SUPPORTED_PROFILES].join(', ')}`); + } + + return { json, verify, profile, help }; +} + +export function runtimeBenchmarkUsage() { + return [ + 'Usage: node scripts/benchmark-runtime-efficiency.mjs [--profile=standard|smoke] [--json] [--verify] [--help]', + ' profile must be one of: standard, smoke', + ].join('\n'); +} diff --git a/scripts/consumer-bundle-boundaries.mjs b/scripts/consumer-bundle-boundaries.mjs new file mode 100644 index 0000000..368ff7c --- /dev/null +++ b/scripts/consumer-bundle-boundaries.mjs @@ -0,0 +1,364 @@ +#!/usr/bin/env node + +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { gzipSync } from 'node:zlib'; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const workspaceRoot = join(tmpdir(), `paddockjs-bundle-boundaries-${process.pid}`); +const packDir = join(workspaceRoot, 'pack'); +const appDir = join(workspaceRoot, 'app'); +const distDir = join(appDir, 'dist'); +const defaultNpmCacheDir = join(homedir(), '.npm'); +const inheritedNpmCacheDir = process.env.npm_config_cache ?? process.env.NPM_CONFIG_CACHE ?? ''; +const npmCacheDir = isExplicitNpmCache(inheritedNpmCacheDir) + ? inheritedNpmCacheDir + : join(workspaceRoot, 'npm-cache'); +const npmExecPath = process.env.npm_execpath; +const npmCommand = npmExecPath ? process.execPath : 'npm'; +const npmBaseArgs = npmExecPath ? [npmExecPath] : []; + +function usage() { + return 'Usage: node scripts/consumer-bundle-boundaries.mjs [--help]'; +} + +function parseArgs(args = process.argv.slice(2)) { + if (args.some((arg) => arg === '--help' || arg === '-h')) { + console.log(usage()); + process.exit(0); + } + if (args.length > 0) { + throw new Error(`Unknown bundle-boundary argument: ${args[0]}`); + } +} + +const BUDGETS = { + root: { + maxJsBytes: 1_250_000, + minCssBytes: 75_000, + minAssetBytes: 5_000, + }, + placeholder: { + maxJsBytes: 20_000, + maxCssBytes: 8_000, + maxAssetBytes: 0, + }, + data: { + maxJsBytes: 260_000, + maxCssBytes: 0, + maxAssetBytes: 0, + }, + environment: { + maxJsBytes: 760_000, + maxCssBytes: 0, + maxAssetBytes: 0, + }, +}; + +function run(command, args, options = {}) { + console.log(`[bundle-boundaries] ${command} ${args.join(' ')}`); + execFileSync(options.command ?? command, options.args ?? args, { + cwd: options.cwd ?? repoRoot, + stdio: 'inherit', + env: { + ...process.env, + npm_config_audit: 'false', + npm_config_cache: npmCacheDir, + npm_config_fund: 'false', + NPM_CONFIG_CACHE: npmCacheDir, + }, + }); +} + +function runNpm(args, options = {}) { + run('npm', args, { + ...options, + command: npmCommand, + args: [...npmBaseArgs, ...args], + }); +} + +function writeJson(path, value) { + writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`); +} + +function writeText(path, lines) { + writeFileSync(path, `${lines.join('\n')}\n`); +} + +function isExplicitNpmCache(cacheDir) { + return Boolean(cacheDir) && resolve(cacheDir) !== resolve(defaultNpmCacheDir); +} + +function createConsumerApp(packageTarball) { + mkdirSync(join(appDir, 'src'), { recursive: true }); + writeJson(join(appDir, 'package.json'), { + private: true, + type: 'module', + scripts: { + build: 'vite build', + }, + dependencies: { + '@inventure71/paddockjs': `file:${packageTarball}`, + vite: '8.0.10', + }, + devDependencies: {}, + }); + writeText(join(appDir, 'vite.config.js'), [ + "import { resolve } from 'node:path';", + "import { defineConfig } from 'vite';", + '', + 'export default defineConfig({', + ' build: {', + ' manifest: true,', + ' rollupOptions: {', + ' input: {', + " root: resolve(__dirname, 'root.html'),", + " placeholder: resolve(__dirname, 'placeholder.html'),", + " data: resolve(__dirname, 'data.html'),", + " environment: resolve(__dirname, 'environment.html'),", + ' },', + ' },', + ' },', + '});', + ]); + writeHtml('root', '/src/root.js'); + writeHtml('placeholder', '/src/placeholder.js'); + writeHtml('data', '/src/data.js'); + writeHtml('environment', '/src/environment.js'); + writeText(join(appDir, 'src/root.js'), [ + 'import {', + ' DEFAULT_PADDOCK_THEME,', + ' createPaddockSimulator,', + ' mountF1Simulator,', + ' resolvePaddockTheme,', + "} from '@inventure71/paddockjs';", + '', + 'globalThis.__paddockRootBoundary = {', + ' mountF1Simulator,', + ' createPaddockSimulator,', + " themeMode: resolvePaddockTheme(DEFAULT_PADDOCK_THEME).activeMode,", + '};', + ]); + writeText(join(appDir, 'src/placeholder.js'), [ + "import { createPaddockLoadingPlaceholder } from '@inventure71/paddockjs/placeholder';", + "import '@inventure71/paddockjs/placeholder.css';", + '', + 'globalThis.__paddockPlaceholderBoundary = createPaddockLoadingPlaceholder({', + " label: 'Loading simulator',", + " detail: 'Packed placeholder boundary',", + '});', + ]); + writeText(join(appDir, 'src/data.js'), [ + 'import {', + ' DriverData,', + ' createProceduralTrack,', + ' formatDriverNumber,', + ' normalizeSimulatorDrivers,', + "} from '@inventure71/paddockjs/data';", + '', + 'const drivers = [{ id: "data-alpha", name: "Data Alpha", color: "#e10600" }];', + 'const entries = [{ driverId: "data-alpha", driverNumber: 71 }];', + 'const track = createProceduralTrack(7101, { profile: "training-short" });', + '', + 'globalThis.__paddockDataBoundary = {', + ' normalized: normalizeSimulatorDrivers(drivers, { entries }),', + ' driver: new DriverData({ pace: 71 }),', + ' number: formatDriverNumber(entries[0].driverNumber),', + ' trackSampleCount: track.sampleCount,', + '};', + ]); + writeText(join(appDir, 'src/environment.js'), [ + 'import {', + ' createPaddockEnvironment,', + ' createProgressReward,', + "} from '@inventure71/paddockjs/environment';", + '', + 'const drivers = [{ id: "env-alpha", name: "Env Alpha", color: "#00ff84" }];', + 'const entries = [{ driverId: "env-alpha", driverNumber: 17 }];', + '', + 'globalThis.__paddockEnvironmentBoundary = () => {', + ' const env = createPaddockEnvironment({', + ' drivers,', + ' entries,', + ' controlledDrivers: ["env-alpha"],', + ' reward: createProgressReward(),', + ' seed: 71,', + ' trackSeed: 20260507,', + ' trackGeneration: { profile: "training-short" },', + ' });', + ' const result = env.step({ "env-alpha": { steering: 0, throttle: 1, brake: 0 } });', + ' env.destroy();', + ' return result.info.controlledDrivers;', + '};', + ]); +} + +function writeHtml(name, scriptPath) { + writeText(join(appDir, `${name}.html`), [ + '', + '', + 'PaddockJS Boundary', + '', + ` `, + '', + '', + ]); +} + +function readManifest() { + const candidates = [ + join(distDir, '.vite', 'manifest.json'), + join(distDir, 'manifest.json'), + ]; + const manifestPath = candidates.find((path) => existsSync(path)); + if (!manifestPath) { + throw new Error('Vite build did not emit a manifest.'); + } + return JSON.parse(readFileSync(manifestPath, 'utf8')); +} + +function resolveEntry(manifest, name) { + const entry = Object.values(manifest).find((chunk) => { + if (!chunk?.isEntry) return false; + return chunk.name === name || + chunk.src === `${name}.html` || + chunk.src === `src/${name}.js` || + chunk.file?.includes(`${name}-`); + }); + if (!entry) { + throw new Error(`Could not find ${name} entry in Vite manifest.`); + } + return entry; +} + +function collectEntryFiles(manifest, entry) { + const jsFiles = new Set(); + const cssFiles = new Set(); + const assetFiles = new Set(); + const visited = new Set(); + + function visit(chunk) { + if (!chunk?.file || visited.has(chunk.file)) return; + visited.add(chunk.file); + if (chunk.file.endsWith('.js')) jsFiles.add(chunk.file); + chunk.css?.forEach((file) => cssFiles.add(file)); + chunk.assets?.forEach((file) => assetFiles.add(file)); + chunk.imports?.forEach((importKey) => visit(manifest[importKey])); + chunk.dynamicImports?.forEach((importKey) => visit(manifest[importKey])); + } + + visit(entry); + return { + jsFiles: [...jsFiles].sort(), + cssFiles: [...cssFiles].sort(), + assetFiles: [...assetFiles].sort(), + }; +} + +function fileSize(file) { + return statSync(join(distDir, file)).size; +} + +function gzipSize(file) { + return gzipSync(readFileSync(join(distDir, file))).length; +} + +function summarizeFiles(files) { + const bytes = files.reduce((total, file) => total + fileSize(file), 0); + const gzipBytes = files.reduce((total, file) => total + gzipSize(file), 0); + return { bytes, gzipBytes }; +} + +function summarizeEntry(name, files) { + const js = summarizeFiles(files.jsFiles); + const css = summarizeFiles(files.cssFiles); + const assets = summarizeFiles(files.assetFiles); + return { + name, + jsBytes: js.bytes, + jsGzipBytes: js.gzipBytes, + cssBytes: css.bytes, + cssGzipBytes: css.gzipBytes, + assetBytes: assets.bytes, + files, + }; +} + +function formatBytes(bytes) { + return `${(bytes / 1024).toFixed(1)} kB`; +} + +function assertBudget(summary) { + const budget = BUDGETS[summary.name]; + assertMax(summary.jsBytes, budget.maxJsBytes, summary.name, 'JavaScript'); + assertMax(summary.cssBytes, budget.maxCssBytes, summary.name, 'CSS'); + assertMax(summary.assetBytes, budget.maxAssetBytes, summary.name, 'asset'); + assertMin(summary.cssBytes, budget.minCssBytes, summary.name, 'CSS'); + assertMin(summary.assetBytes, budget.minAssetBytes, summary.name, 'asset'); +} + +function assertMax(actual, max, name, label) { + if (typeof max !== 'number') return; + if (actual > max) { + throw new Error(`${name} ${label} bundle is ${formatBytes(actual)}, above ${formatBytes(max)}.`); + } +} + +function assertMin(actual, min, name, label) { + if (typeof min !== 'number') return; + if (actual < min) { + throw new Error(`${name} ${label} bundle is ${formatBytes(actual)}, below expected ${formatBytes(min)}.`); + } +} + +function printSummary(summary) { + console.log([ + `[bundle-boundaries] ${summary.name}:`, + `js=${formatBytes(summary.jsBytes)} (${formatBytes(summary.jsGzipBytes)} gzip)`, + `css=${formatBytes(summary.cssBytes)} (${formatBytes(summary.cssGzipBytes)} gzip)`, + `assets=${formatBytes(summary.assetBytes)}`, + ].join(' ')); +} + +try { + parseArgs(); +} catch (error) { + console.error(`${usage()}\n\n${error.message}`); + process.exit(1); +} + +try { + if (existsSync(workspaceRoot)) rmSync(workspaceRoot, { recursive: true, force: true }); + mkdirSync(packDir, { recursive: true }); + mkdirSync(appDir, { recursive: true }); + + runNpm(['pack', '--pack-destination', packDir]); + const packageTarball = readdirSync(packDir) + .filter((name) => name.endsWith('.tgz')) + .map((name) => join(packDir, name))[0]; + if (!packageTarball) { + throw new Error(`npm pack did not create a tarball in ${packDir}`); + } + + createConsumerApp(packageTarball); + runNpm(['install'], { cwd: appDir }); + runNpm(['run', 'build'], { cwd: appDir }); + + const manifest = readManifest(); + const summaries = ['root', 'placeholder', 'data', 'environment'].map((name) => ( + summarizeEntry(name, collectEntryFiles(manifest, resolveEntry(manifest, name))) + )); + summaries.forEach(printSummary); + summaries.forEach(assertBudget); + console.log('[bundle-boundaries] packed package subpath bundle boundaries verified'); +} finally { + if (process.env.PADDOCKJS_KEEP_CONSUMER_BUNDLE_BOUNDARIES !== '1') { + rmSync(workspaceRoot, { recursive: true, force: true }); + } else { + console.log(`[bundle-boundaries] kept temp workspace: ${workspaceRoot}`); + } +} diff --git a/scripts/consumer-package-smoke.mjs b/scripts/consumer-package-smoke.mjs index fde3084..55e2b54 100644 --- a/scripts/consumer-package-smoke.mjs +++ b/scripts/consumer-package-smoke.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; +import { homedir, tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -10,24 +10,60 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const workspaceRoot = join(tmpdir(), `paddockjs-consumer-${process.pid}`); const packDir = join(workspaceRoot, 'pack'); const appDir = join(workspaceRoot, 'app'); +const defaultNpmCacheDir = join(homedir(), '.npm'); +const inheritedNpmCacheDir = process.env.npm_config_cache ?? process.env.NPM_CONFIG_CACHE ?? ''; +const npmCacheDir = isExplicitNpmCache(inheritedNpmCacheDir) + ? inheritedNpmCacheDir + : join(workspaceRoot, 'npm-cache'); +const npmExecPath = process.env.npm_execpath; +const npmCommand = npmExecPath ? process.execPath : 'npm'; +const npmBaseArgs = npmExecPath ? [npmExecPath] : []; + +function usage() { + return 'Usage: node scripts/consumer-package-smoke.mjs [--help]'; +} + +function parseArgs(args = process.argv.slice(2)) { + if (args.some((arg) => arg === '--help' || arg === '-h')) { + console.log(usage()); + process.exit(0); + } + if (args.length > 0) { + throw new Error(`Unknown consumer smoke argument: ${args[0]}`); + } +} function run(command, args, options = {}) { console.log(`[consumer-smoke] ${command} ${args.join(' ')}`); - execFileSync(command, args, { + execFileSync(options.command ?? command, options.args ?? args, { cwd: options.cwd ?? repoRoot, stdio: 'inherit', env: { ...process.env, npm_config_audit: 'false', + npm_config_cache: npmCacheDir, npm_config_fund: 'false', + NPM_CONFIG_CACHE: npmCacheDir, }, }); } +function runNpm(args, options = {}) { + run('npm', args, { + ...options, + command: npmCommand, + args: [...npmBaseArgs, ...args], + }); +} + function writeJson(path, value) { writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`); } +function isExplicitNpmCache(cacheDir) { + return Boolean(cacheDir) && resolve(cacheDir) !== resolve(defaultNpmCacheDir); +} + function createConsumerApp(packageTarball) { mkdirSync(join(appDir, 'src'), { recursive: true }); writeJson(join(appDir, 'package.json'), { @@ -196,12 +232,19 @@ void html; }); } +try { + parseArgs(); +} catch (error) { + console.error(`${usage()}\n\n${error.message}`); + process.exit(1); +} + try { if (existsSync(workspaceRoot)) rmSync(workspaceRoot, { recursive: true, force: true }); mkdirSync(packDir, { recursive: true }); mkdirSync(appDir, { recursive: true }); - run('npm', ['pack', '--pack-destination', packDir]); + runNpm(['pack', '--pack-destination', packDir]); const packageTarball = readdirSync(packDir) .filter((name) => name.endsWith('.tgz')) .map((name) => join(packDir, name))[0]; @@ -210,7 +253,7 @@ try { } createConsumerApp(packageTarball); - run('npm', ['install'], { cwd: appDir }); + runNpm(['install'], { cwd: appDir }); run('node', [ '--input-type=module', '-e', @@ -222,7 +265,7 @@ try { "import { createPaddockLoadingPlaceholder } from '@inventure71/paddockjs/placeholder'; const html = createPaddockLoadingPlaceholder({ label: 'Smoke' }); if (!html.includes('data-paddock-placeholder')) throw new Error('placeholder subpath import failed');", ], { cwd: appDir }); run(join(repoRoot, 'node_modules/.bin/tsc'), ['-p', 'tsconfig.data-subpath.json'], { cwd: appDir }); - run('npm', ['run', 'build'], { cwd: appDir }); + runNpm(['run', 'build'], { cwd: appDir }); console.log('[consumer-smoke] packed package installed and built in a fresh Vite consumer app'); } finally { if (process.env.PADDOCKJS_KEEP_CONSUMER_SMOKE !== '1') { diff --git a/scripts/profile-hotspots.mjs b/scripts/profile-hotspots.mjs new file mode 100644 index 0000000..3ad2775 --- /dev/null +++ b/scripts/profile-hotspots.mjs @@ -0,0 +1,74 @@ +// Ad-hoc CPU profiling driver: runs the heaviest runtime loops so +// `node --cpu-prof` can attribute time to real functions. +import { createRaceSimulation, FIXED_STEP } from '../src/simulation/raceSimulation.js'; +import { interpolateRenderSnapshotInto } from '../src/rendering/renderSnapshot.js'; + +const DEFAULT_STEPS = 20000; + +function usage() { + return [ + 'Usage: node scripts/profile-hotspots.mjs [steps]', + ' steps: positive integer number of fixed simulation steps to profile', + ].join('\n'); +} + +function parseSteps(raw) { + if (raw == null) return DEFAULT_STEPS; + const value = Number(raw); + if (!Number.isInteger(value) || value <= 0) { + throw new Error('steps must be a positive integer'); + } + return value; +} + +function parseArgs(argv) { + const args = argv.slice(2); + if (args.includes('--help') || args.includes('-h')) { + console.log(usage()); + process.exit(0); + } + try { + if (args.length > 1) { + throw new Error(`Unexpected argument: ${args[1]}`); + } + return { steps: parseSteps(args[0]) }; + } catch (error) { + console.error(`${usage()}\n\n${error.message}`); + process.exit(1); + } +} + +const { steps: STEPS } = parseArgs(process.argv); + +const drivers = Array.from({ length: 20 }, (_, index) => ({ + id: `bench-${index}`, + code: `B${index}`, + icon: `B${index}`, + raceName: `Bench ${index}`, + name: `Bench Driver ${index}`, + color: ['#e10600', '#00a3ff', '#f1c65b', '#38bdf8', '#22c55e'][index % 5], + tire: 'M', + pace: 1, + racecraft: 0.8, +})); +const sim = createRaceSimulation({ + drivers, + seed: 7, + trackSeed: 11, + totalLaps: 50, + physicsMode: 'advanced', + warmup: { enabled: false }, +}); + +let renderBuffer = {}; +let sourceBuffer = {}; +const t0 = performance.now(); +for (let i = 0; i < STEPS; i += 1) { + sim.step(FIXED_STEP); + // Mirror the frame loop: a render snapshot every step, a full snapshot at DOM cadence (~ every 6 steps). + sourceBuffer = sim.snapshotRenderInto(sourceBuffer); + renderBuffer = interpolateRenderSnapshotInto(renderBuffer, sourceBuffer, 0.5); + if (i % 6 === 0) sim.snapshot(); +} +const t1 = performance.now(); +console.log(`steps=${STEPS} totalMs=${(t1 - t0).toFixed(1)} msPerStep=${((t1 - t0) / STEPS).toFixed(4)}`); diff --git a/smoke/browser-smoke.mjs b/smoke/browser-smoke.mjs index ec9aa78..e5d95ac 100644 --- a/smoke/browser-smoke.mjs +++ b/smoke/browser-smoke.mjs @@ -7,14 +7,24 @@ import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { inflateSync } from 'node:zlib'; import { chromium } from 'playwright'; +import { browserSmokeUsage, parseBrowserSmokeArgs } from './browserSmokeArgs.mjs'; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const previewRoot = resolve(repoRoot, 'local-preview'); const previewDistIndex = resolve(previewRoot, 'dist', 'index.html'); const deterministicTemplatesPath = '/templates.html?completeTrackSeed=20260430'; -const cliArgs = new Set(process.argv.slice(2)); -const quickMode = cliArgs.has('--quick'); -const skipBuild = cliArgs.has('--skip-build') || process.env.PADDOCKJS_BROWSER_SMOKE_SKIP_BUILD === '1'; +let cliOptions; +try { + cliOptions = parseBrowserSmokeArgs(process.argv.slice(2)); +} catch (error) { + console.error(`${browserSmokeUsage()}\n\n${error.message}`); + process.exit(1); +} +const { quickMode, skipBuild } = cliOptions; +if (cliOptions.help) { + console.log(browserSmokeUsage()); + process.exit(0); +} const startupAssetDelayMs = quickMode ? 250 : 750; function run(command, args, options = {}) { @@ -2166,6 +2176,9 @@ async function smokePolicyRunner(page, baseUrl) { text.includes('"visualFrame": 4') && text.includes('"visualFrameSkip": 4') && text.includes('"step": 4') && text.includes('"frameMetrics"') && text.includes('"lastExpertStepMs"') && + text.includes('"trackDiagnostics"') && + text.includes('"hasTrackIndex": true') && + text.includes('"queryIndexEnumerable": false') && text.includes('"action"') && text.includes('"actionSpec"') && text.includes('"observationSpec"') && text.includes('"configuration": "generation"') && @@ -2220,6 +2233,11 @@ async function smokePolicyRunner(page, baseUrl) { 'policy runner: expected visible physical-driver senses panel', ); const activeReadout = JSON.parse(await page.locator('[data-policy-runner-readout]').textContent()); + assert( + activeReadout.trackDiagnostics?.hasTrackIndex === true && + activeReadout.trackDiagnostics?.queryIndexEnumerable === false, + 'policy runner: expected readout to expose live non-enumerable track index diagnostics', + ); const rayChannels = activeReadout.observationSpec?.object?.rays?.channels ?? []; assert( rayChannels.includes('illegalSurface') && !rayChannels.includes('barrier'), diff --git a/smoke/browserSmokeArgs.mjs b/smoke/browserSmokeArgs.mjs new file mode 100644 index 0000000..bbaf1ad --- /dev/null +++ b/smoke/browserSmokeArgs.mjs @@ -0,0 +1,36 @@ +const HELP_FLAGS = new Set(['--help', '-h']); +const SUPPORTED_ARGS = new Set(['--quick', '--full', '--skip-build', ...HELP_FLAGS]); + +export function parseBrowserSmokeArgs(args = [], { skipBuildEnv = process.env.PADDOCKJS_BROWSER_SMOKE_SKIP_BUILD === '1' } = {}) { + for (const arg of args) { + if (!SUPPORTED_ARGS.has(arg)) { + throw new Error(`Unknown browser smoke argument: ${arg}`); + } + } + const help = args.some((arg) => HELP_FLAGS.has(arg)); + if (help) { + return { + help: true, + quickMode: false, + fullMode: false, + skipBuild: false, + }; + } + if (args.includes('--quick') && args.includes('--full')) { + throw new Error('Choose either --quick or --full, not both'); + } + return { + quickMode: args.includes('--quick'), + fullMode: args.includes('--full'), + skipBuild: args.includes('--skip-build') || skipBuildEnv, + }; +} + +export function browserSmokeUsage() { + return [ + 'Usage: node smoke/browser-smoke.mjs [--quick|--full] [--skip-build] [--help]', + ' --quick runs only the quick smoke.', + ' --full runs the full smoke matrix.', + ' --skip-build reuses local-preview/dist.', + ].join('\n'); +} diff --git a/src/__tests__/componentApi.test.js b/src/__tests__/componentApi.test.js index 28bf8f3..1e4f9a4 100644 --- a/src/__tests__/componentApi.test.js +++ b/src/__tests__/componentApi.test.js @@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'; import { Container, Texture } from 'pixi.js'; import { describe, expect, test, vi } from 'vitest'; import { slowTest } from './testModes.js'; +import { createBrowserExpertAdapter } from '../app/BrowserExpertAdapter.js'; import { F1SimulatorApp } from '../app/F1SimulatorApp.js'; import { installLayoutSupport } from '../app/layoutSupport.js'; import { createRafScheduler } from '../app/layoutScheduler.js'; @@ -2832,6 +2833,8 @@ describe('f1 simulator component API', () => { }); app.sim = app.createRaceSimulation(); app.drsLayer = new Container(); + app.carLayer = new Container(); + app.textures = { car: Texture.EMPTY }; app.trackAsset = { render: vi.fn() }; app.updateDom = vi.fn(); @@ -2875,6 +2878,8 @@ describe('f1 simulator component API', () => { }); app.sim = app.createRaceSimulation(); app.drsLayer = new Container(); + app.carLayer = new Container(); + app.textures = { car: Texture.EMPTY }; app.trackAsset = { render: vi.fn() }; app.updateDom = vi.fn(); app.renderInitialFrame = vi.fn(); @@ -2954,6 +2959,41 @@ describe('f1 simulator component API', () => { expect(app.expert).not.toBeUndefined(); }); + test('browser expert reset preserves resolved physics mode', () => { + const app = new F1SimulatorApp(createRootStub(null), { + drivers: [{ id: 'alpha', name: 'Alpha Project', color: '#ff2d55' }], + assets: DEFAULT_F1_SIMULATOR_ASSETS, + initialCameraMode: 'leader', + totalLaps: 10, + seed: 1971, + trackSeed: 10101, + physicsMode: 'advanced', + ui: {}, + expert: { + enabled: true, + controlledDrivers: ['alpha'], + }, + }); + app.sim = app.createRaceSimulation(); + app.drsLayer = new Container(); + app.carLayer = new Container(); + app.textures = { car: Texture.EMPTY }; + app.trackAsset = { render: vi.fn() }; + app.updateDom = vi.fn(); + app.renderInitialFrame = vi.fn(); + app.renderTrack = vi.fn(); + app.renderExpertFrame = vi.fn(); + + const expert = createBrowserExpertAdapter(app, { + enabled: true, + controlledDrivers: ['alpha'], + }); + const result = expert.reset(); + + expect(result.state.snapshot.physicsMode).toBe('advanced'); + expect(app.options.physicsMode).toBe('advanced'); + }); + test('destroy tears down the browser expert adapter', () => { const app = new F1SimulatorApp(createRootStub(null), { drivers: [{ id: 'alpha', name: 'Alpha Project', color: '#ff2d55' }], diff --git a/src/__tests__/environment.test.js b/src/__tests__/environment.test.js index ad0cfd5..a0af912 100644 --- a/src/__tests__/environment.test.js +++ b/src/__tests__/environment.test.js @@ -2428,7 +2428,7 @@ describe('paddock environment observations and runtime', () => { expect(result.observation[batch.ids[0]]).not.toHaveProperty('object'); expect(noRayTimings.p95MsPerStep).toBeLessThan(25); expect(timings.medianMsPerStep).toBeLessThan(25); - expect(timings.p90MsPerStep).toBeLessThan(noRayTimings.p95MsPerStep * 6); + expect(timings.p90MsPerStep).toBeLessThan(25); expect(timings.maxMsPerStep).toBeLessThan(75); env.destroy(); }); diff --git a/src/__tests__/localPreviewMarkup.test.js b/src/__tests__/localPreviewMarkup.test.js index 5a82d73..5fa868b 100644 --- a/src/__tests__/localPreviewMarkup.test.js +++ b/src/__tests__/localPreviewMarkup.test.js @@ -201,4 +201,14 @@ describe('local preview markup contracts', () => { expect(main).toContain('endReason'); expect(main).toContain('Stopped:'); }); + + test('showcase snippets do not advertise preview-only policy helpers as package exports', () => { + const catalog = readFile('local-preview/src/showcaseCatalog.js'); + + expect(catalog).not.toMatch( + /import\s*\{[^}]*\bcreateDistilledPolicyController\b[^}]*\}\s*from\s*'@inventure71\/paddockjs'/, + ); + expect(catalog).not.toMatch(/code:\s*`[^`]*\bcreatePolicyServerController\b/); + expect(catalog).not.toMatch(/code:\s*`[^`]*\bcreateLiveNodeViewController\b/); + }); }); diff --git a/src/__tests__/physicsMode.test.js b/src/__tests__/physicsMode.test.js index 9328a65..054990b 100644 --- a/src/__tests__/physicsMode.test.js +++ b/src/__tests__/physicsMode.test.js @@ -74,6 +74,10 @@ describe('physics mode', () => { drivers: PROJECT_DRIVERS.slice(0, 1), physicsMode: 'invalid', }); + const unsupportedBrowserFallback = resolveF1SimulatorOptions({ + drivers: PROJECT_DRIVERS.slice(0, 1), + physicsMode: 'unsupported-physics-mode', + }); const env = createPaddockEnvironment({ drivers: PROJECT_DRIVERS.slice(0, 1), entries: CHAMPIONSHIP_ENTRY_BLUEPRINTS, @@ -81,11 +85,20 @@ describe('physics mode', () => { physicsMode: 'advanced', rules: { standingStart: false }, }); + const unsupportedEnvFallback = createPaddockEnvironment({ + drivers: PROJECT_DRIVERS.slice(0, 1), + entries: CHAMPIONSHIP_ENTRY_BLUEPRINTS, + controlledDrivers: [PROJECT_DRIVERS[0].id], + physicsMode: 'unsupported-physics-mode', + rules: { standingStart: false }, + }); expect(browser.physicsMode).toBe('advanced'); expect(removedAlias.physicsMode).toBe('arcade'); expect(fallback.physicsMode).toBe('arcade'); + expect(unsupportedBrowserFallback.physicsMode).toBe('arcade'); expect(env.reset().state.snapshot.physicsMode).toBe('advanced'); + expect(unsupportedEnvFallback.reset().state.snapshot.physicsMode).toBe('arcade'); }); test('keeps arcade physics as the default race simulation mode', () => { diff --git a/src/__tests__/profileHotspotsScript.test.js b/src/__tests__/profileHotspotsScript.test.js new file mode 100644 index 0000000..291523b --- /dev/null +++ b/src/__tests__/profileHotspotsScript.test.js @@ -0,0 +1,46 @@ +import { spawnSync } from 'node:child_process'; +import { resolve } from 'node:path'; +import { describe, expect, test } from 'vitest'; + +const repoRoot = resolve(import.meta.dirname, '../..'); + +describe('profile hotspots script', () => { + test('rejects invalid step counts before reporting timing output', () => { + const result = spawnSync( + process.execPath, + [resolve(repoRoot, 'scripts/profile-hotspots.mjs'), 'nope'], + { cwd: repoRoot, encoding: 'utf8' }, + ); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('Usage: node scripts/profile-hotspots.mjs'); + expect(result.stderr).toContain('steps must be a positive integer'); + expect(result.stderr).not.toContain('steps=NaN'); + }); + + test('rejects extra arguments before running the profiler', () => { + const result = spawnSync( + process.execPath, + [resolve(repoRoot, 'scripts/profile-hotspots.mjs'), '5', 'extra'], + { cwd: repoRoot, encoding: 'utf8' }, + ); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('Usage: node scripts/profile-hotspots.mjs'); + expect(result.stderr).toContain('Unexpected argument: extra'); + }); + + test('prints usage for help without treating it as invalid input', () => { + const result = spawnSync( + process.execPath, + [resolve(repoRoot, 'scripts/profile-hotspots.mjs'), '--help'], + { cwd: repoRoot, encoding: 'utf8' }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('Usage: node scripts/profile-hotspots.mjs'); + expect(result.stderr).toBe(''); + }); +}); diff --git a/src/__tests__/publicApi.types.ts b/src/__tests__/publicApi.types.ts index e9be3a2..af5e9e3 100644 --- a/src/__tests__/publicApi.types.ts +++ b/src/__tests__/publicApi.types.ts @@ -29,7 +29,10 @@ import { type F1SimulatorExpertApi, type F1SimulatorOptions, type NormalizedSimulatorDriver, + type PaddockEnvironmentResult, + type PaddockResolvedProceduralTrackOptions, type PaddockThemeTokenValue, + type PaddockProceduralTrack, type F1SimulatorTheme, type PaddockDriverController, type ResolvedPaddockTheme, @@ -54,6 +57,7 @@ import { kphToSimSpeed as dataSubpathKphToSimSpeed, normalizeSimulatorDrivers as normalizeDataSubpathDrivers, simSpeedToKph as dataSubpathSimSpeedToKph, + type PaddockResolvedProceduralTrackOptions as DataSubpathResolvedProceduralTrackOptions, } from '../data/index.js'; import { createPaddockDriverControllerLoop as createEnvironmentDriverControllerLoop, @@ -70,6 +74,7 @@ import { type PaddockReplayGhostTrajectorySample as EnvPaddockReplayGhostTrajectorySample, type PaddockReplayGhostOptions as EnvPaddockReplayGhostOptions, type PaddockReplayGhostSnapshot as EnvPaddockReplayGhostSnapshot, + type PaddockResolvedProceduralTrackOptions as EnvPaddockResolvedProceduralTrackOptions, } from '../environment/index.js'; import { createPaddockLoadingPlaceholder, @@ -103,6 +108,12 @@ type _RootEnvParityReplayOptions = AssertTrue< type _RootEnvParityReplaySnapshot = AssertTrue< IsEqual >; +type _RootDataParityResolvedTrackOptions = AssertTrue< + IsEqual +>; +type _RootEnvParityResolvedTrackOptions = AssertTrue< + IsEqual +>; // @ts-expect-error Theme tokens are CSS strings; numeric values would produce invalid runtime CSS. const invalidNumericThemeToken: PaddockThemeTokenValue = 720; @@ -144,13 +155,22 @@ const dataSubpathDrivers = normalizeDataSubpathDrivers(DEMO_PROJECT_DRIVERS, { const dataSubpathGrid = buildDataSubpathDriverGrid(dataSubpathDrivers, CHAMPIONSHIP_ENTRY_BLUEPRINTS); const dataSubpathDriver = new DataSubpathDriverData({ pace: 70 }); const dataSubpathVehicle = new DataSubpathVehicleData({ id: 'typed-data-car', name: 'Typed Data Car' }); -const dataSubpathTrack: unknown = createDataSubpathProceduralTrack(7101); +const dataSubpathTrack: PaddockProceduralTrack = createDataSubpathProceduralTrack(7101); +const dataSubpathTrackSampleCount: number = dataSubpathTrack.sampleCount; +const dataSubpathResolvedLengthMin: number | undefined = dataSubpathTrack.generationOptions?.length.min; +const dataSubpathResolvedCacheKey: string | undefined = dataSubpathTrack.generationOptions?.cacheKey; +// @ts-expect-error Runtime stores resolved sim-unit fields, not the caller-facing meter option names. +const invalidResolvedLengthMeters = dataSubpathTrack.generationOptions?.length.minMeters; const dataSubpathNumber: string = formatDataSubpathDriverNumber(71); const dataSubpathSpeed: number = dataSubpathSimSpeedToKph(dataSubpathKphToSimSpeed(180)); void dataSubpathGrid; void dataSubpathDriver; void dataSubpathVehicle; void dataSubpathTrack; +void dataSubpathTrackSampleCount; +void dataSubpathResolvedLengthMin; +void dataSubpathResolvedCacheKey; +void invalidResolvedLengthMeters; void dataSubpathNumber; void dataSubpathSpeed; @@ -326,12 +346,14 @@ const options: F1SimulatorOptions = { }, }; -const typedProceduralTrack: unknown = createProceduralTrack(4101, { +const typedProceduralTrack: PaddockProceduralTrack = createProceduralTrack(4101, { profile: 'training-medium', minLengthMeters: 1600, includePitLane: false, }); +const typedProceduralTrackWidth: number = typedProceduralTrack.width; void typedProceduralTrack; +void typedProceduralTrackWidth; const controller: PaddockSimulatorController = createPaddockSimulator(options); const pitCameraController: PaddockSimulatorController = createPaddockSimulator({ @@ -379,6 +401,13 @@ controller.setRedFlagDeployed(false); const maybeExpertController: F1SimulatorExpertApi | null = controller.expert; const maybeExpertActionSpec = maybeExpertController?.getActionSpec(); const maybeExpertObservationSpec = maybeExpertController?.getObservationSpec(); +const maybeExpertResetResult: PaddockEnvironmentResult | undefined = maybeExpertController?.reset(); +const maybeExpertStepResult: PaddockEnvironmentResult | undefined = maybeExpertController?.step({ + budget: { steering: 0, throttle: 1, brake: 0 }, +}); +const maybeExpertObservation: PaddockEnvironmentResult['observation'] | undefined = + maybeExpertController?.getObservation(); +const maybeExpertState: PaddockEnvironmentResult['state'] | undefined = maybeExpertController?.getState(); maybeExpertController?.attachExternalRenderer({ subscribe(onFrame) { onFrame({ @@ -393,6 +422,10 @@ const maybeExternalRendererState = maybeExpertController?.getExternalRendererSta maybeExpertController?.detachExternalRenderer(); void maybeExpertActionSpec; void maybeExpertObservationSpec; +void maybeExpertResetResult; +void maybeExpertStepResult; +void maybeExpertObservation; +void maybeExpertState; void maybeExternalRendererState; void maybeExpertController; void maybeServedPenalty; @@ -515,7 +548,7 @@ const typedEnvironmentLoop = createEnvironmentDriverControllerLoop({ runtime: env, controller: typedDriverController, }); -typedLoop.stepFrame().then((result) => void result); +typedLoop.stepFrame().then((result: PaddockEnvironmentResult) => void result); typedEnvironmentLoop.stop(); const resetResult = env.reset(); const actionSpec = env.getActionSpec(); diff --git a/src/__tests__/runtimeEfficiencyBenchmarks.test.js b/src/__tests__/runtimeEfficiencyBenchmarks.test.js index 266c658..6b802a8 100644 --- a/src/__tests__/runtimeEfficiencyBenchmarks.test.js +++ b/src/__tests__/runtimeEfficiencyBenchmarks.test.js @@ -1,4 +1,4 @@ -import { execFileSync } from 'node:child_process'; +import { execFileSync, spawnSync } from 'node:child_process'; import { beforeAll, describe, expect, test } from 'vitest'; import { REQUIRED_RUNTIME_BENCHMARK_CATEGORIES, @@ -21,6 +21,38 @@ describe('runtime efficiency benchmarks', () => { return smokeResults; } + test('CLI rejects invalid profiles before printing benchmark JSON', () => { + const result = spawnSync( + process.execPath, + ['scripts/benchmark-runtime-efficiency.mjs', '--profile=bogus', '--json', '--verify'], + { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }, + ); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('Usage: node scripts/benchmark-runtime-efficiency.mjs'); + expect(result.stderr).toContain('profile must be one of: standard, smoke'); + }); + + test('CLI prints usage for help before running benchmarks', () => { + const result = spawnSync( + process.execPath, + ['scripts/benchmark-runtime-efficiency.mjs', '--help'], + { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('Usage: node scripts/benchmark-runtime-efficiency.mjs'); + expect(result.stdout).not.toContain('"benchmarks"'); + expect(result.stderr).toBe(''); + }); + test('cover the simulation, sensor, snapshot, render, and DOM hot paths', () => { const results = getSmokeResults(); diff --git a/src/__tests__/scriptArgs.test.js b/src/__tests__/scriptArgs.test.js index e6d9f75..595311d 100644 --- a/src/__tests__/scriptArgs.test.js +++ b/src/__tests__/scriptArgs.test.js @@ -1,4 +1,6 @@ +import { spawnSync } from 'node:child_process'; import { describe, expect, test } from 'vitest'; +import { parseBrowserSmokeArgs } from '../../smoke/browserSmokeArgs.mjs'; import { buildVitestArgs } from '../../scripts/vitestArgs.mjs'; describe('test script helpers', () => { @@ -24,3 +26,116 @@ describe('test script helpers', () => { expect(buildVitestArgs(['--slow', '--runInBand'])).toEqual(['run', 'src', '--maxWorkers=1', '--testTimeout=30000']); }); }); + +describe('browser smoke script helpers', () => { + test('rejects unknown browser smoke flags before launching a preview', () => { + expect(() => parseBrowserSmokeArgs(['--quick', '--skip-build', '--bogus'])).toThrow( + 'Unknown browser smoke argument: --bogus', + ); + }); + + test('rejects conflicting browser smoke modes before launching a preview', () => { + expect(() => parseBrowserSmokeArgs(['--quick', '--full'])).toThrow('Choose either --quick or --full, not both'); + }); + + test('parses browser smoke mode flags explicitly', () => { + expect(parseBrowserSmokeArgs(['--quick', '--skip-build'], { skipBuildEnv: false })).toEqual({ + quickMode: true, + fullMode: false, + skipBuild: true, + }); + expect(parseBrowserSmokeArgs(['--full'], { skipBuildEnv: true })).toEqual({ + quickMode: false, + fullMode: true, + skipBuild: true, + }); + }); + + test('prints browser smoke usage for help before launching a preview', () => { + const result = spawnSync(process.execPath, ['smoke/browser-smoke.mjs', '--help'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('Usage: node smoke/browser-smoke.mjs'); + expect(result.stdout).not.toContain('[browser-smoke]'); + expect(result.stderr).toBe(''); + }); +}); + +describe('consumer verification script helpers', () => { + test('prints consumer smoke usage for help before packing a workspace', () => { + const result = spawnSync(process.execPath, ['scripts/consumer-package-smoke.mjs', '--help'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('Usage: node scripts/consumer-package-smoke.mjs'); + expect(result.stdout).not.toContain('[consumer-smoke]'); + expect(result.stderr).toBe(''); + }); + + test('rejects unknown consumer smoke arguments before packing a workspace', () => { + const result = spawnSync(process.execPath, ['scripts/consumer-package-smoke.mjs', '--bogus'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('Usage: node scripts/consumer-package-smoke.mjs'); + expect(result.stderr).toContain('Unknown consumer smoke argument: --bogus'); + }); + + test('prints bundle-boundary usage for help before packing a workspace', () => { + const result = spawnSync(process.execPath, ['scripts/consumer-bundle-boundaries.mjs', '--help'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('Usage: node scripts/consumer-bundle-boundaries.mjs'); + expect(result.stdout).not.toContain('[bundle-boundaries]'); + expect(result.stderr).toBe(''); + }); + + test('rejects unknown bundle-boundary arguments before packing a workspace', () => { + const result = spawnSync(process.execPath, ['scripts/consumer-bundle-boundaries.mjs', '--bogus'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('Usage: node scripts/consumer-bundle-boundaries.mjs'); + expect(result.stderr).toContain('Unknown bundle-boundary argument: --bogus'); + }); +}); + +describe('track benchmark script helpers', () => { + test('prints track benchmark usage for help before running benchmarks', () => { + const result = spawnSync(process.execPath, ['scripts/benchmark-track-query-index.mjs', '--help'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('Usage: node scripts/benchmark-track-query-index.mjs'); + expect(result.stdout).not.toContain('| benchmark |'); + expect(result.stderr).toBe(''); + }); + + test('rejects unknown track benchmark arguments before running benchmarks', () => { + const result = spawnSync(process.execPath, ['scripts/benchmark-track-query-index.mjs', '--bogus'], { + cwd: new URL('../..', import.meta.url), + encoding: 'utf8', + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('Usage: node scripts/benchmark-track-query-index.mjs'); + expect(result.stderr).toContain('Unknown track benchmark argument: --bogus'); + }); +}); diff --git a/src/data/index.d.ts b/src/data/index.d.ts index 40c877a..8a1a173 100644 --- a/src/data/index.d.ts +++ b/src/data/index.d.ts @@ -38,6 +38,69 @@ export interface PaddockProceduralTrackOptions { }; } +export interface PaddockTrackPoint { + x: number; + y: number; +} + +export interface PaddockDrsZone { + id: string; + startRatio: number; + endRatio: number; +} + +export interface PaddockResolvedProceduralTrackOptions { + profile: PaddockProceduralTrackProfile; + length: { + min: number; + max: number; + }; + startStraight: { + grid: number; + exit: number; + blend: number; + lockExtra: number; + }; + pitLane: { + enabled: boolean; + }; + shape: { + scale: number; + cornerDensity: number; + variation: number; + }; + validation: { + minClearanceMultiplier: number; + minShapeVariation: number; + minNonAdjacentArcDistance: number; + maxLocalTurnRadians: number; + maxSampleHeadingDeltaRadians: number; + }; + attempts: { + primary: number; + fallback: number; + }; + cacheKey: string; + [key: string]: unknown; +} + +export interface PaddockProceduralTrack { + name: string; + width: number; + kerbWidth: number; + gravelWidth: number; + runoffWidth: number; + barrierWidth: number; + sampleCount: number; + seed?: number; + curveInterpolation?: string; + centerlineControls?: readonly PaddockTrackPoint[]; + drsZones?: readonly PaddockDrsZone[] | null; + pitLane?: { enabled?: boolean } | null; + generationOptions?: PaddockResolvedProceduralTrackOptions; + [key: string]: unknown; +} + export interface CustomField { label: string; value: string; @@ -207,6 +270,6 @@ export function normalizeSimulatorDrivers( drivers: SimulatorDriver[], options?: { entries?: ChampionshipEntryBlueprint[]; caller?: string }, ): NormalizedSimulatorDriver[]; -export function createProceduralTrack(seed?: number | string, options?: PaddockProceduralTrackOptions): unknown; +export function createProceduralTrack(seed?: number | string, options?: PaddockProceduralTrackOptions): PaddockProceduralTrack; export function kphToSimSpeed(kph: number): number; export function simSpeedToKph(simSpeed: number): number; diff --git a/src/environment/index.d.ts b/src/environment/index.d.ts index 7bdbd03..dae46f7 100644 --- a/src/environment/index.d.ts +++ b/src/environment/index.d.ts @@ -39,6 +39,69 @@ export interface PaddockProceduralTrackOptions { }; } +export interface PaddockTrackPoint { + x: number; + y: number; +} + +export interface PaddockDrsZone { + id: string; + startRatio: number; + endRatio: number; +} + +export interface PaddockResolvedProceduralTrackOptions { + profile: PaddockProceduralTrackProfile; + length: { + min: number; + max: number; + }; + startStraight: { + grid: number; + exit: number; + blend: number; + lockExtra: number; + }; + pitLane: { + enabled: boolean; + }; + shape: { + scale: number; + cornerDensity: number; + variation: number; + }; + validation: { + minClearanceMultiplier: number; + minShapeVariation: number; + minNonAdjacentArcDistance: number; + maxLocalTurnRadians: number; + maxSampleHeadingDeltaRadians: number; + }; + attempts: { + primary: number; + fallback: number; + }; + cacheKey: string; + [key: string]: unknown; +} + +export interface PaddockProceduralTrack { + name: string; + width: number; + kerbWidth: number; + gravelWidth: number; + runoffWidth: number; + barrierWidth: number; + sampleCount: number; + seed?: number; + curveInterpolation?: string; + centerlineControls?: readonly PaddockTrackPoint[]; + drsZones?: readonly PaddockDrsZone[] | null; + pitLane?: { enabled?: boolean } | null; + generationOptions?: PaddockResolvedProceduralTrackOptions; + [key: string]: unknown; +} + export type PaddockStabilityState = 'stable' | 'understeer' | 'oversteer' | 'spin-risk' | 'destroyed'; export type PaddockPitIntent = 0 | 1 | 2; export type PaddockScenarioPreset = 'cornering' | 'off-track-recovery' | 'overtaking-pack' | 'pit-entry'; @@ -674,8 +737,8 @@ export interface PaddockDriverControllerContext { controlledDrivers: string[]; actionSpec: PaddockActionSpec; observationSpec: PaddockObservationSpec; - result: PaddockEnvironmentResult | unknown; - previousResult: PaddockEnvironmentResult | unknown | null; + result: PaddockEnvironmentResult; + previousResult: PaddockEnvironmentResult | null; observation: Record; orderedObservations: Array<{ driverId: string; @@ -685,7 +748,7 @@ export interface PaddockDriverControllerContext { }>; metrics: Record; events: RaceEvent[]; - info: PaddockEnvironmentResult['info'] | unknown | null; + info: PaddockEnvironmentResult['info'] | null; previousActions: PaddockActionMap; orderedPreviousActions: Array; actions: PaddockActionMap | null; @@ -721,14 +784,14 @@ export interface PaddockDriverController { } export interface PaddockControllerRuntime { - reset(options?: unknown): PaddockEnvironmentResult | unknown; - step(actions: PaddockActionMap): PaddockEnvironmentResult | unknown; + reset(options?: unknown): PaddockEnvironmentResult; + step(actions: PaddockActionMap): PaddockEnvironmentResult; resetDrivers?( placements: Record, resultOptions?: PaddockEnvironmentResultOptions - ): PaddockEnvironmentResult | unknown; + ): PaddockEnvironmentResult; getObservation(): Record; - getState?(options?: { output?: 'full' | 'minimal' | 'none' }): PaddockEnvironmentResult['state'] | unknown; + getState?(options?: { output?: 'full' | 'minimal' | 'none' }): PaddockEnvironmentResult['state']; getActionSpec(): PaddockActionSpec; getObservationSpec(): PaddockObservationSpec; destroy?(): void; @@ -743,7 +806,7 @@ export interface PaddockDriverControllerLoopOptions { } export interface PaddockDriverControllerLoop { - readonly result: PaddockEnvironmentResult | unknown | null; + readonly result: PaddockEnvironmentResult | null; readonly actionSpec: PaddockActionSpec | null; readonly observationSpec: PaddockObservationSpec | null; readonly stats: { @@ -756,13 +819,13 @@ export interface PaddockDriverControllerLoop { running: boolean; lastError: unknown | null; }; - reset(options?: unknown): Promise; + reset(options?: unknown): Promise; resetDrivers( placements: Record, resultOptions?: PaddockEnvironmentResultOptions - ): Promise; - step(): Promise; - stepFrame(): Promise; + ): Promise; + step(): Promise; + stepFrame(): Promise; start(): void; stop(): void; } diff --git a/src/index.d.ts b/src/index.d.ts index 56d6df6..5aba010 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -2,6 +2,7 @@ import type { PaddockActionSpec, PaddockDriverControllerLoop, PaddockDriverControllerLoopOptions, + PaddockEnvironmentResult, PaddockEnvironmentOptions, PaddockObservationSpec, PaddockParticipantInteraction as EnvPaddockParticipantInteraction, @@ -20,6 +21,8 @@ export type { PaddockDriverControllerContext, PaddockDriverControllerLoop, PaddockDriverControllerLoopOptions, + PaddockEnvironmentResult, + PaddockEnvironmentSnapshotResult, PaddockObservationSpec, } from './environment/index.js'; @@ -71,6 +74,69 @@ export interface PaddockProceduralTrackOptions { }; } +export interface PaddockTrackPoint { + x: number; + y: number; +} + +export interface PaddockDrsZone { + id: string; + startRatio: number; + endRatio: number; +} + +export interface PaddockResolvedProceduralTrackOptions { + profile: PaddockProceduralTrackProfile; + length: { + min: number; + max: number; + }; + startStraight: { + grid: number; + exit: number; + blend: number; + lockExtra: number; + }; + pitLane: { + enabled: boolean; + }; + shape: { + scale: number; + cornerDensity: number; + variation: number; + }; + validation: { + minClearanceMultiplier: number; + minShapeVariation: number; + minNonAdjacentArcDistance: number; + maxLocalTurnRadians: number; + maxSampleHeadingDeltaRadians: number; + }; + attempts: { + primary: number; + fallback: number; + }; + cacheKey: string; + [key: string]: unknown; +} + +export interface PaddockProceduralTrack { + name: string; + width: number; + kerbWidth: number; + gravelWidth: number; + runoffWidth: number; + barrierWidth: number; + sampleCount: number; + seed?: number; + curveInterpolation?: string; + centerlineControls?: readonly PaddockTrackPoint[]; + drsZones?: readonly PaddockDrsZone[] | null; + pitLane?: { enabled?: boolean } | null; + generationOptions?: PaddockResolvedProceduralTrackOptions; + [key: string]: unknown; +} + export type PaddockStabilityState = 'stable' | 'understeer' | 'oversteer' | 'spin-risk' | 'destroyed'; export type PaddockPitIntent = 0 | 1 | 2; export type PaddockPitIntentRequest = PaddockPitIntent | { @@ -959,14 +1025,14 @@ export interface PaddockEnvironmentResultOptions { } export interface F1SimulatorExpertApi { - reset(options?: unknown): unknown; - step(actions: Record): unknown; + reset(options?: unknown): PaddockEnvironmentResult; + step(actions: Record): PaddockEnvironmentResult; resetDrivers?( placements: Record, resultOptions?: PaddockEnvironmentResultOptions - ): unknown; - getObservation(): unknown; - getState(): unknown; + ): PaddockEnvironmentResult; + getObservation(): PaddockEnvironmentResult['observation']; + getState(): PaddockEnvironmentResult['state']; getActionSpec(): PaddockActionSpec; getObservationSpec(): PaddockObservationSpec; attachExternalRenderer(source: PaddockExternalRendererSource): void; @@ -1133,7 +1199,7 @@ export function simSpeedToMetersPerSecond(simSpeed: number): number; export function createPaddockSimulator(options: F1SimulatorOptions): PaddockSimulatorController; export function mountF1Simulator(root: Element, options: F1SimulatorOptions): Promise; -export function createProceduralTrack(seed?: number | string, options?: PaddockProceduralTrackOptions): unknown; +export function createProceduralTrack(seed?: number | string, options?: PaddockProceduralTrackOptions): PaddockProceduralTrack; export function createPaddockDriverControllerLoop(options: PaddockDriverControllerLoopOptions): PaddockDriverControllerLoop; export function mountRaceControls(root: T, simulator: PaddockSimulatorController): T; diff --git a/src/simulation/collisionGeometry.js b/src/simulation/collisionGeometry.js index 5b3e159..81f994d 100644 --- a/src/simulation/collisionGeometry.js +++ b/src/simulation/collisionGeometry.js @@ -1,7 +1,4 @@ -import { - getVehicleGeometryState, - vehicleAxes, -} from './vehicle/vehicleGeometry.js'; +import { getVehicleGeometryState } from './vehicle/vehicleGeometry.js'; import { normalizeAngle } from './simMath.js'; const DEFAULT_SWEEP_STEPS = 16; @@ -340,17 +337,18 @@ function writeInterpolatedBodyShape(target, geometryState, amount) { const x = pose.previousX + (pose.x - pose.previousX) * amount; const y = pose.previousY + (pose.y - pose.previousY) * amount; const heading = normalizeAngle(pose.previousHeading + headingDelta * amount); - const axes = vehicleAxes(heading); + const cos = Math.cos(heading); + const sin = Math.sin(heading); const halfLength = target.halfLength; const halfWidth = target.halfWidth; target.center.x = x; target.center.y = y; target.heading = heading; - target.forward.x = axes.forward.x; - target.forward.y = axes.forward.y; - target.right.x = axes.right.x; - target.right.y = axes.right.y; + target.forward.x = cos; + target.forward.y = sin; + target.right.x = -sin; + target.right.y = cos; writeOffsetCorner(target.corners[0], target.center, target.forward, target.right, halfLength, halfWidth); writeOffsetCorner(target.corners[1], target.center, target.forward, target.right, halfLength, -halfWidth); diff --git a/src/simulation/driver/driverController.js b/src/simulation/driver/driverController.js index 796aff3..11acc0c 100644 --- a/src/simulation/driver/driverController.js +++ b/src/simulation/driver/driverController.js @@ -4,7 +4,7 @@ import { decideRacingControls } from './racingControls.js'; import { decideRejoinControls } from './rejoinControls.js'; import { shouldContinueRejoinRecovery } from './edgeRecovery.js'; import { decideSafetyCarControls } from './safetyCarControls.js'; -import { VEHICLE_LIMITS } from '../vehicle/vehiclePhysics.js'; +import { VEHICLE_LIMITS, isSimulatorPhysicsMode } from '../vehicle/vehiclePhysics.js'; export function decideDriverControls({ car, orderIndex, race }) { if (car.manualControls) return car.manualControls; @@ -37,7 +37,7 @@ export function decideDriverControls({ car, orderIndex, race }) { } function shouldStabilizeSimulatorCar(car, race) { - if (race.physicsMode !== 'advanced') return false; + if (!isSimulatorPhysicsMode(race.physicsMode)) return false; const gripUsage = car.gripUsage ?? 0; const slipAngle = Math.abs(car.slipAngleRadians ?? 0); const edgeDistance = race.track.width / 2 - VEHICLE_LIMITS.carWidth * 2.25; diff --git a/src/simulation/driver/edgeRecovery.js b/src/simulation/driver/edgeRecovery.js index bf2fdbb..f9bbb5f 100644 --- a/src/simulation/driver/edgeRecovery.js +++ b/src/simulation/driver/edgeRecovery.js @@ -1,11 +1,11 @@ import { clamp, normalizeAngle } from '../simMath.js'; import { metersToSimUnits } from '../units.js'; import { pointAt } from '../track/trackModel.js'; -import { VEHICLE_LIMITS } from '../vehicle/vehiclePhysics.js'; +import { VEHICLE_LIMITS, isSimulatorPhysicsMode } from '../vehicle/vehiclePhysics.js'; import { REJOIN_LOOKAHEAD_BASE, REJOIN_LOOKAHEAD_MAX } from './driverControlConstants.js'; export function calculateTrackEdgeGuard(car, race) { - const simulatorMode = race.physicsMode === 'advanced'; + const simulatorMode = isSimulatorPhysicsMode(race.physicsMode); const trackLimit = race.track.width / 2; const halfCarWidth = VEHICLE_LIMITS.carWidth / 2; const wholeCarOutsideLimit = trackLimit + halfCarWidth; diff --git a/src/simulation/driver/racingControls.js b/src/simulation/driver/racingControls.js index f63133d..0acf7b5 100644 --- a/src/simulation/driver/racingControls.js +++ b/src/simulation/driver/racingControls.js @@ -1,7 +1,7 @@ import { clamp, normalizeAngle } from '../simMath.js'; import { kphToSimSpeed, metersToSimUnits, simUnitsToMeters } from '../units.js'; -import { offsetTrackPoint, pointAt } from '../track/trackModel.js'; -import { VEHICLE_LIMITS } from '../vehicle/vehiclePhysics.js'; +import { pointAtInto, sampleHeadingAt, sampleHeadingCurvatureAtInto } from '../track/trackModel.js'; +import { VEHICLE_LIMITS, isSimulatorPhysicsMode } from '../vehicle/vehiclePhysics.js'; import { BRAKING_LOOKAHEAD_MAX_DISTANCE, CURVATURE_LOOKAHEAD_SAMPLES, EDGE_RECOVERY_MIN_LOOKAHEAD, LOOKAHEAD_BASE_DISTANCE, LOOKAHEAD_MAX_DISTANCE, OVERTAKE_LATERAL_MIN, PREVIEW_CURVATURE_CAP, TRAFFIC_GAP_AHEAD, TRAFFIC_SIDE_GAP } from './driverControlConstants.js'; import { createDriverInput } from './driverInput.js'; import { angleToPoint } from './driverMath.js'; @@ -10,15 +10,14 @@ import { calculateActualOverlapPenalty, calculatePlannedTrafficPenalty, planRaci import { analyzeTrackEdgeMotion } from './recoveryDynamics.js'; export function decideRacingControls(car, orderIndex, race) { - if (race.physicsMode === 'advanced') { + if (isSimulatorPhysicsMode(race.physicsMode)) { return decideSimulatorRacingControls(car, orderIndex, race); } return decideArcadeRacingControls(car, orderIndex, race); } -export function decideArcadeRacingControls(car, orderIndex, race) { - return decideRacingControlsForMode(car, orderIndex, race, { - simulatorMode: false, +const ARCADE_CONTROL_PROFILE = { + simulatorMode: false, baseLookaheadSpeedFactor: (aggression) => 1.62 - aggression * 0.12, previewLookaheadSpeedFactor: 3.15, edgeLookaheadPenaltyMeters: 18, @@ -73,12 +72,14 @@ export function decideArcadeRacingControls(car, orderIndex, race) { recoveryHeadingThrottleStart: 0.38, throttleResponseKph: 16, throttleScale: () => 1, - }); +}; + +export function decideArcadeRacingControls(car, orderIndex, race) { + return decideRacingControlsForMode(car, orderIndex, race, ARCADE_CONTROL_PROFILE); } -export function decideSimulatorRacingControls(car, orderIndex, race) { - return decideRacingControlsForMode(car, orderIndex, race, { - simulatorMode: true, +const SIMULATOR_CONTROL_PROFILE = { + simulatorMode: true, baseLookaheadSpeedFactor: (aggression) => 2.45 - aggression * 0.06, previewLookaheadSpeedFactor: 6.15, edgeLookaheadPenaltyMeters: 34, @@ -141,7 +142,10 @@ export function decideSimulatorRacingControls(car, orderIndex, race) { 0, 1, ), - }); +}; + +export function decideSimulatorRacingControls(car, orderIndex, race) { + return decideRacingControlsForMode(car, orderIndex, race, SIMULATOR_CONTROL_PROFILE); } function decideRacingControlsForMode(car, orderIndex, race, profile) { @@ -170,7 +174,7 @@ function decideRacingControlsForMode(car, orderIndex, race, profile) { EDGE_RECOVERY_MIN_LOOKAHEAD, LOOKAHEAD_MAX_DISTANCE, ); - const targetBase = pointAt(race.track, car.progress + lookahead); + const targetBase = pointAtInto(race.track, car.progress + lookahead, TARGET_BASE_SCRATCH); const curvature = Math.max( car.trackState.curvature, targetBase.curvature, @@ -189,8 +193,9 @@ function decideRacingControlsForMode(car, orderIndex, race, profile) { -edgeGuard.recoveryOffset, edgeGuard.recoveryOffset, ); - const target = offsetTrackPoint(targetBase, targetOffset); - const angleError = angleToPoint(car, target); + TARGET_POINT_SCRATCH.x = targetBase.x + targetBase.normalX * targetOffset; + TARGET_POINT_SCRATCH.y = targetBase.y + targetBase.normalY * targetOffset; + const angleError = angleToPoint(car, TARGET_POINT_SCRATCH); const headingError = normalizeAngle(targetBase.heading - car.heading); const lateralError = car.trackState?.signedOffset ?? 0; const outwardDriftAngle = simulatorMode && @@ -363,15 +368,20 @@ function decideRacingControlsForMode(car, orderIndex, race, profile) { .controls(); } +const LOOKAHEAD_SAMPLE_SCRATCH = { heading: 0, curvature: 0 }; +const TARGET_BASE_SCRATCH = { x: 0, y: 0, heading: 0, normalX: 0, normalY: 0, curvature: 0, distance: 0 }; +const TARGET_POINT_SCRATCH = { x: 0, y: 0 }; + export function maxLookaheadCurvature(track, progress, lookahead) { let maximum = 0; - let previous = pointAt(track, progress); + const sample = LOOKAHEAD_SAMPLE_SCRATCH; + let previousHeading = sampleHeadingCurvatureAtInto(track, progress, sample).heading; + const segmentDistance = Math.max(1, lookahead / CURVATURE_LOOKAHEAD_SAMPLES); for (let index = 1; index <= CURVATURE_LOOKAHEAD_SAMPLES; index += 1) { - const sample = pointAt(track, progress + lookahead * (index / CURVATURE_LOOKAHEAD_SAMPLES)); - const segmentDistance = Math.max(1, lookahead / CURVATURE_LOOKAHEAD_SAMPLES); - const segmentCurvature = Math.abs(normalizeAngle(sample.heading - previous.heading)) / segmentDistance; + sampleHeadingCurvatureAtInto(track, progress + lookahead * (index / CURVATURE_LOOKAHEAD_SAMPLES), sample); + const segmentCurvature = Math.abs(normalizeAngle(sample.heading - previousHeading)) / segmentDistance; maximum = Math.max(maximum, Math.abs(sample.curvature ?? 0), Math.min(segmentCurvature, PREVIEW_CURVATURE_CAP)); - previous = sample; + previousHeading = sample.heading; } return maximum; } @@ -380,16 +390,16 @@ export function calculateRacingLineOffset(car, race, lookahead, curvature, edgeG const cornerStrength = clamp((curvature - 0.00012) / 0.00095, 0, 1); if (cornerStrength <= 0) return 0; - const entry = pointAt(race.track, car.progress - lookahead * 0.35); - const apex = pointAt(race.track, car.progress + lookahead * 0.55); - const exit = pointAt(race.track, car.progress + lookahead * 1.25); - const signedEntry = normalizeAngle(apex.heading - entry.heading); - const signedExit = normalizeAngle(exit.heading - apex.heading); + const entryHeading = sampleHeadingAt(race.track, car.progress - lookahead * 0.35); + const apexHeading = sampleHeadingAt(race.track, car.progress + lookahead * 0.55); + const exitHeading = sampleHeadingAt(race.track, car.progress + lookahead * 1.25); + const signedEntry = normalizeAngle(apexHeading - entryHeading); + const signedExit = normalizeAngle(exitHeading - apexHeading); const turnDirection = Math.sign(Math.abs(signedEntry) > Math.abs(signedExit) ? signedEntry : signedExit); if (turnDirection === 0) return 0; const aggression = car.aggression ?? car.personality?.baseAggression ?? 0.5; - const simulatorMode = race.physicsMode === 'advanced'; + const simulatorMode = isSimulatorPhysicsMode(race.physicsMode); const safeEdge = race.track.width / 2 - VEHICLE_LIMITS.carWidth * (simulatorMode ? 2.05 - aggression * 0.08 : 1.15 - aggression * 0.12); const apexOffset = turnDirection * safeEdge * diff --git a/src/simulation/driver/racingLinePlan.js b/src/simulation/driver/racingLinePlan.js index 197540a..01d910e 100644 --- a/src/simulation/driver/racingLinePlan.js +++ b/src/simulation/driver/racingLinePlan.js @@ -18,15 +18,16 @@ export function planRacingLine(car, orderIndex, race) { let bestOffset = currentOffset; let bestScore = -Infinity; - LANE_OFFSETS.forEach((rawOffset) => { - const offset = clamp(rawOffset, -trackLimit, trackLimit); + for (let laneIndex = 0; laneIndex < LANE_OFFSETS.length; laneIndex += 1) { + const offset = clamp(LANE_OFFSETS[laneIndex], -trackLimit, trackLimit); const edgeClearance = trackLimit - Math.abs(offset); let score = 80; score -= Math.abs(offset - preferred) * 0.18; score -= Math.abs(offset - currentOffset) * (0.09 - aggression * 0.025); score -= Math.max(0, LANE_EDGE_CLEARANCE_TARGET - edgeClearance) * (0.92 - aggression * 0.42); - traffic.forEach((entry) => { + for (let trafficIndex = 0; trafficIndex < traffic.length; trafficIndex += 1) { + const entry = traffic[trafficIndex]; const lateral = Math.abs(entry.signedOffset - offset); if (entry.gap > 0 && entry.gap < TRAFFIC_GAP_AHEAD) { const overlapRisk = clamp(TRAFFIC_SIDE_OVERLAP - lateral, 0, TRAFFIC_SIDE_OVERLAP); @@ -38,7 +39,7 @@ export function planRacingLine(car, orderIndex, race) { const sideOverlapRisk = clamp(TRAFFIC_SIDE_OVERLAP - lateral, 0, TRAFFIC_SIDE_OVERLAP); score -= sideOverlapRisk * (TRAFFIC_SIDE_OVERLAP + entry.gap) * 0.052 * (1 - riskTolerance * 0.22); } - }); + } if (ahead && car.gapAhead < TRAFFIC_GAP_AHEAD) { const passSide = attackPlan?.targetOffset ?? clamp( @@ -73,7 +74,7 @@ export function planRacingLine(car, orderIndex, race) { bestScore = score; bestOffset = offset; } - }); + } const laneChangeRate = metersToSimUnits(0.95 + car.racecraft * 0.32 + aggression * 0.78); car.desiredOffset = currentOffset + clamp(bestOffset - currentOffset, -laneChangeRate, laneChangeRate); diff --git a/src/simulation/driver/rejoinControls.js b/src/simulation/driver/rejoinControls.js index 63ce6a6..60fbbbe 100644 --- a/src/simulation/driver/rejoinControls.js +++ b/src/simulation/driver/rejoinControls.js @@ -4,11 +4,11 @@ import { offsetTrackPoint, pointAt } from '../track/trackModel.js'; import { REJOIN_LOOKAHEAD_BASE, REJOIN_LOOKAHEAD_MAX } from './driverControlConstants.js'; import { angleToPoint } from './driverMath.js'; import { createDriverInput } from './driverInput.js'; -import { VEHICLE_LIMITS } from '../vehicle/vehiclePhysics.js'; +import { VEHICLE_LIMITS, isSimulatorPhysicsMode } from '../vehicle/vehiclePhysics.js'; import { analyzeTrackEdgeMotion } from './recoveryDynamics.js'; export function decideRejoinControls(car, race) { - if (race.physicsMode === 'advanced') { + if (isSimulatorPhysicsMode(race.physicsMode)) { return decideSimulatorRejoinControls(car, race); } return decideArcadeRejoinControls(car, race); @@ -103,7 +103,7 @@ export function decideSimulatorRejoinControls(car, race) { } function decideRejoinControlsForMode(car, race, profile) { - const simulatorMode = race.physicsMode === 'advanced'; + const simulatorMode = isSimulatorPhysicsMode(race.physicsMode); const lookahead = clamp(car.speed * (profile.simulatorMode ? 0.58 : 0.72) + REJOIN_LOOKAHEAD_BASE, REJOIN_LOOKAHEAD_BASE, REJOIN_LOOKAHEAD_MAX); const edgeMotion = analyzeTrackEdgeMotion(car, race); const lowSpeedOffTrack = !car.trackState.onTrack && car.speed < kphToSimSpeed(24); diff --git a/src/simulation/driver/trafficScan.js b/src/simulation/driver/trafficScan.js index 80e5791..f1c7270 100644 --- a/src/simulation/driver/trafficScan.js +++ b/src/simulation/driver/trafficScan.js @@ -2,25 +2,43 @@ import { metersToSimUnits } from '../units.js'; import { DEFEND_REAR_GAP, TRAFFIC_GAP_AHEAD, TRAFFIC_SIDE_GAP, TRAFFIC_REAR_WINDOW } from './driverControlConstants.js'; import { VEHICLE_LIMITS } from '../vehicle/vehiclePhysics.js'; +const TRAFFIC_REAR_SCAN_WINDOW = metersToSimUnits(39); +const TRAFFIC_FORWARD_SCAN_WINDOW = metersToSimUnits(134); +const TRAFFIC_BESIDE_WINDOW = metersToSimUnits(28); + +// Entries are reused across calls: drivers consume the scan synchronously +// within a single control decision, so a module-level pool avoids re-allocating +// the candidate list for every car on every step. +const TRAFFIC_SCRATCH = []; +const TRAFFIC_ENTRY_POOL = []; + export function scanNearbyTraffic(car, race) { - return race.cars - .filter((other) => other !== car) - .map((other) => ({ - car: other, - gap: other.raceDistance - car.raceDistance, - signedOffset: other.trackState?.signedOffset ?? 0, - speed: other.speed, - })) - .filter((entry) => entry.gap > -metersToSimUnits(39) && entry.gap < metersToSimUnits(134)); + const traffic = TRAFFIC_SCRATCH; + traffic.length = 0; + const cars = race.cars; + for (let index = 0; index < cars.length; index += 1) { + const other = cars[index]; + if (other === car) continue; + const gap = other.raceDistance - car.raceDistance; + if (gap <= -TRAFFIC_REAR_SCAN_WINDOW || gap >= TRAFFIC_FORWARD_SCAN_WINDOW) continue; + const entry = TRAFFIC_ENTRY_POOL[traffic.length] ??= { car: null, gap: 0, signedOffset: 0, speed: 0 }; + entry.car = other; + entry.gap = gap; + entry.signedOffset = other.trackState?.signedOffset ?? 0; + entry.speed = other.speed; + traffic.push(entry); + } + return traffic; } export function findDefensiveThreat(traffic) { let closest = null; - traffic.forEach((entry) => { - if (entry.gap >= -VEHICLE_LIMITS.carLength * 1.1 || entry.gap < -DEFEND_REAR_GAP) return; + for (let index = 0; index < traffic.length; index += 1) { + const entry = traffic[index]; + if (entry.gap >= -VEHICLE_LIMITS.carLength * 1.1 || entry.gap < -DEFEND_REAR_GAP) continue; if (!closest || entry.gap > closest.gap) closest = entry; - }); + } return closest; } @@ -28,24 +46,32 @@ export function findDefensiveThreat(traffic) { export function findLaneTrafficAhead(traffic, offset, maxDistance) { let closest = null; - traffic.forEach((entry) => { - if (entry.gap <= 0 || entry.gap > maxDistance) return; - if (Math.abs(entry.signedOffset - offset) > TRAFFIC_SIDE_GAP) return; + for (let index = 0; index < traffic.length; index += 1) { + const entry = traffic[index]; + if (entry.gap <= 0 || entry.gap > maxDistance) continue; + if (Math.abs(entry.signedOffset - offset) > TRAFFIC_SIDE_GAP) continue; if (!closest || entry.gap < closest.gap) closest = entry; - }); + } return closest; } export function findLaneTrafficBeside(traffic, offset) { let closest = null; + let closestLateral = 0; + let closestRisk = -Infinity; - traffic.forEach((entry) => { + for (let index = 0; index < traffic.length; index += 1) { + const entry = traffic[index]; const lateral = Math.abs(entry.signedOffset - offset); - if (Math.abs(entry.gap) > metersToSimUnits(28) || lateral > TRAFFIC_SIDE_GAP) return; - const risk = (metersToSimUnits(28) - Math.abs(entry.gap)) + (TRAFFIC_SIDE_GAP - lateral); - if (!closest || risk > closest.risk) closest = { ...entry, lateral, risk }; - }); + if (Math.abs(entry.gap) > TRAFFIC_BESIDE_WINDOW || lateral > TRAFFIC_SIDE_GAP) continue; + const risk = (TRAFFIC_BESIDE_WINDOW - Math.abs(entry.gap)) + (TRAFFIC_SIDE_GAP - lateral); + if (!closest || risk > closestRisk) { + closest = entry; + closestLateral = lateral; + closestRisk = risk; + } + } - return closest; + return closest ? { ...closest, lateral: closestLateral, risk: closestRisk } : null; } diff --git a/src/simulation/participants/participantInteractions.js b/src/simulation/participants/participantInteractions.js index 6ee8b54..0b14d8a 100644 --- a/src/simulation/participants/participantInteractions.js +++ b/src/simulation/participants/participantInteractions.js @@ -41,14 +41,6 @@ export const PARTICIPANT_INTERACTION_PROFILES = Object.freeze({ }), }); -const INTERACTION_FLAGS = Object.freeze([ - 'collidable', - 'detectableByRays', - 'detectableAsNearby', - 'blocksPitLane', - 'affectsRaceOrder', -]); - export function normalizeParticipantInteractions(options = {}) { const defaultProfile = resolveProfileName(options.defaultProfile); const defaultInteraction = { ...PARTICIPANT_INTERACTION_PROFILES[defaultProfile] }; @@ -73,11 +65,15 @@ export function attachParticipantInteractions(cars = [], options = {}) { export function resolveInteraction(override = {}, fallbackProfile = 'normal') { const profile = resolveProfileName(override?.profile ?? fallbackProfile); - const resolved = { ...PARTICIPANT_INTERACTION_PROFILES[profile] }; - INTERACTION_FLAGS.forEach((flag) => { - if (override?.[flag] != null) resolved[flag] = Boolean(override[flag]); - }); - return resolved; + const base = PARTICIPANT_INTERACTION_PROFILES[profile]; + return { + profile, + collidable: override?.collidable != null ? Boolean(override.collidable) : base.collidable, + detectableByRays: override?.detectableByRays != null ? Boolean(override.detectableByRays) : base.detectableByRays, + detectableAsNearby: override?.detectableAsNearby != null ? Boolean(override.detectableAsNearby) : base.detectableAsNearby, + blocksPitLane: override?.blocksPitLane != null ? Boolean(override.blocksPitLane) : base.blocksPitLane, + affectsRaceOrder: override?.affectsRaceOrder != null ? Boolean(override.affectsRaceOrder) : base.affectsRaceOrder, + }; } export function canCollide(first, second) { @@ -110,8 +106,21 @@ export function affectsRaceOrder(car) { } export function serializeParticipantInteraction(interaction) { - const normalized = resolveInteraction(interaction ?? {}, interaction?.profile ?? 'normal'); - return { ...normalized }; + return resolveInteraction(interaction ?? {}, interaction?.profile ?? 'normal'); +} + +const SERIALIZED_INTERACTION_SOURCE = Symbol('serializedInteractionSource'); +const SERIALIZED_INTERACTION_VALUE = Symbol('serializedInteractionValue'); + +// Render snapshots are pooled and rebuilt every frame; the interaction config +// only changes when a new object is attached, so cache the serialized form per +// car keyed on the interaction reference. +export function serializeParticipantInteractionCached(car) { + if (car[SERIALIZED_INTERACTION_SOURCE] !== car.interaction || !car[SERIALIZED_INTERACTION_VALUE]) { + car[SERIALIZED_INTERACTION_SOURCE] = car.interaction; + car[SERIALIZED_INTERACTION_VALUE] = serializeParticipantInteraction(car.interaction); + } + return car[SERIALIZED_INTERACTION_VALUE]; } function resolveProfileName(profile) { diff --git a/src/simulation/race/raceStep.js b/src/simulation/race/raceStep.js index 639c0e2..7f5b519 100644 --- a/src/simulation/race/raceStep.js +++ b/src/simulation/race/raceStep.js @@ -1,7 +1,7 @@ import { decideDriverControls } from '../driverController.js'; import { clamp } from '../simMath.js'; import { updateReplayGhosts } from '../replay/replayGhosts.js'; -import { integrateVehiclePhysics } from '../vehicle/vehiclePhysics.js'; +import { integrateVehiclePhysics, isSimulatorPhysicsMode } from '../vehicle/vehiclePhysics.js'; import { applyWheelSurfaceState } from '../vehicle/wheelSurface.js'; import { applyRedFlagHoldForSimulation } from './redFlag.js'; import { freezeRetiredCar, updateStalledDnfForSimulation } from './stalledDnf.js'; @@ -38,19 +38,28 @@ export function runRaceStep(simulation, dt) { const orderedCars = simulation.orderedCars(); const raceContext = simulation.driverRaceContext(orderedCars); - const orderedIndexById = new Map(orderedCars.map((car, index) => [car.id, index])); - const driveCars = orderedCars.length === simulation.cars.length - ? orderedCars - : [ - ...orderedCars, - ...simulation.cars.filter((car) => !orderedIndexById.has(car.id)), - ]; + for (let index = 0; index < simulation.cars.length; index += 1) { + simulation.cars[index]._driveOrderIndex = -1; + } + for (let index = 0; index < orderedCars.length; index += 1) { + orderedCars[index]._driveOrderIndex = index; + } + let driveCars = orderedCars; + if (orderedCars.length !== simulation.cars.length) { + driveCars = simulation._driveCarsScratch ??= []; + driveCars.length = 0; + driveCars.push(...orderedCars); + for (let index = 0; index < simulation.cars.length; index += 1) { + const car = simulation.cars[index]; + if (car._driveOrderIndex === -1) driveCars.push(car); + } + } driveCars.forEach((car) => { if (car.destroyed || car.outOfRace) { freezeRetiredCar(car, { physicsMode: simulation.physicsMode }); return; } - const orderIndex = orderedIndexById.get(car.id); + const orderIndex = car._driveOrderIndex >= 0 ? car._driveOrderIndex : undefined; car.previousX = car.x; car.previousY = car.y; car.previousHeading = car.heading; @@ -66,7 +75,7 @@ export function runRaceStep(simulation, dt) { throttle: controls.throttle ?? 0, brake: controls.brake ?? 0, }; - if (simulation.physicsMode === 'advanced') { + if (isSimulatorPhysicsMode(simulation.physicsMode)) { measureRuntimePhase(simulation, 'prePhysicsWheelSurface', () => { applyWheelSurfaceState(car, simulation.track); }); diff --git a/src/simulation/race/safetyCar.js b/src/simulation/race/safetyCar.js index 8ae1d09..5c3965e 100644 --- a/src/simulation/race/safetyCar.js +++ b/src/simulation/race/safetyCar.js @@ -1,6 +1,7 @@ import { pointAt } from '../track/trackModel.js'; import { kphToSimSpeed } from '../units.js'; import { freezeVehicleMotion, syncVehicleVelocityToHeading } from '../vehicle/vehicleKinematics.js'; +import { isSimulatorPhysicsMode } from '../vehicle/vehiclePhysics.js'; export function setSafetyCarState(sim, deployed) { const next = Boolean(deployed); @@ -82,7 +83,7 @@ export function setRedFlagState(sim, deployed) { }); } else if (!car.finished) { car.speed = Math.max(car.speed, kphToSimSpeed(60)); - if (sim.physicsMode === 'advanced') syncVehicleVelocityToHeading(car); + if (isSimulatorPhysicsMode(sim.physicsMode)) syncVehicleVelocityToHeading(car); car.brake = 0; car.throttle = Math.max(car.throttle ?? 0, 0.35); } diff --git a/src/simulation/rules/pitLaneSpeedingSteward.js b/src/simulation/rules/pitLaneSpeedingSteward.js index 3c8a8ab..a9817ba 100644 --- a/src/simulation/rules/pitLaneSpeedingSteward.js +++ b/src/simulation/rules/pitLaneSpeedingSteward.js @@ -20,7 +20,7 @@ export function calculatePitLaneSpeedingReview({ car, rule, stewardState }) { if (!isViolation) { return { - nextState: { ...current, active: false }, + nextState: current.active === false ? current : { ...current, active: false }, event: null, penalty: null, }; diff --git a/src/simulation/rules/rulesReview.js b/src/simulation/rules/rulesReview.js index cd4039b..8babf53 100644 --- a/src/simulation/rules/rulesReview.js +++ b/src/simulation/rules/rulesReview.js @@ -129,7 +129,9 @@ export function reviewTrackLimitsForSimulation(sim) { sim.cars.forEach((car) => { if (isLegallyInsidePitLaneForTrackLimits(car)) { const current = sim.stewardState.trackLimits[car.id]; - sim.stewardState.trackLimits[car.id] = { ...(current ?? { violations: 0 }), active: false }; + if (!current || current.active !== false) { + sim.stewardState.trackLimits[car.id] = { ...(current ?? { violations: 0 }), active: false }; + } return; } @@ -146,18 +148,26 @@ export function reviewTrackLimitsForSimulation(sim) { }); } +const PIT_SPEED_REVIEW_SCRATCH = { + car: { id: null, speedKph: 0, trackState: null, pitLanePart: null }, + rule: null, + stewardState: null, +}; + export function reviewPitLaneSpeedingForSimulation(sim) { const rule = getPenaltyRule(sim.rules, 'pitLaneSpeeding'); sim.cars.forEach((car) => { const currentState = sim.stewardState.pitLaneSpeeding[car.id]; - const review = calculatePitLaneSpeedingReview({ - car: { - ...car, - speedKph: simSpeedToKph(car.speed), - }, - rule, - stewardState: currentState, - }); + // The steward only reads the speed and pit-lane location, so feed it a + // pooled view instead of spreading the whole car every step. + const reviewCar = PIT_SPEED_REVIEW_SCRATCH.car; + reviewCar.id = car.id; + reviewCar.speedKph = simSpeedToKph(car.speed); + reviewCar.trackState = car.trackState; + reviewCar.pitLanePart = car.pitLanePart; + PIT_SPEED_REVIEW_SCRATCH.rule = rule; + PIT_SPEED_REVIEW_SCRATCH.stewardState = currentState; + const review = calculatePitLaneSpeedingReview(PIT_SPEED_REVIEW_SCRATCH); sim.stewardState.pitLaneSpeeding[car.id] = review.nextState; if (review.event) sim.events.unshift({ ...review.event, at: sim.time }); if (review.penalty) sim.recordPenalty(review.penalty); diff --git a/src/simulation/rules/trackLimitsSteward.js b/src/simulation/rules/trackLimitsSteward.js index f353e23..db0b580 100644 --- a/src/simulation/rules/trackLimitsSteward.js +++ b/src/simulation/rules/trackLimitsSteward.js @@ -22,7 +22,7 @@ export function calculateTrackLimitReview({ car, rule, track, stewardState }) { const wheelStates = wheelSurfaceState.wheels; if (wheelStates.some((wheelState) => wheelState.inPitLane)) { return { - nextState: { ...current, active: false }, + nextState: current.active === false ? current : { ...current, active: false }, event: null, penalty: null, }; @@ -34,7 +34,7 @@ export function calculateTrackLimitReview({ car, rule, track, stewardState }) { if (!isViolation) { return { - nextState: { ...current, active: false }, + nextState: current.active === false ? current : { ...current, active: false }, event: null, penalty: null, }; diff --git a/src/simulation/timing/sectorPerformance.js b/src/simulation/timing/sectorPerformance.js index 457698d..2ca01c4 100644 --- a/src/simulation/timing/sectorPerformance.js +++ b/src/simulation/timing/sectorPerformance.js @@ -5,7 +5,7 @@ const OVERALL_BEST_1 = '_sectorPerformanceOverallBest1'; const OVERALL_BEST_2 = '_sectorPerformanceOverallBest2'; export function createEmptySectorTimes() { - return Array.from({ length: TELEMETRY_SECTOR_COUNT }, () => null); + return new Array(TELEMETRY_SECTOR_COUNT).fill(null); } export function createEmptySectorPerformance() { @@ -17,11 +17,19 @@ export function createEmptySectorPerformance() { } export function serializeSectorTimes(values) { - return createEmptySectorTimes().map((_, index) => finiteOrNull(values?.[index])); + const result = new Array(TELEMETRY_SECTOR_COUNT); + for (let index = 0; index < TELEMETRY_SECTOR_COUNT; index += 1) { + result[index] = finiteOrNull(values?.[index]); + } + return result; } export function serializeSectorPerformance(values) { - return createEmptySectorTimes().map((_, index) => values?.[index] ?? null); + const result = new Array(TELEMETRY_SECTOR_COUNT); + for (let index = 0; index < TELEMETRY_SECTOR_COUNT; index += 1) { + result[index] = values?.[index] ?? null; + } + return result; } export function updateSectorPerformance(cars, stats = null) { diff --git a/src/simulation/track/spatialQueries.js b/src/simulation/track/spatialQueries.js index 6dd7a05..8dea386 100644 --- a/src/simulation/track/spatialQueries.js +++ b/src/simulation/track/spatialQueries.js @@ -6,27 +6,59 @@ import { queryNearestTrackProjection, queryNearestTrackProjectionInto } from './ import { recordStat } from './trackQueryStats.js'; export function pointAt(track, distanceAlong) { + return pointAtInto(track, distanceAlong, {}); +} + +export function pointAtInto(track, distanceAlong, target) { const wrapped = wrapDistance(distanceAlong, track.length); - const low = sampleIndexAtDistance(track, wrapped); + const low = sampleIndexAtDistanceUnwrapped(track, wrapped); const next = track.samples[low] ?? track.samples[0]; const previous = track.samples[Math.max(0, low - 1)] ?? next; const span = Math.max(1, next.distance - previous.distance); const amount = clamp((wrapped - previous.distance) / span, 0, 1); - return { - x: previous.x + (next.x - previous.x) * amount, - y: previous.y + (next.y - previous.y) * amount, - heading: previous.heading + normalizeAngle(next.heading - previous.heading) * amount, - normalX: previous.normalX + (next.normalX - previous.normalX) * amount, - normalY: previous.normalY + (next.normalY - previous.normalY) * amount, - curvature: previous.curvature + (next.curvature - previous.curvature) * amount, - distance: wrapped, - }; + target.x = previous.x + (next.x - previous.x) * amount; + target.y = previous.y + (next.y - previous.y) * amount; + target.heading = previous.heading + normalizeAngle(next.heading - previous.heading) * amount; + target.normalX = previous.normalX + (next.normalX - previous.normalX) * amount; + target.normalY = previous.normalY + (next.normalY - previous.normalY) * amount; + target.curvature = previous.curvature + (next.curvature - previous.curvature) * amount; + target.distance = wrapped; + return target; } -export function sampleIndexAtDistance(track, distanceAlong) { +export function sampleHeadingCurvatureAtInto(track, distanceAlong, target) { const wrapped = wrapDistance(distanceAlong, track.length); + const low = sampleIndexAtDistanceUnwrapped(track, wrapped); + + const next = track.samples[low] ?? track.samples[0]; + const previous = track.samples[Math.max(0, low - 1)] ?? next; + const span = Math.max(1, next.distance - previous.distance); + const amount = clamp((wrapped - previous.distance) / span, 0, 1); + + target.heading = previous.heading + normalizeAngle(next.heading - previous.heading) * amount; + target.curvature = previous.curvature + (next.curvature - previous.curvature) * amount; + return target; +} + +export function sampleHeadingAt(track, distanceAlong) { + const wrapped = wrapDistance(distanceAlong, track.length); + const low = sampleIndexAtDistanceUnwrapped(track, wrapped); + + const next = track.samples[low] ?? track.samples[0]; + const previous = track.samples[Math.max(0, low - 1)] ?? next; + const span = Math.max(1, next.distance - previous.distance); + const amount = clamp((wrapped - previous.distance) / span, 0, 1); + + return previous.heading + normalizeAngle(next.heading - previous.heading) * amount; +} + +export function sampleIndexAtDistance(track, distanceAlong) { + return binarySampleIndexAtDistance(track, wrapDistance(distanceAlong, track.length)); +} + +function binarySampleIndexAtDistance(track, wrapped) { let low = 0; let high = track.samples.length - 1; @@ -39,6 +71,43 @@ export function sampleIndexAtDistance(track, distanceAlong) { return low; } +// Uniform-bin index over sample distances: table[bin] holds the smallest +// sample index whose distance reaches the bin start, so a lookup plus a short +// forward walk returns exactly what the binary search would, in O(1). Built +// eagerly when the track query index is attached; lookups on sample arrays +// without a prepared table fall back to the binary search. +const SAMPLE_INDEX_LUTS = new WeakMap(); + +export function prepareSampleIndexLut(track) { + const samples = track?.samples; + if (!Array.isArray(samples) || samples.length < 2 || !Number.isFinite(track.length) || track.length <= 0) return; + if (SAMPLE_INDEX_LUTS.has(samples)) return; + const lastIndex = samples.length - 1; + const bins = Math.max(1, lastIndex * 2); + const table = new Int32Array(bins); + const binSize = track.length / bins; + let index = 0; + for (let bin = 0; bin < bins; bin += 1) { + const start = bin * binSize; + while (index < lastIndex && samples[index].distance < start) index += 1; + table[bin] = index; + } + SAMPLE_INDEX_LUTS.set(samples, { bins, binSize, table }); +} + +function sampleIndexAtDistanceUnwrapped(track, wrapped) { + const samples = track.samples; + const lut = Number.isFinite(wrapped) ? SAMPLE_INDEX_LUTS.get(samples) : null; + if (!lut) return binarySampleIndexAtDistance(track, wrapped); + const lastIndex = samples.length - 1; + let bin = Math.floor(wrapped / lut.binSize); + if (bin < 0) bin = 0; + else if (bin >= lut.bins) bin = lut.bins - 1; + let index = lut.table[bin]; + while (index < lastIndex && samples[index].distance < wrapped) index += 1; + return index; +} + export function nearestSampleInRange(track, position, startIndex, endIndex) { const sampleCount = track.samples.length - 1; let best = null; diff --git a/src/simulation/track/trackModel.js b/src/simulation/track/trackModel.js index 7b1072a..a5b7d08 100644 --- a/src/simulation/track/trackModel.js +++ b/src/simulation/track/trackModel.js @@ -6,6 +6,7 @@ import { generateCenterlineControls, generateFallbackCenterlineControls, generat import { isValidProceduralTrackModel } from './trackValidation.js'; import { recalculateSampleGeometry } from './sampleGeometry.js'; import { rotateSamplesToStandingStart, straightenStandingStartSamples } from './startStraight.js'; +import { prepareSampleIndexLut } from './spatialQueries.js'; import { createTrackSectors } from './trackSectors.js'; import { deriveDrsZones, normalizeDrsZone } from './drsZones.js'; import { createPitLaneModel } from './pitLaneLayout.js'; @@ -15,7 +16,14 @@ import { attachTrackSnapshotJsonSerializer } from './trackSnapshotJson.js'; export { WORLD, TRACK } from './trackConstants.js'; export { isInDrsZone } from './drsZones.js'; -export { nearestTrackState, offsetTrackPoint, pointAt } from './spatialQueries.js'; +export { + nearestTrackState, + offsetTrackPoint, + pointAt, + pointAtInto, + sampleHeadingAt, + sampleHeadingCurvatureAtInto, +} from './spatialQueries.js'; const PROCEDURAL_TRACK_CACHE = new Map(); const TRACK_MODEL_CACHE = new WeakMap(); @@ -57,6 +65,7 @@ export function buildTrackModel(track = TRACK) { ? null : createPitLaneModel(model); attachTrackQueryIndex(model, createTrackQueryIndex(model)); + prepareSampleIndexLut(model); attachTrackSnapshotJsonSerializer(model); if (canReuseCachedModel) { TRACK_MODEL_CACHE.set(track, freezeTrackModel(model)); diff --git a/src/simulation/vehicle/contactResolution.js b/src/simulation/vehicle/contactResolution.js index b3976d3..30ac7d6 100644 --- a/src/simulation/vehicle/contactResolution.js +++ b/src/simulation/vehicle/contactResolution.js @@ -6,7 +6,7 @@ import { } from '../collisionGeometry.js'; import { canCollide, isCollidable } from '../participants/participantInteractions.js'; import { clamp, normalizeAngle } from '../simMath.js'; -import { VEHICLE_LIMITS } from './vehiclePhysics.js'; +import { VEHICLE_LIMITS, isSimulatorPhysicsMode } from './vehiclePhysics.js'; import { shiftPreviousRenderPose } from '../pit/pitRouting.js'; const MAX_COLLISION_CORRECTION = 4.5; @@ -114,8 +114,8 @@ export function resolveCollisionsForSimulation(sim) { } if (oneCarFixed) { - if (!firstPitControlled) dampPitContactVelocity(first, 0.985, sim.physicsMode === 'advanced'); - if (!secondPitControlled) dampPitContactVelocity(second, 0.985, sim.physicsMode === 'advanced'); + if (!firstPitControlled) dampPitContactVelocity(first, 0.985, isSimulatorPhysicsMode(sim.physicsMode)); + if (!secondPitControlled) dampPitContactVelocity(second, 0.985, isSimulatorPhysicsMode(sim.physicsMode)); } else { applyContactVelocityResponse(sim, first, second, collision.axis); } @@ -167,7 +167,7 @@ export function resolveCollisionsForSimulation(sim) { export function applyContactVelocityResponse(sim, first, second, axis, options = {}) { recordContactVelocityResponse(options.stats); if ( - sim.physicsMode === 'advanced' || + isSimulatorPhysicsMode(sim.physicsMode) || Number.isFinite(first.velocityX) || Number.isFinite(second.velocityX) ) { diff --git a/src/simulation/vehicle/vehicleGeometry.js b/src/simulation/vehicle/vehicleGeometry.js index 9d7525e..84d8e29 100644 --- a/src/simulation/vehicle/vehicleGeometry.js +++ b/src/simulation/vehicle/vehicleGeometry.js @@ -274,33 +274,22 @@ function sweptPoseSignature(pose) { ].join(':'); } -function geometryPose(car) { - const { x, y, heading } = currentPoseState(car); - return { - x, - y, - heading, - previousX: finiteOr(car.previousX, x), - previousY: finiteOr(car.previousY, y), - previousHeading: normalizeAngle(finiteOr(car.previousHeading, heading)), - }; -} - function currentGeometryStateMatches(car, state) { const pose = state?.pose; if (!pose) return false; - const currentPose = currentPoseState(car); return ( - pose.x === currentPose.x && - pose.y === currentPose.y && - pose.heading === currentPose.heading + pose.x === finiteOr(car.x, 0) && + pose.y === finiteOr(car.y, 0) && + pose.heading === normalizeAngle(finiteOr(car.heading, 0)) ); } function geometryStateMatches(car, state) { const pose = state?.pose; if (!pose) return false; - const { x, y, heading } = currentPoseState(car); + const x = finiteOr(car.x, 0); + const y = finiteOr(car.y, 0); + const heading = normalizeAngle(finiteOr(car.heading, 0)); return ( pose.x === x && pose.y === y && @@ -312,6 +301,10 @@ function geometryStateMatches(car, state) { } export function createVehicleShapeAabb(shape) { + return writeVehicleShapeAabb({}, shape); +} + +function writeVehicleShapeAabb(target, shape) { let minX = Infinity; let maxX = -Infinity; let minY = Infinity; @@ -323,12 +316,11 @@ export function createVehicleShapeAabb(shape) { if (corner.y < minY) minY = corner.y; if (corner.y > maxY) maxY = corner.y; } - return { - minX, - maxX, - minY, - maxY, - }; + target.minX = minX; + target.maxX = maxX; + target.minY = minY; + target.maxY = maxY; + return target; } export function mergeAabbs(aabbs) { @@ -346,32 +338,73 @@ export function mergeAabbs(aabbs) { return { minX, maxX, minY, maxY }; } -export function createVehicleGeometryState(car) { - const pose = geometryPose(car); - const current = writeVehicleGeometry(null, pose); - const previous = writeVehicleGeometry(null, { - x: pose.previousX, - y: pose.previousY, - heading: pose.previousHeading, - }); - const bodyAabb = createVehicleShapeAabb(current.body); - const previousBodyAabb = createVehicleShapeAabb(previous.body); - const sweptBodyAabb = mergeAabbs([previousBodyAabb, bodyAabb]); +function writeGeometryPose(target, car) { + const pose = target ?? {}; + const x = finiteOr(car.x, 0); + const y = finiteOr(car.y, 0); + const heading = normalizeAngle(finiteOr(car.heading, 0)); + pose.x = x; + pose.y = y; + pose.heading = heading; + pose.previousX = finiteOr(car.previousX, x); + pose.previousY = finiteOr(car.previousY, y); + pose.previousHeading = normalizeAngle(finiteOr(car.previousHeading, heading)); + return pose; +} - return { - pose, - currentSignature: currentPoseSignature(pose), - sweptSignature: sweptPoseSignature(pose), - signature: sweptPoseSignature(pose), - current, - previous, - body: current.body, - wheels: current.wheels, - contactPatches: current.contactPatches, - bodyAabb, - previousBodyAabb, - sweptBodyAabb, +function createGeometryStateShell() { + const state = { + pose: null, + current: null, + previous: null, + body: null, + wheels: null, + contactPatches: null, + bodyAabb: {}, + previousBodyAabb: {}, + sweptBodyAabb: {}, }; + // Signatures are derived lazily from the pose: nothing on the hot path reads + // them, so the per-step string formatting cost must not be paid eagerly. + Object.defineProperties(state, { + currentSignature: { + get() { return currentPoseSignature(this.pose); }, + enumerable: true, + }, + sweptSignature: { + get() { return sweptPoseSignature(this.pose); }, + enumerable: true, + }, + signature: { + get() { return sweptPoseSignature(this.pose); }, + enumerable: true, + }, + }); + return state; +} + +const PREVIOUS_GEOMETRY_POSE_SCRATCH = { x: 0, y: 0, heading: 0 }; + +export function createVehicleGeometryState(car, target = null) { + const state = target ?? createGeometryStateShell(); + const pose = state.pose = writeGeometryPose(state.pose, car); + const current = state.current = writeVehicleGeometry(state.current, pose); + PREVIOUS_GEOMETRY_POSE_SCRATCH.x = pose.previousX; + PREVIOUS_GEOMETRY_POSE_SCRATCH.y = pose.previousY; + PREVIOUS_GEOMETRY_POSE_SCRATCH.heading = pose.previousHeading; + const previous = state.previous = writeVehicleGeometry(state.previous, PREVIOUS_GEOMETRY_POSE_SCRATCH); + const bodyAabb = writeVehicleShapeAabb(state.bodyAabb, current.body); + const previousBodyAabb = writeVehicleShapeAabb(state.previousBodyAabb, previous.body); + const sweptBodyAabb = state.sweptBodyAabb; + sweptBodyAabb.minX = Math.min(bodyAabb.minX, previousBodyAabb.minX); + sweptBodyAabb.maxX = Math.max(bodyAabb.maxX, previousBodyAabb.maxX); + sweptBodyAabb.minY = Math.min(bodyAabb.minY, previousBodyAabb.minY); + sweptBodyAabb.maxY = Math.max(bodyAabb.maxY, previousBodyAabb.maxY); + + state.body = current.body; + state.wheels = current.wheels; + state.contactPatches = current.contactPatches; + return state; } export function createCurrentVehicleGeometryState(car, target = null) { @@ -388,8 +421,13 @@ export function createCurrentVehicleGeometryState(car, target = null) { export function getVehicleGeometryState(car) { if (geometryStateMatches(car, car.geometryState)) return car.geometryState; - car.geometryState = createVehicleGeometryState(car); - return car.geometryState; + // Double-buffer pooled states: consumers may still hold the state returned + // for the previous pose within a step, so alternate between two reusable + // shells instead of allocating a fresh geometry tree on every pose change. + const next = createVehicleGeometryState(car, car._geometryStateSpare ?? null); + car._geometryStateSpare = car.geometryState ?? null; + car.geometryState = next; + return next; } export function getCurrentVehicleGeometryState(car) { diff --git a/src/simulation/vehicle/vehiclePhysics.js b/src/simulation/vehicle/vehiclePhysics.js index bfa0a8a..6012d99 100644 --- a/src/simulation/vehicle/vehiclePhysics.js +++ b/src/simulation/vehicle/vehiclePhysics.js @@ -50,7 +50,11 @@ const SIMULATOR_SURFACE_MODEL = { }; export function normalizePhysicsMode(value) { - return value === 'advanced' ? 'advanced' : DEFAULT_PHYSICS_MODE; + return PHYSICS_MODES.includes(value) ? value : DEFAULT_PHYSICS_MODE; +} + +export function isSimulatorPhysicsMode(value) { + return value === 'advanced'; } function accelerationLimit(speed, surfaceGrip) { @@ -120,7 +124,8 @@ function setPhysicsTelemetry(car, { } export function integrateVehiclePhysics(car, controls, dt, options = {}) { - if (normalizePhysicsMode(options.physicsMode) === 'advanced') { + const mode = normalizePhysicsMode(options.physicsMode); + if (mode === 'advanced') { return integrateSimulatorVehiclePhysics(car, controls, dt, options); } return integrateArcadeVehiclePhysics(car, controls, dt, options); diff --git a/src/simulation/vehicle/vehicleSnapshots.js b/src/simulation/vehicle/vehicleSnapshots.js index db5b80c..3d616d4 100644 --- a/src/simulation/vehicle/vehicleSnapshots.js +++ b/src/simulation/vehicle/vehicleSnapshots.js @@ -1,4 +1,7 @@ -import { serializeParticipantInteraction } from '../participants/participantInteractions.js'; +import { + serializeParticipantInteraction, + serializeParticipantInteractionCached, +} from '../participants/participantInteractions.js'; export function finiteOrNull(value) { return Number.isFinite(value) ? value : null; @@ -185,7 +188,7 @@ export function serializeRenderCarInto(target, car, dependencies) { target.dnfOrder = car.dnfOrder ?? null; target.outOfRace = Boolean(car.outOfRace || car.destroyed); target.pitStop = serializeRenderPitStop(car.pitStop); - target.interaction = serializeParticipantInteraction(car.interaction); + target.interaction = serializeParticipantInteractionCached(car); return target; } diff --git a/src/simulation/vehicle/vehicleState.js b/src/simulation/vehicle/vehicleState.js index 8ede2e6..63438d5 100644 --- a/src/simulation/vehicle/vehicleState.js +++ b/src/simulation/vehicle/vehicleState.js @@ -2,7 +2,7 @@ import { buildDriverPersonality } from '../driverController.js'; import { clamp, normalizeAngle, seededRange } from '../simMath.js'; import { offsetTrackPoint, pointAt } from '../track/trackModel.js'; import { kphToSimSpeed, metersToSimUnits } from '../units.js'; -import { VEHICLE_LIMITS } from './vehiclePhysics.js'; +import { VEHICLE_LIMITS, isSimulatorPhysicsMode } from './vehiclePhysics.js'; import { applyWheelSurfaceState } from './wheelSurface.js'; import { nearestTrackStateForCar } from '../track/trackStatePolicy.js'; import { clearCarDnf } from '../race/retirements.js'; @@ -73,6 +73,7 @@ export function createCar(driver, index, random, track, { standingStart = false, downforceCoefficient: vehicle.downforceCoefficient ?? 6.1 + seededRange(random, -0.18, 0.18), tireGrip: vehicle.tireGrip ?? 2.22 + racecraft * 0.28 + seededRange(random, -0.03, 0.03), tireCare: vehicle.tireCare ?? 1, + driverModel: driver.driverModel ?? vehicle.driverModel ?? null, pace, racecraft, personality, @@ -170,7 +171,7 @@ export function applyExternalCarState(car, partial, context) { } car.speed = clamp(Number.isFinite(car.speed) ? car.speed : 0, 0, VEHICLE_LIMITS.maxSpeed); car.heading = normalizeAngle(Number.isFinite(car.heading) ? car.heading : 0); - syncExternalVelocityState(car, nextPartial, physicsMode === 'advanced'); + syncExternalVelocityState(car, nextPartial, isSimulatorPhysicsMode(physicsMode)); const centerState = nearestTrackStateForCar(track, car, car, car.progress ?? car.raceDistance); applyWheelSurfaceState(car, track, { centerState }); if ( diff --git a/src/ui/raceCanvasTemplate.js b/src/ui/raceCanvasTemplate.js index 889a1ee..cb089fc 100644 --- a/src/ui/raceCanvasTemplate.js +++ b/src/ui/raceCanvasTemplate.js @@ -39,8 +39,9 @@ export function createRaceCanvasMarkup({ } const timingPanelId = includeTimingTower ? createTimingPanelId() : ''; const showPhysicsModeIndicator = debug.physicsModeIndicator === true; - const physicsModeLabel = physicsMode === 'advanced' ? 'Advanced physics mode' : 'Arcade physics mode'; - const physicsModeClass = physicsMode === 'advanced' ? 'advanced' : 'arcade'; + const simulatorPhysics = physicsMode === 'advanced'; + const physicsModeLabel = `${simulatorPhysics ? 'Advanced' : 'Arcade'} physics mode`; + const physicsModeClass = simulatorPhysics ? 'advanced' : 'arcade'; const body = `