@inventure71/paddockjs 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/INSTALL_AND_UPDATE.md +165 -0
  3. package/README.md +217 -20
  4. package/docs/architecture.md +84 -15
  5. package/docs/concepts.md +20 -3
  6. package/docs/data_contract.md +412 -20
  7. package/docs/data_model.md +2 -1
  8. package/docs/index.md +1 -0
  9. package/docs/learnings.md +1 -1
  10. package/docs/rules.md +140 -19
  11. package/docs/system_specs.md +74 -20
  12. package/docs/training.md +206 -0
  13. package/examples/train-basic-policy.mjs +276 -0
  14. package/examples/trainingData.mjs +133 -0
  15. package/package.json +18 -8
  16. package/src/api/PaddockSimulatorController.js +39 -4
  17. package/src/app/BrowserExpertAdapter.js +32 -0
  18. package/src/app/F1SimulatorApp.js +1251 -146
  19. package/src/app/domBindings.js +10 -2
  20. package/src/config/defaultOptions.js +11 -3
  21. package/src/data/championship.js +13 -0
  22. package/src/data/normalizeDrivers.js +7 -2
  23. package/src/environment/actions.js +68 -0
  24. package/src/environment/episode.js +17 -0
  25. package/src/environment/evaluation.js +184 -0
  26. package/src/environment/events.js +17 -0
  27. package/src/environment/index.d.ts +521 -0
  28. package/src/environment/index.js +15 -0
  29. package/src/environment/observationOptions.js +12 -0
  30. package/src/environment/observations.js +284 -0
  31. package/src/environment/options.js +157 -0
  32. package/src/environment/recorder.js +28 -0
  33. package/src/environment/rewards.js +69 -0
  34. package/src/environment/runtime.js +175 -0
  35. package/src/environment/scenarios.js +220 -0
  36. package/src/environment/sensors.js +367 -0
  37. package/src/environment/specs.js +163 -0
  38. package/src/environment/workerProtocol.js +52 -0
  39. package/src/index.d.ts +405 -6
  40. package/src/index.js +27 -2
  41. package/src/rendering/proceduralTrackAsset.js +343 -24
  42. package/src/simulation/collisionGeometry.js +214 -0
  43. package/src/simulation/driverController.js +431 -65
  44. package/src/simulation/raceSimulation.js +2140 -171
  45. package/src/simulation/rules/collisionSteward.js +69 -0
  46. package/src/simulation/rules/penaltyLedger.js +153 -0
  47. package/src/simulation/rules/pitLaneSpeedingSteward.js +71 -0
  48. package/src/simulation/rules/tireRequirementSteward.js +29 -0
  49. package/src/simulation/rules/trackLimitsSteward.js +85 -0
  50. package/src/simulation/rulesConfig.js +352 -0
  51. package/src/simulation/trackModel.js +1154 -76
  52. package/src/simulation/units.js +6 -4
  53. package/src/simulation/vehicleGeometry.js +247 -0
  54. package/src/simulation/vehiclePhysics.js +82 -50
  55. package/src/simulation/wheelSurface.js +338 -0
  56. package/src/styles.css +369 -67
  57. package/src/ui/bannerTemplates.js +69 -0
  58. package/src/ui/componentTemplates.js +45 -81
  59. package/src/ui/raceControlStatusBanner.js +39 -0
  60. package/src/ui/shellTemplate.js +1 -1
  61. package/src/ui/templateUtils.js +23 -0
  62. package/AGENTS.md +0 -86
  63. package/src/standalone.js +0 -15
@@ -0,0 +1,175 @@
1
+ import { createRaceSimulation, FIXED_STEP } from '../simulation/raceSimulation.js';
2
+ import { handleActionError, resolveActionMap } from './actions.js';
3
+ import { collectStepEvents } from './events.js';
4
+ import { createEpisodeState, evaluateEpisode } from './episode.js';
5
+ import { buildEnvironmentObservation } from './observations.js';
6
+ import { resolveEnvironmentOptions } from './options.js';
7
+ import { applyEnvironmentScenario } from './scenarios.js';
8
+ import { buildActionSpec, buildObservationSpec } from './specs.js';
9
+
10
+ export function createPaddockEnvironment(options = {}) {
11
+ let resolvedOptions = resolveEnvironmentOptions(options);
12
+ let sim = createSimulationWithEnvironmentScenario(resolvedOptions);
13
+ return createEnvironmentRuntime({
14
+ getSimulation: () => sim,
15
+ setSimulation(nextSim) {
16
+ sim = nextSim;
17
+ },
18
+ createSimulation(nextOptions) {
19
+ return createSimulationWithEnvironmentScenario(nextOptions);
20
+ },
21
+ getOptions: () => resolvedOptions,
22
+ setOptions(nextOptions) {
23
+ resolvedOptions = nextOptions;
24
+ },
25
+ afterReset() {},
26
+ afterStep() {},
27
+ });
28
+ }
29
+
30
+ function createSimulationWithEnvironmentScenario(options) {
31
+ const sim = createRaceSimulation(options);
32
+ applyEnvironmentScenario(sim, options);
33
+ return sim;
34
+ }
35
+
36
+ export function createEnvironmentRuntime(host) {
37
+ const episodeState = createEpisodeState();
38
+
39
+ initializeControlledPitIntent(host);
40
+
41
+ function reset(nextOptions = {}) {
42
+ const options = resolveEnvironmentOptions({
43
+ ...host.getOptions(),
44
+ ...nextOptions,
45
+ });
46
+ host.setOptions(options);
47
+ host.setSimulation(host.createSimulation(options));
48
+ initializeControlledPitIntent(host);
49
+ episodeState.step = 0;
50
+ episodeState.previousSnapshot = null;
51
+ const result = buildResult({ host, episodeState, events: [], actionErrors: [] });
52
+ episodeState.lastResult = result;
53
+ host.afterReset(result);
54
+ return result;
55
+ }
56
+
57
+ function step(actions = {}) {
58
+ const options = host.getOptions();
59
+ const sim = host.getSimulation();
60
+ const { controlsByDriver, pitIntentByDriver, errors } = resolveActionMap(actions, options.controlledDrivers, {
61
+ policy: options.actionPolicy,
62
+ });
63
+
64
+ Object.entries(controlsByDriver).forEach(([driverId, controls]) => {
65
+ sim.setCarControls(driverId, controls);
66
+ });
67
+ Object.entries(pitIntentByDriver).forEach(([driverId, pitIntent]) => {
68
+ const applied = Boolean(sim.setPitIntent?.(driverId, pitIntent));
69
+ if (!applied && !isNoopPitIntent(pitIntent)) {
70
+ handleActionError(`Pit intent could not be applied for controlled driver: ${driverId}`, options.actionPolicy, errors);
71
+ }
72
+ });
73
+
74
+ episodeState.previousSnapshot = episodeState.lastResult?.state?.snapshot ?? sim.snapshot();
75
+ const stepEvents = [];
76
+ for (let index = 0; index < options.frameSkip; index += 1) {
77
+ sim.step(FIXED_STEP);
78
+ const events = typeof sim.consumeStepEvents === 'function'
79
+ ? sim.consumeStepEvents()
80
+ : sim.events;
81
+ stepEvents.push(...collectStepEvents(events));
82
+ }
83
+ episodeState.step += 1;
84
+ const result = buildResult({ host, episodeState, events: stepEvents, actionErrors: errors, actions });
85
+ episodeState.lastResult = result;
86
+ host.afterStep(result);
87
+ return result;
88
+ }
89
+
90
+ function getObservation() {
91
+ return episodeState.lastResult?.observation ??
92
+ buildResult({ host, episodeState, events: [], actionErrors: [] }).observation;
93
+ }
94
+
95
+ function getState() {
96
+ return { snapshot: host.getSimulation().snapshot() };
97
+ }
98
+
99
+ function getActionSpec() {
100
+ return buildActionSpec(host.getOptions());
101
+ }
102
+
103
+ function getObservationSpec() {
104
+ return buildObservationSpec(host.getOptions());
105
+ }
106
+
107
+ function destroy() {
108
+ episodeState.lastResult = null;
109
+ episodeState.previousSnapshot = null;
110
+ }
111
+
112
+ return { reset, step, getObservation, getState, getActionSpec, getObservationSpec, destroy };
113
+ }
114
+
115
+ function isNoopPitIntent(pitIntent) {
116
+ if (pitIntent && typeof pitIntent === 'object') {
117
+ return Number(pitIntent.intent ?? pitIntent.pitIntent) === 0;
118
+ }
119
+ return Number(pitIntent) === 0;
120
+ }
121
+
122
+ function initializeControlledPitIntent(host) {
123
+ const sim = host.getSimulation?.();
124
+ const options = host.getOptions?.();
125
+ options?.controlledDrivers?.forEach?.((driverId) => {
126
+ sim?.setAutomaticPitIntentEnabled?.(driverId, false);
127
+ sim?.setPitIntent?.(driverId, 0);
128
+ });
129
+ }
130
+
131
+ function buildResult({ host, episodeState, events, actionErrors, actions = {} }) {
132
+ const options = host.getOptions();
133
+ const snapshot = host.getSimulation().snapshot();
134
+ const observation = buildEnvironmentObservation({
135
+ snapshot,
136
+ previousSnapshot: episodeState.previousSnapshot,
137
+ options,
138
+ events,
139
+ });
140
+ const episode = evaluateEpisode(snapshot, options, episodeState);
141
+ const reward = computeReward({ options, observation, events, snapshot, actions, previousSnapshot: episodeState.previousSnapshot });
142
+ return {
143
+ observation,
144
+ reward,
145
+ terminated: episode.terminated,
146
+ truncated: episode.truncated,
147
+ done: episode.terminated || episode.truncated,
148
+ events,
149
+ state: { snapshot },
150
+ info: {
151
+ step: episodeState.step,
152
+ elapsedSeconds: snapshot.time,
153
+ seed: options.seed,
154
+ trackSeed: options.trackSeed,
155
+ controlledDrivers: [...options.controlledDrivers],
156
+ actionErrors,
157
+ endReason: episode.endReason,
158
+ },
159
+ };
160
+ }
161
+
162
+ function computeReward({ options, observation, events, snapshot, actions, previousSnapshot }) {
163
+ if (!options.reward) return null;
164
+ return Object.fromEntries(options.controlledDrivers.map((driverId) => [
165
+ driverId,
166
+ Number(options.reward({
167
+ driverId,
168
+ previous: previousSnapshot,
169
+ current: observation[driverId],
170
+ action: actions?.[driverId],
171
+ events: observation[driverId]?.events ?? events,
172
+ state: { snapshot },
173
+ }) ?? 0),
174
+ ]));
175
+ }
@@ -0,0 +1,220 @@
1
+ import { normalizeAngle } from '../simulation/simMath.js';
2
+ import { offsetTrackPoint, pointAt } from '../simulation/trackModel.js';
3
+ import { kphToSimSpeed, metersToSimUnits, simUnitsToMeters } from '../simulation/units.js';
4
+
5
+ export const ENVIRONMENT_SCENARIO_PRESETS = Object.freeze([
6
+ 'cornering',
7
+ 'off-track-recovery',
8
+ 'overtaking-pack',
9
+ 'pit-entry',
10
+ ]);
11
+
12
+ export function resolveScenarioPlacementConfig(scenario = {}, driverIds = new Set()) {
13
+ const preset = scenario.preset == null ? null : String(scenario.preset);
14
+ if (preset && !ENVIRONMENT_SCENARIO_PRESETS.includes(preset)) {
15
+ throw new Error(`PaddockJS environment scenario.preset must be one of: ${ENVIRONMENT_SCENARIO_PRESETS.join(', ')}.`);
16
+ }
17
+
18
+ const placements = normalizePlacementMap(scenario.placements, driverIds);
19
+ const traffic = normalizeTrafficLayout(scenario.traffic, driverIds);
20
+
21
+ return {
22
+ preset,
23
+ placements,
24
+ traffic,
25
+ };
26
+ }
27
+
28
+ export function applyEnvironmentScenario(sim, options) {
29
+ const scenario = options.scenario ?? {};
30
+ if (!scenario.preset && Object.keys(scenario.placements ?? {}).length === 0 && (scenario.traffic ?? []).length === 0) {
31
+ return;
32
+ }
33
+
34
+ const snapshot = sim.snapshot();
35
+ const carsById = new Map(snapshot.cars.map((car) => [car.id, car]));
36
+ const placements = {
37
+ ...buildPresetPlacements(snapshot, options),
38
+ ...(scenario.placements ?? {}),
39
+ };
40
+
41
+ Object.entries(placements).forEach(([driverId, placement]) => {
42
+ if (!carsById.has(driverId)) return;
43
+ applyPlacement(sim, snapshot.track, carsById.get(driverId), driverId, placement);
44
+ });
45
+
46
+ const nextSnapshot = sim.snapshot();
47
+ const nextCarsById = new Map(nextSnapshot.cars.map((car) => [car.id, car]));
48
+ scenario.traffic?.forEach((trafficPlacement) => {
49
+ const reference = nextCarsById.get(trafficPlacement.relativeTo);
50
+ const car = nextCarsById.get(trafficPlacement.driverId);
51
+ if (!reference || !car) return;
52
+ applyPlacement(sim, nextSnapshot.track, car, trafficPlacement.driverId, {
53
+ distanceMeters: reference.distanceMeters + trafficPlacement.deltaDistanceMeters,
54
+ offsetMeters: trafficPlacement.offsetMeters,
55
+ speedKph: trafficPlacement.speedKph ?? reference.speedKph,
56
+ headingErrorRadians: trafficPlacement.headingErrorRadians ?? 0,
57
+ });
58
+ });
59
+ }
60
+
61
+ function normalizePlacementMap(value, driverIds) {
62
+ if (value == null) return {};
63
+ if (typeof value !== 'object' || Array.isArray(value)) {
64
+ throw new Error('PaddockJS environment scenario.placements must be an object keyed by driver id.');
65
+ }
66
+ return Object.fromEntries(Object.entries(value).map(([driverId, placement]) => {
67
+ assertKnownDriver(driverId, driverIds, 'scenario placement');
68
+ return [driverId, normalizePlacement(placement, `scenario.placements.${driverId}`)];
69
+ }));
70
+ }
71
+
72
+ function normalizeTrafficLayout(value, driverIds) {
73
+ if (value == null) return [];
74
+ if (!Array.isArray(value)) {
75
+ throw new Error('PaddockJS environment scenario.traffic must be an array.');
76
+ }
77
+ return value.map((entry, index) => {
78
+ if (!entry || typeof entry !== 'object') {
79
+ throw new Error(`PaddockJS environment scenario.traffic[${index}] must be an object.`);
80
+ }
81
+ assertKnownDriver(entry.driverId, driverIds, `scenario.traffic[${index}].driverId`);
82
+ assertKnownDriver(entry.relativeTo, driverIds, `scenario.traffic[${index}].relativeTo`);
83
+ return {
84
+ driverId: entry.driverId,
85
+ relativeTo: entry.relativeTo,
86
+ deltaDistanceMeters: finiteNumber(entry.deltaDistanceMeters, 0, `scenario.traffic[${index}].deltaDistanceMeters`),
87
+ offsetMeters: finiteNumber(entry.offsetMeters, 0, `scenario.traffic[${index}].offsetMeters`),
88
+ speedKph: optionalFiniteNumber(entry.speedKph, `scenario.traffic[${index}].speedKph`),
89
+ headingErrorRadians: finiteNumber(entry.headingErrorRadians, 0, `scenario.traffic[${index}].headingErrorRadians`),
90
+ };
91
+ });
92
+ }
93
+
94
+ function normalizePlacement(placement, label) {
95
+ if (!placement || typeof placement !== 'object') {
96
+ throw new Error(`PaddockJS environment ${label} must be an object.`);
97
+ }
98
+ const distanceMeters = placement.distanceMeters ?? placement.startDistanceMeters;
99
+ return {
100
+ distanceMeters: optionalFiniteNumber(distanceMeters, `${label}.distanceMeters`),
101
+ offsetMeters: finiteNumber(placement.offsetMeters, 0, `${label}.offsetMeters`),
102
+ speedKph: optionalFiniteNumber(placement.speedKph, `${label}.speedKph`),
103
+ headingErrorRadians: finiteNumber(placement.headingErrorRadians, 0, `${label}.headingErrorRadians`),
104
+ };
105
+ }
106
+
107
+ function buildPresetPlacements(snapshot, options) {
108
+ const preset = options.scenario?.preset;
109
+ if (!preset) return {};
110
+ const controlledDriverId = options.controlledDrivers[0];
111
+ const cars = snapshot.cars;
112
+ const track = snapshot.track;
113
+ const primaryDistance = presetBaseDistance(track, preset);
114
+ const placements = {};
115
+
116
+ if (preset === 'cornering') {
117
+ placements[controlledDriverId] = {
118
+ distanceMeters: simUnitsToMeters(primaryDistance),
119
+ offsetMeters: 0,
120
+ speedKph: 135,
121
+ headingErrorRadians: 0,
122
+ };
123
+ } else if (preset === 'off-track-recovery') {
124
+ placements[controlledDriverId] = {
125
+ distanceMeters: simUnitsToMeters(primaryDistance),
126
+ offsetMeters: simUnitsToMeters(track.width / 2) + 7,
127
+ speedKph: 52,
128
+ headingErrorRadians: -0.45,
129
+ };
130
+ } else if (preset === 'pit-entry') {
131
+ placements[controlledDriverId] = {
132
+ distanceMeters: simUnitsToMeters(primaryDistance),
133
+ offsetMeters: 0,
134
+ speedKph: 120,
135
+ headingErrorRadians: 0,
136
+ };
137
+ } else if (preset === 'overtaking-pack') {
138
+ const baseMeters = simUnitsToMeters(primaryDistance);
139
+ cars.slice(0, 4).forEach((car, index) => {
140
+ placements[car.id] = {
141
+ distanceMeters: baseMeters + (index - 1) * 18,
142
+ offsetMeters: index % 2 === 0 ? -2.2 : 2.2,
143
+ speedKph: 135 - index * 3,
144
+ headingErrorRadians: 0,
145
+ };
146
+ });
147
+ }
148
+
149
+ return placements;
150
+ }
151
+
152
+ function presetBaseDistance(track, preset) {
153
+ if (preset === 'cornering') return findHighCurvatureDistance(track) - metersToSimUnits(70);
154
+ if (preset === 'off-track-recovery') return track.length * 0.42;
155
+ if (preset === 'overtaking-pack') return track.length * 0.35;
156
+ if (preset === 'pit-entry') {
157
+ const pitDistance = track.pitLane?.entry?.trackDistance ??
158
+ track.pitLane?.entry?.distanceFromStart ??
159
+ track.length * 0.92;
160
+ return pitDistance - metersToSimUnits(170);
161
+ }
162
+ return 0;
163
+ }
164
+
165
+ function findHighCurvatureDistance(track) {
166
+ const samples = Array.isArray(track.samples) ? track.samples : [];
167
+ const fallback = track.length * 0.25;
168
+ const best = samples
169
+ .filter((sample) => sample.distance > metersToSimUnits(350))
170
+ .reduce((selected, sample) => {
171
+ if (!selected || (sample.curvature ?? 0) > (selected.curvature ?? 0)) return sample;
172
+ return selected;
173
+ }, null);
174
+ return best?.distance ?? fallback;
175
+ }
176
+
177
+ function applyPlacement(sim, track, currentCar, driverId, placement) {
178
+ const currentDistanceMeters = currentCar.distanceMeters ?? simUnitsToMeters(currentCar.raceDistance ?? currentCar.progress ?? 0);
179
+ const raceDistance = metersToSimUnits(Math.max(0, placement.distanceMeters ?? currentDistanceMeters));
180
+ const offset = metersToSimUnits(placement.offsetMeters ?? 0);
181
+ const base = pointAt(track, raceDistance);
182
+ const position = offsetTrackPoint(base, offset);
183
+ const heading = normalizeAngle(base.heading + (placement.headingErrorRadians ?? 0));
184
+ const partial = {
185
+ x: position.x,
186
+ y: position.y,
187
+ previousX: position.x,
188
+ previousY: position.y,
189
+ progress: base.distance,
190
+ raceDistance,
191
+ desiredOffset: offset,
192
+ heading,
193
+ previousHeading: heading,
194
+ };
195
+ if (placement.speedKph != null) partial.speed = kphToSimSpeed(placement.speedKph);
196
+ sim.setCarState(driverId, partial);
197
+ }
198
+
199
+ function assertKnownDriver(driverId, driverIds, label) {
200
+ if (typeof driverId !== 'string' || driverId.length === 0) {
201
+ throw new Error(`PaddockJS environment ${label} must be a driver id.`);
202
+ }
203
+ if (!driverIds.has(driverId)) {
204
+ throw new Error(`PaddockJS environment ${label} does not exist: ${driverId}`);
205
+ }
206
+ }
207
+
208
+ function finiteNumber(value, fallback, label) {
209
+ if (value == null) return fallback;
210
+ const number = Number(value);
211
+ if (!Number.isFinite(number)) {
212
+ throw new Error(`PaddockJS environment ${label} must be a finite number.`);
213
+ }
214
+ return number;
215
+ }
216
+
217
+ function optionalFiniteNumber(value, label) {
218
+ if (value == null) return undefined;
219
+ return finiteNumber(value, undefined, label);
220
+ }