@adatechnology/game-vehicles-driving 0.2.31 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/arcade.ts","../src/run-over.ts","../src/semi/fuel.ts","../src/semi/surfaces.ts","../src/semi/driver.ts","../src/semi/impact.ts","../src/semi/vehicle-type.ts","../src/semi/from-stats.ts","../src/driving-aids.ts","../src/controls.ts","../src/semi/condition.ts","../src/systems.ts","../src/ejection.ts","../src/parking-sensor.ts","../src/storage.ts","../src/windshield-fog.ts","../src/physics-desc.ts","../src/physics-input.ts","../src/physics-resistance.ts","../src/physics-run-over.ts"],"sourcesContent":["import type { DriveInput, Driver, DriverState, DrivingEvent, DrivingWorld, StepResult } from './types'\n\nexport interface RunOverRules {\n /** Above this speed (m/s) a body is knocked down. */\n knockSpeed: number\n /** Above this speed a body is killed. */\n killSpeed: number\n /** Knock damage is `speed² * knockDamage`. */\n knockDamage: number\n /** Seconds a knocked body is stunned. */\n stunSeconds: number\n /** Fraction of the vehicle speed given to a knocked body. */\n throwFactor: number\n /** Sideways speed added to a knocked body. */\n sideKick: number\n /** The vehicle keeps this fraction of its speed after knocking a body. */\n knockSlow: number\n /** Damage the vehicle takes for each body killed. */\n killVehicleDamage: number\n /** Below `knockSpeed` the vehicle slows by `exp(-holdDrag * dt)` for each body in the way. */\n holdDrag: number\n /** Metres added around the vehicle's footprint when testing a body. */\n margin: number\n}\n\nexport interface CrashRules {\n /** Below this speed an impact is only a bump (no event, but the vehicle still bounces). */\n minSpeed: number\n /** Above this speed the impact damages the vehicle by `speed * damage`. */\n damageSpeed: number\n damage: number\n /** Camera shake is `speed / shakeDivisor`. */\n shakeDivisor: number\n /** Above this speed the driver is hurt by `speed * hurtFactor`. */\n hurtSpeed: number\n hurtFactor: number\n /** The speed after an impact is `v * bounce`. */\n bounce: number\n noiseRadius: number\n}\n\n/** The numbers of the game's drivable car (G 70188-70290). Every one is an option. */\nexport interface ArcadeSpec {\n length: number\n width: number\n accel: number\n /** Deceleration when accelerating against a reverse move, or braking against a forward move. */\n brakeAgainstMotion: number\n reverseAccel: number\n /** Coasting drag: `v *= exp(-drag * dt)`. */\n drag: number\n handbrakeDrag: number\n maxForward: number\n maxReverse: number\n /** Largest steering angle, radians. */\n steerMax: number\n /** The steering angle follows its target by `min(1, steerResponse * dt)`. */\n steerResponse: number\n /** Distance used in `yaw += steer * v / wheelbase * dt`. */\n wheelbase: number\n engineNoiseInterval: number\n engineNoiseBase: number\n engineNoiseSpeedFactor: number\n hornNoiseRadius: number\n crash: CrashRules\n runOver: RunOverRules\n}\n\nexport const defaultArcadeSpec: ArcadeSpec = {\n length: 4.3,\n width: 1.9,\n accel: 5.5,\n brakeAgainstMotion: 12,\n reverseAccel: 3,\n drag: 0.5,\n handbrakeDrag: 3,\n maxForward: 17,\n maxReverse: -5,\n steerMax: 0.55,\n steerResponse: 5,\n wheelbase: 2.6,\n engineNoiseInterval: 0.5,\n engineNoiseBase: 25,\n engineNoiseSpeedFactor: 2,\n hornNoiseRadius: 120,\n crash: { minSpeed: 0.5, damageSpeed: 4, damage: 9, shakeDivisor: 20, hurtSpeed: 9, hurtFactor: 1.2, bounce: -0.25, noiseRadius: 25 },\n runOver: { knockSpeed: 3, killSpeed: 8, knockDamage: 2.5, stunSeconds: 1.4, throwFactor: 0.8, sideKick: 2, knockSlow: 0.93, killVehicleDamage: 3, holdDrag: 2.5, margin: 0.3 },\n}\n\nexport type ArcadeOptions = Partial<Omit<ArcadeSpec, 'crash' | 'runOver'>> & { crash?: Partial<CrashRules>; runOver?: Partial<RunOverRules> }\n\n/** The eight points the game tests for a wall: the four corners, the middle of the front and rear, and the middle of both sides. */\nexport function vehicleCorners(spec: Pick<ArcadeSpec, 'length' | 'width'>, x: number, z: number, yaw: number): Array<[number, number]> {\n const c = Math.cos(yaw)\n const s = Math.sin(yaw)\n const hl = spec.length / 2\n const hw = spec.width / 2\n const out: Array<[number, number]> = []\n for (const [a, b] of [[hl, hw], [hl, -hw], [-hl, hw], [-hl, -hw], [hl, 0], [-hl, 0], [0, hw], [0, -hw]] as const) out.push([x + a * c + b * s, z - a * s + b * c])\n return out\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\n/**\n * The arcade driver: the game's car, extracted. A pure step function over `DriverState`: no three.js, no game. Port of `carUpdate`\n * (jogo.js 70233-70290) with the same order of operations, so a scripted run gives the same positions and events.\n */\nexport function createArcadeDriver(options: ArcadeOptions = {}): Driver & { readonly spec: ArcadeSpec } {\n const spec: ArcadeSpec = {\n ...defaultArcadeSpec,\n ...options,\n crash: { ...defaultArcadeSpec.crash, ...(options.crash || {}) },\n runOver: { ...defaultArcadeSpec.runOver, ...(options.runOver || {}) },\n }\n const state: DriverState = { x: 0, z: 0, yaw: 0, v: 0, steer: 0, noiseTimer: 0 }\n\n const step = (input: DriveInput, dt: number, world: DrivingWorld): StepResult => {\n const events: DrivingEvent[] = []\n const f = (input.throttle > 0 ? 1 : 0) - (input.brake > 0 ? 1 : 0)\n if (f > 0) state.v += (state.v < 0 ? spec.brakeAgainstMotion : spec.accel) * dt * Math.min(1, input.throttle)\n else if (f < 0) state.v -= (state.v > 0 ? spec.brakeAgainstMotion : spec.reverseAccel) * dt * Math.min(1, input.brake)\n else state.v *= Math.exp(-spec.drag * dt)\n if (input.handbrake) state.v *= Math.exp(-spec.handbrakeDrag * dt)\n state.v = clamp(state.v, spec.maxReverse, spec.maxForward)\n state.steer = lerp(state.steer, clamp(input.steer, -1, 1) * spec.steerMax, Math.min(1, dt * spec.steerResponse))\n const nyaw = state.yaw + ((state.steer * state.v) / spec.wheelbase) * dt\n const fx = Math.cos(nyaw)\n const fz = -Math.sin(nyaw)\n const nx = state.x + fx * state.v * dt\n const nz = state.z + fz * state.v * dt\n if (!world.blocked(nx, nz, nyaw)) {\n state.x = nx\n state.z = nz\n state.yaw = nyaw\n } else if (Math.abs(state.v) > spec.crash.minSpeed) {\n const sp = Math.abs(state.v)\n if (sp > spec.crash.damageSpeed) {\n events.push({ type: 'crash', speed: sp, damage: sp * spec.crash.damage, shake: sp / spec.crash.shakeDivisor, hurtDriver: sp > spec.crash.hurtSpeed ? sp * spec.crash.hurtFactor : 0 })\n events.push({ type: 'noise', radius: spec.crash.noiseRadius, x: state.x, z: state.z, source: 'crash' })\n }\n state.v *= spec.crash.bounce\n }\n // run-over: speed is read once, before the loop, as the game does\n const sp = Math.abs(state.v)\n const ro = spec.runOver\n const bodies = world.bodies ? world.bodies() : []\n for (let i = 0; i < bodies.length; i++) {\n const body = bodies[i]\n if (!body) continue\n const dx = body.x - state.x\n const dz = body.z - state.z\n const a = dx * fx + dz * fz\n const b = -dx * fz + dz * fx\n if (Math.abs(a) > spec.length / 2 + ro.margin || Math.abs(b) > spec.width / 2 + ro.margin) continue\n if (sp > ro.killSpeed) events.push({ type: 'run_over', outcome: 'kill', index: i, speed: sp, vehicleDamage: ro.killVehicleDamage })\n else if (sp > ro.knockSpeed) {\n events.push({\n type: 'run_over',\n outcome: 'knock',\n index: i,\n speed: sp,\n damage: sp * sp * ro.knockDamage,\n stunSeconds: ro.stunSeconds,\n vx: fx * sp * ro.throwFactor + (b > 0 ? -fz : fz) * ro.sideKick,\n vz: fz * sp * ro.throwFactor + (b > 0 ? fx : -fx) * ro.sideKick,\n slow: ro.knockSlow,\n })\n state.v *= ro.knockSlow\n } else {\n state.v *= Math.exp(-ro.holdDrag * dt)\n events.push({ type: 'run_over', outcome: 'push', index: i, speed: sp, dx: (b > 0 ? -fz : fz) * dt, dz: (b > 0 ? fx : -fx) * dt })\n }\n }\n state.noiseTimer -= dt\n if (state.noiseTimer <= 0) {\n state.noiseTimer = spec.engineNoiseInterval\n events.push({ type: 'noise', radius: spec.engineNoiseBase + sp * spec.engineNoiseSpeedFactor, x: state.x, z: state.z, source: 'engine' })\n }\n if (input.horn) {\n events.push({ type: 'noise', radius: spec.hornNoiseRadius, x: state.x, z: state.z, source: 'horn' })\n events.push({ type: 'horn' })\n }\n return { state, events }\n }\n\n return {\n spec,\n state,\n step,\n place(x, z, yaw) {\n state.x = x\n state.z = z\n state.yaw = yaw\n state.v = 0\n state.steer = 0\n },\n }\n}\n","import type { RunOverRules } from './arcade'\nimport { defaultArcadeSpec } from './arcade'\n\nexport type RunOverOutcome = 'push' | 'knock' | 'kill'\n\n/** What a vehicle moving at `speed` (m/s) does to a body it touches: pushes it (and is held), knocks it down, or kills it. */\nexport function runOver(speed: number, rules: Partial<RunOverRules> = {}): RunOverOutcome {\n const { knockSpeed, killSpeed } = { ...defaultArcadeSpec.runOver, ...rules }\n const s = Math.abs(speed)\n return s > killSpeed ? 'kill' : s > knockSpeed ? 'knock' : 'push'\n}\n","export interface FuelModel {\n /** Litres per second at idle. */\n idleRate: number\n /** Extra litres per second at full throttle and redline. */\n fullRate: number\n /** Extra consumption per unit of cargo mass over the vehicle's own mass (0.5 = +50% when the load equals the vehicle). */\n loadFactor: number\n /** Extra consumption of a wrecked engine (0.4 = up to +40% at zero health). */\n damagedEngineExtra: number\n}\n\nexport const defaultFuelModel: FuelModel = { idleRate: 0.0003, fullRate: 0.0035, loadFactor: 0.5, damagedEngineExtra: 0.4 }\n\n/**\n * Litres per second: it depends on the RPM, the throttle, the weight of the cargo and the state of the engine\n * (Frota document, section 04: \"a damaged engine spends up to 40% more\").\n */\nexport function fuelRate(model: FuelModel, rpmFraction: number, throttle: number, loadRatio: number, engineHealth: number): number {\n const base = model.idleRate + model.fullRate * Math.max(0, Math.min(1, rpmFraction)) * Math.max(0, Math.min(1, throttle))\n return base * (1 + model.loadFactor * Math.max(0, loadRatio)) * (1 + model.damagedEngineExtra * (1 - Math.max(0, Math.min(1, engineHealth))))\n}\n","import { applyPatches, mergeById, removeIds } from '@adatechnology/game-contracts'\n\n/** A kind of ground the tyres run on. */\nexport interface Surface {\n id: string\n /** Multiplier of the tyre grip (dry asphalt = 1). */\n grip: number\n /** Above this speed (km/h) the tyres float: grip drops linearly to `grip * aquaplaningFactor` over `aquaplaningBand` km/h. */\n aquaplaningKmh?: number\n aquaplaningFactor?: number\n aquaplaningBand?: number\n /** A vehicle without four-wheel drive sinks: its rolling resistance becomes the spec's `bogResistance`. */\n bogs?: boolean\n}\n\n/** The table of the Frota document, section 03 (Surfaces). Every number is a default a game can replace. */\nexport const defaultSurfaces: readonly Surface[] = [\n { id: 'dry_asphalt', grip: 1 },\n { id: 'wet_asphalt', grip: 0.75, aquaplaningKmh: 90, aquaplaningFactor: 0.4, aquaplaningBand: 30 },\n { id: 'dirt', grip: 0.65 },\n { id: 'grass', grip: 0.55 },\n { id: 'mud', grip: 0.4, bogs: true },\n /** Blood and bodies after a run-over; a driver applies it for a few seconds with `contaminate`. */\n { id: 'blood', grip: 0.5 },\n]\n\nexport interface SurfaceOptions {\n packs?: ReadonlyArray<{ surfaces?: readonly Surface[] }>\n patch?: Readonly<Record<string, Partial<Surface>>>\n remove?: readonly string[]\n}\n\nexport interface SurfaceRegistry {\n get(id: string): Surface\n readonly surfaces: readonly Surface[]\n}\n\n/** The registry of surfaces: the document's table, plus packs, patches and removals by id. An unknown id falls back to dry asphalt. */\nexport function createSurfaces(options: SurfaceOptions = {}): SurfaceRegistry {\n const entries = mergeById(defaultSurfaces, options.packs?.flatMap((pack) => pack.surfaces ?? []))\n applyPatches(entries, options.patch)\n removeIds(entries, options.remove)\n const fallback = entries.get('dry_asphalt') ?? ({ id: 'dry_asphalt', grip: 1 } as Surface)\n return {\n get: (id) => entries.get(id) ?? fallback,\n get surfaces() {\n return [...entries.values()]\n },\n }\n}\n\n/** Grip of a surface at a speed, with aquaplaning. */\nexport function surfaceGrip(surface: Surface, speedMetresPerSecond: number): number {\n if (surface.aquaplaningKmh == null) return surface.grip\n const kmh = Math.abs(speedMetresPerSecond) * 3.6\n const band = surface.aquaplaningBand ?? 30\n const t = Math.max(0, Math.min(1, (kmh - surface.aquaplaningKmh) / band))\n return surface.grip * (1 - (1 - (surface.aquaplaningFactor ?? 0.4)) * t)\n}\n","import type { Driver } from '../types'\nimport { fuelRate, defaultFuelModel } from './fuel'\nimport type { FuelModel } from './fuel'\nimport { createSurfaces, surfaceGrip } from './surfaces'\nimport type { SurfaceRegistry } from './surfaces'\nimport type { SemiEvent, SemiInput, SemiSimSpec, SemiState, SemiWorld, VehicleCondition } from './types'\n\nconst G = 9.81\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\nconst MAX_SUBSTEP = 1 / 240\nexport const FLAT_BELOW = 0.2\n/**\n * A wheel without its tyre (chosen by the physics of a bare rim on asphalt): the rim is about seven tenths of the wheel's radius (the sidewall is gone),\n * steel or aluminium sliding on asphalt holds about 0.4 of the load (rubber 1.05), and the flange gouging the road drags like a coefficient of 0.25\n * against the 0.015 of a tyre: the corner drops, grips less and brakes, so the car pulls to that side and loses speed. A flat tyre sags this much, metres,\n * and drags six times a whole one.\n */\nexport const RIM_RADIUS_SHARE = 0.7\nexport const RIM_FRICTION = 0.4\nconst RIM_ROLLING = 0.25\nexport const FLAT_SAG = 0.05\nconst FLAT_ROLLING = 6\nexport const STALL_HEALTH = 0.3\n/** Clutch: engaged past this share it drags the engine; below this share of the idle, with less gas than `STALL_GAS`, the engine dies. */\nconst CLUTCH_BITE = 0.7\nconst STALL_RPM = 0.5\nconst STALL_GAS = 0.35\n\n/** A mid-size passenger car, so a game can start from numbers that drive like a car. Every field can be replaced. */\nexport const defaultSemiSpec: SemiSimSpec = {\n mass: 1300,\n centreHeight: 0.5,\n wheels: [\n { x: 1.3, z: -0.75, steer: true },\n { x: 1.3, z: 0.75, steer: true },\n { x: -1.3, z: -0.75, drive: true, handbrake: true },\n { x: -1.3, z: 0.75, drive: true, handbrake: true },\n ],\n wheelRadius: 0.32,\n fourWheelDrive: false,\n drag: 0.4,\n rolling: 0.015,\n bogResistance: 0.3,\n maxSteer: 0.55,\n brakeForce: 14000,\n engine: { idleRpm: 900, peakRpm: 4200, redlineRpm: 6500, peakTorque: 220 },\n gears: [3.6, 2.2, 1.5, 1.1, 0.85],\n reverseRatio: 3.4,\n finalDrive: 3.7,\n efficiency: 0.85,\n upshiftFraction: 0.85,\n downshiftFraction: 0.35,\n suspension: { restLength: 0.4, spring: 32000, damper: 3200 },\n tyre: { friction: 1.05, corneringStiffness: 9 },\n tank: { capacity: 45 },\n}\n\nexport interface SemiSimOptions {\n surfaces?: SurfaceRegistry\n}\n\nexport interface SemiDriver extends Omit<Driver, 'step' | 'state'> {\n readonly spec: SemiSimSpec\n readonly state: SemiState\n condition: VehicleCondition\n /** Sets the load carried, kilograms; the mass, the wheel loads and the fuel use follow. */\n setCargo(kg: number): void\n /** A surface that overrides the ground under the wheels for `seconds` (blood after a run-over). */\n contaminate(surfaceId: string, seconds: number): void\n /** Fills the tank (litres). */\n refuel(litres: number): void\n step(input: SemiInput, dt: number, world?: SemiWorld): { state: SemiState; events: SemiEvent[] }\n}\n\nexport const torqueAt = (spec: SemiSimSpec, rpm: number): number => {\n const e = spec.engine\n if (rpm >= e.redlineRpm) return 0\n const t = rpm <= e.peakRpm ? 0.7 + 0.3 * clamp((rpm - e.idleRpm) / (e.peakRpm - e.idleRpm), 0, 1) : 1 - 0.4 * ((rpm - e.peakRpm) / (e.redlineRpm - e.peakRpm))\n return e.peakTorque * t\n}\n\n/**\n * The semi-simulation driver (Frota document, section 03): a single rigid body with a low centre of mass, a spring and damper on each wheel\n * measured against the ground under it, separate longitudinal and lateral tyre forces inside a friction circle, an automatic gearbox with a\n * simulated RPM, a handbrake that locks the rear wheels, surfaces with their grip, and damage that changes how it drives. No team code exists\n * for it: the numbers are the document's and the tests check them.\n */\n/** Sliding friction of a locked tyre against its rolling grip, and how much of its side grip is left. */\nconst SLIDING_GRIP = 0.75\nconst LOCKED_STEER = 0.15\n/** Brakes: air temperature, where they start to fade and where only `BRAKE_FADED` of their force is left, joules per °C per kg of vehicle, cooling time. */\nconst AMBIENT_C = 25\nconst BRAKE_FADE_FROM_C = 350\nconst BRAKE_FADE_TO_C = 650\nconst BRAKE_FADED = 0.5\nconst BRAKE_HEAT_CAPACITY = 3\nconst BRAKE_COOL_S = 60\n\nexport function createSemiSimDriver(specification: Partial<SemiSimSpec> = {}, options: SemiSimOptions = {}): SemiDriver {\n const spec: SemiSimSpec = { ...defaultSemiSpec, ...specification }\n const surfaces = options.surfaces ?? createSurfaces()\n const fuelModel: FuelModel = { ...defaultFuelModel, ...spec.tank }\n const wheelbase = Math.max(...spec.wheels.map((w) => w.x)) - Math.min(...spec.wheels.map((w) => w.x))\n const track = Math.max(...spec.wheels.map((w) => w.z)) - Math.min(...spec.wheels.map((w) => w.z))\n const baseMass = spec.mass\n let cargo = 0\n let contamination: { id: string; left: number } | null = null\n const n = spec.wheels.length\n const state: SemiState = {\n x: 0,\n z: 0,\n yaw: 0,\n u: 0,\n w: 0,\n yawRate: 0,\n height: spec.suspension.restLength + spec.wheelRadius - (spec.mass * G) / (specification.wheels ? specification.wheels.length : defaultSemiSpec.wheels.length) / spec.suspension.spring,\n heightRate: 0,\n pitch: 0,\n pitchRate: 0,\n roll: 0,\n rollRate: 0,\n rpm: spec.engine.idleRpm,\n gear: 1,\n engineOn: true,\n bogged: false,\n fuel: spec.tank.capacity,\n loads: new Array<number>(n).fill((baseMass * G) / n),\n slip: new Array<number>(n).fill(0),\n steerAngle: 0,\n }\n const driver: SemiDriver = {\n spec,\n state,\n condition: {},\n setCargo(kg) {\n cargo = Math.max(0, kg)\n },\n contaminate(surfaceId, seconds) {\n contamination = { id: surfaceId, left: seconds }\n },\n refuel(litres) {\n state.fuel = Math.min(spec.tank.capacity, state.fuel + litres)\n },\n place(x, z, yaw) {\n state.x = x\n state.z = z\n state.yaw = yaw\n state.u = state.w = state.yawRate = 0\n },\n step(input, dt, world = {}) {\n const events: SemiEvent[] = []\n const steps = Math.max(1, Math.ceil(dt / MAX_SUBSTEP))\n const h = dt / steps\n for (let s = 0; s < steps; s++) substep(input, h, world, events)\n return { state, events }\n },\n }\n\n const stallWatch = { throttleTime: 0 }\n\n function substep(input: SemiInput, dt: number, world: SemiWorld, events: SemiEvent[]): void {\n const cond = driver.condition\n const mass = baseMass + cargo\n const engineHealth = clamp(cond.engine ?? 1, 0, 1)\n const suspensionHealth = clamp(cond.suspension ?? 1, 0, 1)\n const brakeHealth = clamp(cond.brakes ?? 1, 0, 1)\n const inertia = (spec.yawInertia ?? (baseMass * (wheelbase * wheelbase + track * track)) / 12) * (mass / baseMass)\n const pitchInertia = (mass * (wheelbase * wheelbase + 1)) / 12\n const rollInertia = (mass * (track * track + 1)) / 12\n if (contamination) {\n contamination.left -= dt\n if (contamination.left <= 0) contamination = null\n }\n const cs = Math.cos(state.yaw)\n const sn = Math.sin(state.yaw)\n // steering: the front wheels follow the input, slower when fast (the wheel angle limit shrinks a little)\n const target = clamp(input.steer, -1, 1) * spec.maxSteer\n state.steerAngle += (target - state.steerAngle) * Math.min(1, dt * 8)\n // gearbox: automatic by default. From a stop, the brake reverses and the throttle goes forward again.\n let gear = state.gear\n if (input.gear != null) gear = input.gear\n else if (state.u < 0.5 && input.brake > 0 && input.throttle <= 0) gear = -1\n else if (gear <= 0 && !(gear === -1 && state.u < 0.5 && input.throttle <= 0)) gear = 1\n const ratioOf = (g: number): number => (g < 0 ? spec.reverseRatio : g === 0 ? 0 : (spec.gears[g - 1] as number))\n const driveWheels = spec.wheels.map((w, i) => ({ w, i })).filter(({ w }) => (spec.fourWheelDrive ? true : w.drive))\n // the wheel speed that drives the engine: mean longitudinal speed of the driven wheels / radius\n let driveSpeed = 0\n for (const { w } of driveWheels) driveSpeed += state.u + state.yawRate * w.z\n driveSpeed /= Math.max(1, driveWheels.length)\n const wheelRpm = (Math.abs(driveSpeed) / spec.wheelRadius) * (60 / (2 * Math.PI))\n if (input.gear == null && gear > 0) {\n if (wheelRpm * ratioOf(gear) * spec.finalDrive > spec.engine.redlineRpm * spec.upshiftFraction && gear < spec.gears.length) gear++\n else if (gear > 1 && wheelRpm * ratioOf(gear) * spec.finalDrive < spec.engine.redlineRpm * spec.downshiftFraction) gear--\n }\n if (gear !== state.gear) {\n state.gear = gear\n events.push({ type: 'shift', gear })\n }\n const reversing = state.gear < 0\n const accelInput = reversing ? input.brake : input.throttle\n const brakeInput = clamp(reversing ? input.throttle : input.brake, 0, 1)\n const ratio = ratioOf(state.gear) * spec.finalDrive\n // the clutch: pressed it frees the engine from the wheels; released in gear below about half the idle it drags the engine down\n const engaged = input.clutch == null || state.gear === 0 ? 1 : 1 - clamp(input.clutch, 0, 1)\n const coupled = wheelRpm * ratio\n const free = spec.engine.idleRpm + clamp(accelInput, 0, 1) * (spec.engine.redlineRpm * 0.7 - spec.engine.idleRpm)\n state.rpm = clamp(coupled * engaged + Math.max(coupled, free) * (1 - engaged), spec.engine.idleRpm, spec.engine.redlineRpm + 200)\n if (input.clutch != null && state.gear !== 0 && state.engineOn && engaged > CLUTCH_BITE && coupled < spec.engine.idleRpm * STALL_RPM && accelInput < STALL_GAS) {\n state.engineOn = false\n events.push({ type: 'stall' })\n }\n if (!state.engineOn || state.fuel <= 0) state.rpm = 0\n // engine torque: a wrecked engine fails to deliver at full throttle, and under 30% it can die uphill\n let throttle = clamp(accelInput, 0, 1)\n if (engineHealth < STALL_HEALTH && throttle > 0.8) {\n stallWatch.throttleTime += dt\n if (state.pitch > 0.06 && stallWatch.throttleTime > 0.5 && state.engineOn) {\n state.engineOn = false\n events.push({ type: 'stall' })\n }\n throttle *= 0.5\n } else stallWatch.throttleTime = 0\n const starting = input.start ?? (accelInput > 0 && Math.abs(state.u) < 0.5)\n if (!state.engineOn && starting && engineHealth >= STALL_HEALTH && state.fuel > 0) state.engineOn = true\n if (state.fuel <= 0 && state.engineOn) {\n state.engineOn = false\n events.push({ type: 'out_of_fuel' })\n }\n const engineTorque = state.engineOn ? torqueAt(spec, state.rpm) * throttle * (0.55 + 0.45 * engineHealth) * clamp(input.powerLimit ?? 1, 0, 1) * engaged : 0\n const driveForceTotal = state.gear === 0 ? 0 : ((reversing ? -1 : 1) * engineTorque * ratio * spec.efficiency) / spec.wheelRadius\n // fuel\n if (state.engineOn) {\n const burned = fuelRate(fuelModel, state.rpm / spec.engine.redlineRpm, throttle, cargo / baseMass, engineHealth) * dt\n state.fuel = Math.max(0, state.fuel - burned)\n }\n\n // ground under each wheel, and the suspension\n const ride = spec.suspension.restLength\n let sumN = 0\n let sumNA = 0\n let sumNB = 0\n const wheelState: Array<{ n: number; grip: number; surface: string; bog: boolean; flat: boolean; rim: boolean }> = []\n let bogging = false\n for (let i = 0; i < n; i++) {\n const w = spec.wheels[i] as (typeof spec.wheels)[number]\n const wx = state.x + w.x * cs + w.z * sn\n const wz = state.z - w.x * sn + w.z * cs\n const ground = world.ground ? world.ground(wx, wz) : {}\n const surface = surfaces.get(contamination && contamination.left > 0 && surfaces.get(contamination.id).grip < surfaces.get(ground.surface ?? 'dry_asphalt').grip ? contamination.id : (ground.surface ?? 'dry_asphalt'))\n const tyreHealth = cond.tyres ? clamp(cond.tyres[i] ?? 1, 0, 1) : 1\n const rim = !!cond.rims?.[i]\n const flat = rim || tyreHealth < FLAT_BELOW\n const radius = rim ? (spec.rimRadius ?? spec.wheelRadius * RIM_RADIUS_SHARE) : flat ? spec.wheelRadius - FLAT_SAG : spec.wheelRadius\n const top = state.height + w.x * state.pitch - w.z * state.roll\n const length = top - (ground.height ?? 0) - radius\n const compression = ride - length\n const rate = -(state.heightRate + w.x * state.pitchRate - w.z * state.rollRate)\n const k = spec.suspension.spring * (0.5 + 0.5 * suspensionHealth)\n const c = spec.suspension.damper * (0.5 + 0.5 * suspensionHealth)\n const load = Math.max(0, k * compression + c * rate)\n const bog = !!surface.bogs && !spec.fourWheelDrive\n if (bog) bogging = true\n const grip = surfaceGrip(surface, state.u) * (rim ? RIM_FRICTION / spec.tyre.friction : flat ? 0.5 : 1)\n wheelState.push({ n: load, grip, surface: surface.id, bog, flat, rim })\n sumN += load\n sumNA += load * w.x\n sumNB += load * w.z\n }\n // brakes fade as they heat up from hard stops, and cool down in the air\n const brakeHeat = state.brakeHeat ?? AMBIENT_C\n const fade = 1 - clamp((brakeHeat - BRAKE_FADE_FROM_C) / (BRAKE_FADE_TO_C - BRAKE_FADE_FROM_C), 0, 1) * (1 - BRAKE_FADED)\n let brakeWork = 0\n // forces on the ground, per wheel\n let fFwd = 0\n let fRight = 0\n let torque = 0\n let pitchTorque = 0\n let rollTorque = 0\n const handbrake = !!input.handbrake\n const loadSum = Math.max(1, wheelState.reduce((a, b) => a + b.n, 0))\n const drivenCount = Math.max(1, driveWheels.length)\n for (let i = 0; i < n; i++) {\n const w = spec.wheels[i] as (typeof spec.wheels)[number]\n const ws = wheelState[i] as (typeof wheelState)[number]\n const delta = w.steer ? state.steerAngle : 0\n const cd = Math.cos(delta)\n const sd = Math.sin(delta)\n const vxw = state.u + state.yawRate * w.z\n const vyw = state.w - state.yawRate * w.x\n const vl = vxw * cd - vyw * sd\n const vc = vxw * sd + vyw * cd\n const capacity = spec.tyre.friction * ws.grip * ws.n\n // longitudinal request: drive, brake, rolling and handbrake lock\n let fl = 0\n if (driveWheels.some((d) => d.i === i)) fl += driveForceTotal / drivenCount\n const locked = handbrake && w.handbrake\n const brakeShare = (spec.brakeForce * brakeHealth * fade * brakeInput * ws.n) / loadSum\n const moving = Math.abs(vl) > 0.05\n // without ABS a brake asking more than the tyre holds locks the wheel: it slides on less grip and steers no more\n const lockedByBrake = spec.abs === false && moving && brakeShare > capacity\n if (locked || lockedByBrake) fl += moving ? -Math.sign(vl) * capacity * (lockedByBrake ? SLIDING_GRIP : 1) : 0\n else if (brakeShare > 0 && moving) fl += -Math.sign(vl) * brakeShare\n if (brakeShare > 0 && moving) brakeWork += Math.min(brakeShare, capacity) * Math.abs(vl) * dt\n const rolling = ws.bog && accelInput > 0 ? spec.bogResistance : ws.rim ? RIM_ROLLING : spec.rolling * (ws.flat ? FLAT_ROLLING : 1)\n // lateral: slip angle into a saturating curve, separate from the longitudinal one\n const alpha = Math.atan2(vc, Math.abs(vl) + 0.5)\n let fc = -Math.tanh((spec.tyre.corneringStiffness * alpha)) * capacity\n if (locked) fc *= 0.6\n if (lockedByBrake) fc *= LOCKED_STEER\n // friction circle\n const total = Math.hypot(fl, fc)\n let used = 1\n if (total > capacity && total > 0) used = capacity / total\n fl *= used\n fc *= used\n // rolling resistance is the ground's, not the tyre's: it is not limited by the friction circle\n if (moving) fl += -Math.sign(vl) * rolling * ws.n\n const slipRatio = capacity > 0 ? clamp(total / capacity, 0, 1) : 0\n state.slip[i] = slipRatio\n if (ws.surface === 'wet_asphalt' && Math.abs(state.u) * 3.6 > (surfaces.get(ws.surface).aquaplaningKmh ?? 1e9) && slipRatio >= 0.99) events.push({ type: 'aquaplaning', wheel: i })\n // to the body\n const fx = fl * cd + fc * sd\n const fy = -fl * sd + fc * cd\n fFwd += fx\n fRight += fy\n torque += w.z * fx - w.x * fy\n pitchTorque += fx * spec.centreHeight\n rollTorque += -fy * spec.centreHeight\n }\n const bogNow = bogging && Math.abs(state.u) < 1 && accelInput > 0\n if (bogNow && !state.bogged) events.push({ type: 'bogged' })\n state.bogged = bogNow\n state.brakeHeat = brakeHeat + brakeWork / (baseMass * BRAKE_HEAT_CAPACITY) - (brakeHeat - AMBIENT_C) * Math.min(1, dt / BRAKE_COOL_S)\n // air drag\n fFwd += -spec.drag * state.u * Math.abs(state.u)\n fRight += -spec.drag * state.w * Math.abs(state.w)\n // planar integration in the body frame\n const du = fFwd / mass - state.yawRate * state.w\n const dw = fRight / mass + state.yawRate * state.u\n state.u += du * dt\n state.w += dw * dt\n // a stopped vehicle does not creep: the sticking friction holds it\n if (Math.abs(state.u) < 0.02 && accelInput <= 0) state.u = 0\n state.yawRate += (torque / inertia) * dt\n state.yaw += state.yawRate * dt\n const csn = Math.cos(state.yaw)\n const snn = Math.sin(state.yaw)\n state.x += (state.u * csn + state.w * snn) * dt\n state.z += (-state.u * snn + state.w * csn) * dt\n // vertical, pitch and roll from the wheel loads\n const ay = (sumN - mass * G) / mass\n state.heightRate += ay * dt\n state.height += state.heightRate * dt\n state.pitchRate += ((sumNA + pitchTorque) / pitchInertia) * dt\n state.pitch += state.pitchRate * dt\n state.rollRate += ((-sumNB + rollTorque) / rollInertia) * dt\n state.roll += state.rollRate * dt\n for (let i = 0; i < n; i++) state.loads[i] = (wheelState[i] as (typeof wheelState)[number]).n\n }\n\n return driver\n}\n","/** Kinetic energy of a vehicle against a body: `0.5 * mass * speed²` (joules, with kg and m/s). Frota document, section 08. */\nexport const impactEnergy = (vehicleMass: number, relativeSpeed: number): number => 0.5 * vehicleMass * relativeSpeed * relativeSpeed\n\n/** Damage to the body that was hit: `energy * bumperMultiplier * zoneFactor`. The zone factors (head, torso, legs) belong to the game. */\nexport const bodyDamage = (energy: number, bumperMultiplier: number, zoneFactor: number): number => energy * bumperMultiplier * zoneFactor\n\n/** Damage to the vehicle: `energy * 0.04 * (1 - frontArmor)`, with the armour from 0 to 1. */\nexport const vehicleDamageFromImpact = (energy: number, frontArmor: number, factor = 0.04): number => energy * factor * (1 - frontArmor)\n\n/** Speed the vehicle loses: `bodyMass / (vehicleMass + bodyMass) * speed`. */\nexport const speedLoss = (bodyMass: number, vehicleMass: number, speed: number): number => (bodyMass / (vehicleMass + bodyMass)) * speed\n","import type { SemiPedal, SemiSimSpec, SemiTracks, SemiWheel } from './types'\n\n/** What a vehicle is built as: the wheels it has, the engine and gearbox it carries, how it is driven. A car when a body says nothing. */\nexport type VehicleType = 'car' | 'motorcycle' | 'bicycle' | 'truck' | 'tractor' | 'tracked'\n\n/** One axle as the model has it: metres ahead of the middle of the vehicle, the distance between its outer wheels (0 for a single wheel) and the radius of its tyres. */\nexport interface AxleDimensions {\n readonly x: number\n readonly track: number\n readonly radius: number\n}\n\n/** The tracks as the model has them (x ahead of the middle of the vehicle). */\nexport interface TrackDimensions {\n readonly gauge: number\n readonly rearX: number\n readonly frontX: number\n readonly roadWheels: number\n readonly radius: number\n}\n\n/** A cyclist sustains this much: the middle of the 150-400 W range of design 14.2 (specs/008-motor-fisico-jolt/design/veiculos.md), at the cadence and with the gears of the T6.2 bicycle test. */\nexport const CYCLIST: SemiPedal = { watts: 250, cadenceRpm: 80, gears: [1.5, 2.5, 3.5] }\n\n/** The engine and gearbox a type carries (five gears at most: the physics engine's automatic gearbox stops upshifting with six, measured on the scooter in specs/008 evidence T6.2c): the speeds the engine turns at, the gears below the top one (the top gear is set by the top speed) and the final drive. */\nexport interface TypeDrivetrain {\n readonly engine: Pick<SemiSimSpec['engine'], 'idleRpm' | 'peakRpm' | 'redlineRpm'>\n readonly gears: readonly number[]\n readonly finalDrive: number\n readonly efficiency: number\n /** The ratio between neighbouring gears from the top gear down: the steps of the box. */\n readonly step: number\n /** Share of the redline the engine turns at in the top gear at the top speed: the rest is headroom for the tyre's slip (a slipping wheel spins the engine past the limiter). */\n readonly topShare: number\n /** Shifts, shares of the redline. */\n readonly upshift: number\n readonly downshift: number\n}\n\nconst MOTORCYCLE: TypeDrivetrain = { engine: { idleRpm: 1300, peakRpm: 7500, redlineRpm: 10000 }, gears: [2.8, 2.0, 1.5, 1.2, 1.0], finalDrive: 3, efficiency: 0.9, step: 1.25, topShare: 0.8, upshift: 0.6, downshift: 0.3 }\nconst TRUCK: TypeDrivetrain = { engine: { idleRpm: 600, peakRpm: 1500, redlineRpm: 2500 }, gears: [7, 4.7, 3.2, 2.2, 1.5], finalDrive: 4.5, efficiency: 0.85, step: 1.5, topShare: 0.95, upshift: 0.85, downshift: 0.35 }\nconst TRACTOR: TypeDrivetrain = { engine: { idleRpm: 800, peakRpm: 1600, redlineRpm: 2300 }, gears: [7, 4.7, 3.2, 2.2, 1.5], finalDrive: 4.5, efficiency: 0.85, step: 1.5, topShare: 0.95, upshift: 0.85, downshift: 0.35 }\nconst TRACKED: TypeDrivetrain = { engine: { idleRpm: 600, peakRpm: 1500, redlineRpm: 2500 }, gears: [7, 4.7, 3.2, 2.2, 1.5], finalDrive: 4.5, efficiency: 0.85, step: 1.5, topShare: 0.95, upshift: 0.85, downshift: 0.35 }\n\n/** The drivetrain of a type; undefined for a car (the semi-simulation's own defaults) and a bicycle (the cyclist). */\nexport const drivetrainOfType = (type: VehicleType): TypeDrivetrain | undefined => {\n if (type === 'motorcycle') return MOTORCYCLE\n if (type === 'truck') return TRUCK\n if (type === 'tractor') return TRACTOR\n if (type === 'tracked') return TRACKED\n return undefined\n}\n\n/** A two-wheeler has no track: a single wheel on the centre line per axle. */\nexport const isTwoWheeler = (type: VehicleType): boolean => type === 'motorcycle' || type === 'bicycle'\n\nexport interface WheelPlanParams {\n readonly axles: readonly AxleDimensions[]\n readonly fourWheelDrive: boolean\n readonly twoWheeler: boolean\n}\n\n/** The wheels of a vehicle from its axles (front first): the front axle steers, the others drive unless all do, and the last one holds the handbrake. A bike drives its rear wheel only. */\nexport const wheelsOfAxles = ({ axles, fourWheelDrive, twoWheeler }: WheelPlanParams): SemiWheel[] => {\n const front = axles[0]!.x\n const rear = axles[axles.length - 1]!.x\n const middle = (front + rear) / 2\n return axles.flatMap((axle, index): SemiWheel[] => {\n const isFront = index === 0\n const isRear = index === axles.length - 1\n const common = { x: axle.x - middle, ...(isFront ? { steer: true } : {}), ...(isRear ? { handbrake: true } : {}) }\n const drive = twoWheeler ? isRear : fourWheelDrive || !isFront\n const wheel = (z: number): SemiWheel => ({ ...common, z, ...(drive ? { drive: true } : {}) })\n return axle.track > 0 ? [wheel(-axle.track / 2), wheel(axle.track / 2)] : [wheel(0)]\n })\n}\n\n/** The four-wheel stand-in of a tracked vehicle for the semi-simulation: two wheels a side at the ends of the track, the front pair steering. */\nexport const trackStandIn = (tracks: SemiTracks): SemiWheel[] => {\n const side = tracks.gauge / 2\n return [\n { x: tracks.frontX, z: -side, steer: true, drive: true },\n { x: tracks.frontX, z: side, steer: true, drive: true },\n { x: tracks.rearX, z: -side, drive: true, handbrake: true },\n { x: tracks.rearX, z: side, drive: true, handbrake: true },\n ]\n}\n\n/** The tracks of a body re-centred on the middle of the track run. */\nexport const tracksOfBody = (tracks: TrackDimensions): SemiTracks => {\n const middle = (tracks.frontX + tracks.rearX) / 2\n return { gauge: tracks.gauge, rearX: tracks.rearX - middle, frontX: tracks.frontX - middle, roadWheels: tracks.roadWheels, roadRadius: tracks.radius }\n}\n","import { defaultSemiSpec, torqueAt } from './driver'\nimport type { SemiPedal, SemiSimSpec } from './types'\nimport { CYCLIST, drivetrainOfType, isTwoWheeler, trackStandIn, tracksOfBody, wheelsOfAxles } from './vehicle-type'\nimport type { AxleDimensions, TrackDimensions, VehicleType } from './vehicle-type'\n\n/** The design ratings of a vehicle (the shape of `fleetStats` in `game-vehicles-fleet`; any object with these fields works). */\nexport interface DesignStats {\n /** 0-10. */\n acceleration: number\n /** 0-10. */\n handling: number\n maxSpeedKmh: number\n}\n\nexport interface BodyDimensions {\n mass: number\n wheelbase: number\n track: number\n fourWheelDrive?: boolean\n /** What it is built as (a car when omitted): the wheels, the engine, the gearbox and the controller come from the type. */\n type?: VehicleType\n /** The axles of the model, front first. Without them the vehicle has two, from `wheelbase` and `track` (a single wheel each for a two-wheeler). */\n axles?: readonly AxleDimensions[]\n /** A tracked vehicle's tracks. */\n tracks?: TrackDimensions\n}\n\n/** A motorcycle is simulated with its rider on (the real 0-100 km/h figures are measured with one): the mass of a rider, an assumption of the spec. */\nexport const RIDER_MASS_KG = 75\n\n/**\n * Power per kg of bike and rider by acceleration rating: the real power-to-weight of the two bikes that anchor the 0-100 km/h band of the class (`accelerationByClass.motorcycles`),\n * rating 1 the Honda PCX 160 (11.8 kW at 8 500 rpm, 132 kg: https://zigwheels.com/honda-bikes/pcx150/specifications) and rating 10 the Kawasaki Ninja 400 (33.4 kW at 10 000 rpm, 168 kg:\n * https://www.motorcyclespecs.co.za/model/kawasaki/kawasaki_ninja_400_21.html), linear in between.\n */\n/** Fitted: with the real power to weight alone the physics engine's bikes take 8.6 to 8.9 s to 100 km/h at rating 9 against the 3.9-8.1 s band; 1.3 puts all ten models inside the band (evidence T6.2c). */\nconst MOTORCYCLE_POWER_FACTOR = 1.3\nconst MOTORCYCLE_POWER_RATING_1 = 11800 / (132 + RIDER_MASS_KG)\nconst MOTORCYCLE_POWER_RATING_10 = 33400 / (168 + RIDER_MASS_KG)\nconst motorcyclePower = (rating: number): number => MOTORCYCLE_POWER_FACTOR * (MOTORCYCLE_POWER_RATING_1 + ((MOTORCYCLE_POWER_RATING_10 - MOTORCYCLE_POWER_RATING_1) * (rating - 1)) / 9)\n\n/** The default engine's power per kg at a rating: its torque per kg times its peak speed (unchanged for a car). */\nconst carPower = (rating: number): number => (0.06 + 0.015 * rating) * ((defaultSemiSpec.engine.peakRpm * 2 * Math.PI) / 60)\n\nconst peakTorqueOf = (type: VehicleType, rating: number, mass: number, peakRpm: number): number => {\n const power = type === 'motorcycle' ? motorcyclePower(rating) : carPower(rating)\n return (mass * power * 60) / (2 * Math.PI * peakRpm)\n}\n\n/** The cyclist with a bicycle geared so that the top gear turns the cranks at his cadence at the top speed, the lower ones a step of 1.4 apart (wheel turns per crank turn). */\nconst cyclistFor = (top: number, wheelRadius: number): SemiPedal => {\n const topGear = top / (2 * Math.PI * wheelRadius) / (CYCLIST.cadenceRpm / 60)\n return { ...CYCLIST, gears: [topGear / 1.4 ** 2, topGear / 1.4, topGear] }\n}\n\nconst axlesOfBody = (body: BodyDimensions, twoWheeler: boolean): readonly AxleDimensions[] =>\n body.axles ?? [{ x: body.wheelbase / 2, track: twoWheeler ? 0 : body.track, radius: defaultSemiSpec.wheelRadius }, { x: -body.wheelbase / 2, track: twoWheeler ? 0 : body.track, radius: defaultSemiSpec.wheelRadius }]\n\n/** The radius the engine turns: the driven axles' tyres (every axle's when all drive, the rear one's on a bike). */\nconst drivenRadius = (axles: readonly AxleDimensions[], driveAll: boolean, twoWheeler: boolean): number => {\n const driven = twoWheeler ? axles.slice(-1) : driveAll ? axles : axles.slice(1)\n return driven.reduce((sum, axle) => sum + axle.radius, 0) / driven.length\n}\n\n/**\n * A semi-simulation spec from the design ratings and the body: the grip follows the handling, the torque follows the acceleration (a motorcycle's from its real power to weight), the air drag\n * is set so that the top gear tops out at the design top speed (a bicycle's from the cyclist's watts), and the brake force follows the mass. The `type` sets the wheels (two for a bike, one\n * pair per axle for the rest, the model's own when `axles` is given), the engine and the gearbox, and a tracked vehicle gets its tracks.\n */\nexport function semiSpecFromStats(stats: DesignStats, body: BodyDimensions, base: Partial<SemiSimSpec> = {}): SemiSimSpec {\n const type = body.type ?? 'car'\n const mass = body.mass + (type === 'motorcycle' ? RIDER_MASS_KG : 0)\n const twoWheeler = isTwoWheeler(type)\n const drivetrain = drivetrainOfType(type)\n const tracks = type === 'tracked' && body.tracks ? tracksOfBody(body.tracks) : undefined\n const axles = axlesOfBody(body, twoWheeler)\n const driveAll = !!body.fourWheelDrive\n const wheelRadius = tracks?.roadRadius ?? drivenRadius(axles, driveAll, twoWheeler)\n const spec: SemiSimSpec = {\n ...defaultSemiSpec,\n ...(drivetrain ? { engine: { ...defaultSemiSpec.engine, ...drivetrain.engine }, gears: drivetrain.gears, finalDrive: drivetrain.finalDrive, efficiency: drivetrain.efficiency, upshiftFraction: drivetrain.upshift, downshiftFraction: drivetrain.downshift } : {}),\n ...(type === 'bicycle' ? { finalDrive: 1, efficiency: 0.95 } : {}),\n wheelRadius,\n centreHeight: twoWheeler ? 0.6 : Math.max(defaultSemiSpec.centreHeight, wheelRadius + 0.1),\n ...base,\n }\n const wheels = tracks ? trackStandIn(tracks) : wheelsOfAxles({ axles, fourWheelDrive: driveAll, twoWheeler })\n const pedal = type === 'bicycle' ? cyclistFor(stats.maxSpeedKmh / 3.6, wheelRadius) : undefined\n const peakTorque = pedal ? (pedal.watts * 60) / (2 * Math.PI * pedal.cadenceRpm) : peakTorqueOf(type, stats.acceleration, mass, spec.engine.peakRpm)\n const engine = pedal ? { idleRpm: 40, peakRpm: pedal.cadenceRpm, redlineRpm: pedal.cadenceRpm * 1.5, peakTorque } : { ...spec.engine, peakTorque }\n const top = stats.maxSpeedKmh / 3.6\n // the last gear puts the redline at the top speed\n const topShare = drivetrain?.topShare ?? 0.95\n const lastRatio = (engine.redlineRpm * topShare * 2 * Math.PI * spec.wheelRadius) / (60 * top * spec.finalDrive)\n const stack = drivetrain?.gears ?? spec.gears\n const step = drivetrain?.step ?? 1.25\n const gears = pedal ? pedal.gears.map((ratio) => 1 / ratio) : [...stack.slice(0, -1).map((g, i, all) => Math.max(g, lastRatio * step ** (all.length - i))), lastRatio]\n // a car keeps the 0.76 of its first calibration; the other types use the torque their own curve gives at the speed the last gear puts the redline at\n const torqueAtTop = type === 'car' ? peakTorque * 0.76 : torqueAt({ ...spec, engine }, engine.redlineRpm * topShare)\n const topRatio = pedal ? gears[gears.length - 1]! : lastRatio\n // a cyclist's thrust at the top speed is the sustained power over the speed; an engine's is its torque there through the last gear\n const thrust = pedal ? (pedal.watts * spec.efficiency) / top : (torqueAtTop * topRatio * spec.finalDrive * spec.efficiency) / spec.wheelRadius\n const rollingForce = spec.rolling * mass * 9.81\n const drag = Math.max(0.01, (thrust - rollingForce) / (top * top))\n // the brakes grow with the mass, so a bus is not stopped by a hatch's brakes: the default car's ratio (about 1.1 g) up to 2 t, easing to the 0.6 g of a loaded truck or bus at 10 t (the tyres still cap it)\n const carRatio = defaultSemiSpec.brakeForce / (defaultSemiSpec.mass * 9.81)\n const heavyShare = Math.max(0, Math.min(1, (mass - 2000) / 8000))\n const brakeForce = base.brakeForce ?? mass * 9.81 * (carRatio + (0.6 - carRatio) * heavyShare)\n return {\n ...spec,\n mass,\n wheels,\n fourWheelDrive: driveAll,\n engine,\n gears,\n drag,\n brakeForce,\n tyre: { ...spec.tyre, friction: 0.8 + 0.03 * stats.handling },\n ...(pedal ? { pedal } : {}),\n ...(tracks ? { tracks } : {}),\n }\n}\n","/**\n * The driver aids the controls apply between the pedals and the engine: the drive profile (economy shifts early and softens the gas, sport holds the\n * gears and sharpens it), traction control (cuts the torque while a driven wheel spins past its grip) and cruise control (holds the set speed with the\n * gas; the brake or the clutch cancels it, the gas pedal overrides it while pressed). Pure functions over numbers, every threshold an option.\n */\nexport type DriveProfile = 'eco' | 'normal' | 'sport'\n\nexport interface ProfileTuning {\n /** Multiplies the gas pedal. */\n readonly throttle: number\n /** Upshift and downshift points, shares of the redline (the semi driver's `upshiftFraction` and `downshiftFraction`). */\n readonly upshift: number\n readonly downshift: number\n}\n\nexport const DRIVE_PROFILES: Readonly<Record<DriveProfile, ProfileTuning>> = {\n eco: { throttle: 0.7, upshift: 0.55, downshift: 0.25 },\n normal: { throttle: 1, upshift: 0.85, downshift: 0.35 },\n sport: { throttle: 1, upshift: 0.97, downshift: 0.55 },\n}\n\nexport interface TractionOptions {\n /** Grip in use of a driven wheel (1 = sliding) above which the torque is cut. */\n readonly slip: number\n /** Torque left at full spin. */\n readonly floor: number\n}\n\nexport const DEFAULT_TRACTION: TractionOptions = { slip: 0.97, floor: 0.35 }\n\n/** Share of the torque traction control lets through for the worst driven wheel's grip in use (1 = sliding). */\nexport function tractionLimit(slips: readonly number[], options: TractionOptions = DEFAULT_TRACTION): number {\n const worst = Math.max(0, ...slips)\n if (worst <= options.slip) return 1\n return Math.max(options.floor, 1 - (worst - options.slip) / (1 - options.slip))\n}\n\nexport interface CruiseOptions {\n /** Gas per m/s under the set speed. */\n readonly gain: number\n /** Lowest speed it engages at, m/s (about 30 km/h). */\n readonly minSpeed: number\n}\n\nexport const DEFAULT_CRUISE: CruiseOptions = { gain: 0.35, minSpeed: 8.3 }\n\n/** Gas cruise control asks for to hold `target` at `speed` (m/s); none above the target, the car coasts down to it. */\nexport function cruiseThrottle(target: number, speed: number, options: CruiseOptions = DEFAULT_CRUISE): number {\n return Math.max(0, Math.min(1, (target - speed) * options.gain + 0.12))\n}\n","/**\n * The controls of a vehicle someone drives: pedals (the clutch too), wheel, gearbox (automatic or manual), handbrake (held or pulled), ignition and\n * starter, drive mode (4x2, 4x4, automatic 4x4), drive profile (eco, normal, sport), traction control, ABS, cruise control, lamps (position, low,\n * high, flash, fog, interior), wipers and washer, climate and demister, horn, alarm and radio, the hotwire of a car without its key (the ignition key held\n * strips and joins the wires under the column), the siren and the beacon of an emergency vehicle, and the glovebox lid. It turns key codes into a `SemiInput` for the semi driver and keeps\n * what the cabin shows; it draws and plays nothing (an adapter reads `state` for the lamps and the sounds). Every key is an option.\n */\nimport { cruiseThrottle, DEFAULT_CRUISE, DRIVE_PROFILES, tractionLimit } from './driving-aids'\nimport type { DriveProfile } from './driving-aids'\nimport type { SemiInput } from './semi/types'\n\nexport type ControlCommand =\n | 'ignition'\n | 'gearbox'\n | 'gear_up'\n | 'gear_down'\n | 'parking_brake'\n | 'drive_mode'\n | 'lights'\n | 'high_beam'\n | 'fog_lights'\n | 'interior_light'\n | 'alarm'\n | 'radio'\n | 'radio_source'\n | 'radio_track'\n | 'exit'\n | 'indicator_left'\n | 'indicator_right'\n | 'hazard'\n | 'wipers'\n | 'seatbelt'\n | 'drive_profile'\n | 'traction_control'\n | 'abs'\n | 'cruise'\n | 'climate'\n | 'demist'\n | 'siren'\n | 'beacon'\n | 'glovebox'\n\nexport type ControlKeyMap = {\n readonly throttle: readonly string[]\n readonly brake: readonly string[]\n readonly left: readonly string[]\n readonly right: readonly string[]\n readonly handbrake: readonly string[]\n readonly horn: readonly string[]\n readonly clutch: readonly string[]\n /** Flashes the high beam while held. */\n readonly flash: readonly string[]\n readonly washer: readonly string[]\n /** Held without the key (`hasKey: false`): strips and joins the wires under the column until the engine turns over. */\n readonly hotwire: readonly string[]\n} & { readonly [command in ControlCommand]: readonly string[] }\n\n/** Keys of a keyboard (`KeyboardEvent.code`). The host keeps them from its own bindings while someone drives. */\nexport const DEFAULT_CONTROL_KEYS: ControlKeyMap = {\n throttle: ['KeyW', 'ArrowUp'],\n brake: ['KeyS', 'ArrowDown'],\n left: ['KeyA', 'ArrowLeft'],\n right: ['KeyD', 'ArrowRight'],\n handbrake: ['Space'],\n horn: ['KeyH'],\n clutch: ['KeyC'],\n flash: ['KeyX'],\n washer: ['KeyZ'],\n hotwire: ['KeyI'],\n ignition: ['KeyI'],\n gearbox: ['KeyM'],\n gear_up: ['KeyE'],\n gear_down: ['KeyQ'],\n parking_brake: ['KeyP'],\n drive_mode: ['KeyG'],\n lights: ['KeyL'],\n high_beam: ['KeyK'],\n fog_lights: ['KeyN'],\n interior_light: ['KeyU'],\n alarm: ['KeyY'],\n radio: ['KeyR'],\n radio_source: ['KeyT'],\n radio_track: ['BracketRight'],\n exit: ['KeyF'],\n indicator_left: ['Comma'],\n indicator_right: ['Period'],\n hazard: ['KeyB'],\n wipers: ['KeyO'],\n seatbelt: ['KeyJ'],\n drive_profile: ['Digit7'],\n traction_control: ['Digit8'],\n abs: ['Digit9'],\n cruise: ['Digit0'],\n climate: ['Minus'],\n demist: ['Equal'],\n siren: ['Semicolon'],\n beacon: ['Quote'],\n glovebox: ['Slash'],\n}\nconst HELD_KEYS = ['throttle', 'brake', 'left', 'right', 'handbrake', 'horn', 'clutch', 'flash', 'washer', 'hotwire']\n\nexport type Gearbox = 'automatic' | 'manual'\nexport type DriveMode = '4x2' | '4x4' | 'auto'\nexport type LampMode = 'off' | 'position' | 'low' | 'high'\nexport type AlarmState = 'off' | 'armed' | 'ringing'\nexport type RadioSource = 'radio' | 'tape'\nexport type Indicator = 'off' | 'left' | 'right' | 'hazard'\nexport type Wipers = 'off' | 'intermittent' | 'slow' | 'fast'\n/** The siren's tone: the slow rise and fall, or the fast warble of a junction. */\nexport type Siren = 'off' | 'wail' | 'yelp'\n\nexport interface ControlState {\n ignition: boolean\n gearbox: Gearbox\n /** The gear the driver chose (manual): -1 reverse, 0 neutral, 1.. forward. */\n gear: number\n /** Pulled and left pulled (P); Space holds it only while pressed. */\n parkingBrake: boolean\n driveMode: DriveMode\n /** The front axle drives now (4x4, or automatic 4x4 that felt the rear slip). */\n fourWheelEngaged: boolean\n /** `flash`: the high beam lit while the flash key is held, over any mode. */\n lamps: { mode: LampMode; fog: boolean; interior: boolean; flash: boolean }\n /** What the rear lamps show this step: brake (pedal or handbrake) and reversing. */\n brakeLights: boolean\n reverseLights: boolean\n horn: boolean\n alarm: AlarmState\n /** `track`: the station or the song on the tape, 0-based (`radioTracks` of them). */\n radio: { on: boolean; source: RadioSource; track: number }\n indicator: Indicator\n /** The indicator lamps are lit this instant (they blink at `blinkHz`); `tick` is true on the step the relay clicks. */\n blinkOn: boolean\n tick: boolean\n wipers: Wipers\n /** The washer squirts while its key is held (the wipers sweep with it). */\n washer: boolean\n seatbelt: boolean\n /** Clutch pedal, 0 up to 1 down (manual gearbox). */\n clutch: number\n profile: DriveProfile\n tractionControl: boolean\n abs: boolean\n /** Cruise control: the speed it holds, m/s. */\n cruise: { on: boolean; speed: number }\n climate: { on: boolean; demist: boolean }\n /** The starter turns this step. */\n cranking: boolean\n /** Without the key: how far the wires under the column are (0 untouched, 1 joined: the ignition is live), and whether they are joined now. */\n hotwire: { progress: number; done: boolean }\n siren: Siren\n /** The beacon (light bar) is on, and which of its two sides is lit this instant (it alternates at `beaconHz`). */\n beacon: boolean\n beaconSide: 0 | 1\n /** The glovebox lid is open. */\n glovebox: boolean\n}\n\nexport type ControlEvent =\n | { type: 'command'; command: ControlCommand; state: ControlState }\n | { type: 'refused'; command: ControlCommand; reason: 'no_four_wheel_drive' | 'no_fog_lamps' | 'ignition_off' | 'battery_flat' | 'too_slow' | 'no_key' | 'no_siren' }\n | { type: 'cruise_cancelled' }\n /** The wires under the column: stripped (first touch), joined (the ignition is live and the starter turns). */\n | { type: 'hotwire'; stage: 'started' | 'joined' }\n\nexport interface VehicleControlOptions {\n /** Forward gears of the gearbox. */\n gears: number\n /** The vehicle can drive both axles (4x4 and automatic 4x4 are offered). */\n fourWheelDrive?: boolean\n /** The vehicle has fog lamps. Default true. */\n fogLamps?: boolean\n keys?: Partial<ControlKeyMap>\n gearbox?: Gearbox\n /** Automatic 4x4: the front axle comes in above this slip of a driven wheel (1 = sliding) and goes out after `releaseSeconds` below it. */\n autoFourWheel?: { slip: number; releaseSeconds: number }\n /** The engine runs from the start (a vehicle the player gets into with the engine on). Default false: the key turns it on (I) or the gas pedal starts it. */\n running?: boolean\n /** Blinks a second of the indicators (default 1.5, the 90 a minute of the road codes). */\n blinkHz?: number\n /** The steering wheel coming back this far (0..1 of the lock) after a turn cancels the indicator, as the column does. Default 0.15. */\n indicatorCancel?: number\n /** Stations or songs the radio steps through (`radio_track`). Default 3. */\n radioTracks?: number\n /** The driver works the clutch (C) in manual: released in gear too slowly or without gas, the engine stalls. Default false (the clutch is automated). */\n clutchPedal?: boolean\n /** The starter can turn the engine over (a battery with charge); asked at every crank. Default always. */\n canCrank?: () => boolean\n /** A crank happened (takes the battery's energy). */\n onCrank?: () => void\n /** Share of the torque the engine gives besides the aids (an overheated engine). Default 1. */\n powerLimit?: () => number\n /** The driver has the key. Default true. Without it the ignition refuses and the hotwire key (held) joins the wires. */\n hasKey?: boolean\n /** Seconds of the hotwire key held to strip and join the wires. Default 8. */\n hotwireSeconds?: number\n /** The vehicle has a siren and a beacon (an emergency vehicle). Default false: both refuse. */\n emergency?: boolean\n /** The beacon's sides swap this many times a second. Default 2.5. */\n beaconHz?: number\n onEvent?: (event: ControlEvent) => void\n}\n\n/** What the controls read of the driver each step, and the one thing they change on it (which axles drive). */\nexport interface ControlledDriver {\n readonly spec: { fourWheelDrive: boolean; abs?: boolean; upshiftFraction?: number; downshiftFraction?: number; readonly wheels?: ReadonlyArray<{ drive?: boolean }> }\n readonly state: { u: number; gear: number; slip: readonly number[]; engineOn: boolean }\n}\n\nexport interface VehicleControls {\n /** A key went down or up. True when it is a driving key (the host keeps it from its own bindings). */\n key(code: string, down: boolean): boolean\n /** Runs a command as its key would (a button of a panel). */\n command(command: ControlCommand): void\n /** The input for this step, pedals and wheel eased over `dt` seconds. */\n input(dt: number, driver?: ControlledDriver): SemiInput\n /** After the driver stepped: the automatic 4x4 watches the slip, the ignition the engine. */\n after(driver: ControlledDriver, dt: number): void\n readonly state: ControlState\n readonly keys: ControlKeyMap\n /** Lets go of every key (the window lost focus, the driver got out). */\n release(): void\n}\n\nexport function createVehicleControls(options: VehicleControlOptions): VehicleControls {\n const keys: ControlKeyMap = { ...DEFAULT_CONTROL_KEYS, ...options.keys }\n const auto4 = options.autoFourWheel ?? { slip: 0.18, releaseSeconds: 2 }\n const hasFog = options.fogLamps !== false\n const held = new Set<string>()\n const any = (codes: readonly string[]): boolean => codes.some((c) => held.has(c))\n const commandOf = new Map<string, ControlCommand>()\n for (const [command, codes] of Object.entries(keys)) if (!HELD_KEYS.includes(command)) for (const code of codes) commandOf.set(code, command as ControlCommand)\n const driving = new Set<string>(Object.values(keys).flat())\n\n const state: ControlState = {\n ignition: !!options.running,\n gearbox: options.gearbox ?? 'automatic',\n gear: 1,\n parkingBrake: false,\n driveMode: options.fourWheelDrive ? 'auto' : '4x2',\n fourWheelEngaged: false,\n lamps: { mode: 'off', fog: false, interior: false, flash: false },\n brakeLights: false,\n reverseLights: false,\n horn: false,\n alarm: 'off',\n radio: { on: false, source: 'radio', track: 0 },\n indicator: 'off',\n blinkOn: false,\n tick: false,\n wipers: 'off',\n washer: false,\n seatbelt: false,\n clutch: 0,\n profile: 'normal',\n tractionControl: true,\n abs: true,\n cruise: { on: false, speed: 0 },\n climate: { on: false, demist: false },\n cranking: false,\n hotwire: { progress: 0, done: false },\n siren: 'off',\n beacon: false,\n beaconSide: 0,\n glovebox: false,\n }\n const hasKey = options.hasKey !== false\n const hotwireSeconds = Math.max(0.1, options.hotwireSeconds ?? 8)\n const beaconHz = options.beaconHz ?? 2.5\n let beaconClock = 0\n let crankAsked = false\n let lastSpeed = 0\n let engineRunning = !!options.running\n const blinkHz = options.blinkHz ?? 1.5\n const cancelAt = options.indicatorCancel ?? 0.15\n let blink = 0\n let turned = 0\n let throttle = 0\n let brake = 0\n let steer = 0\n let calm = 0\n const emit = (event: ControlEvent): void => options.onEvent?.(event)\n const LAMPS: readonly LampMode[] = ['off', 'position', 'low']\n const MODES: readonly DriveMode[] = ['4x2', '4x4', 'auto']\n const WIPERS: readonly Wipers[] = ['off', 'intermittent', 'slow', 'fast']\n const PROFILES: readonly DriveProfile[] = ['eco', 'normal', 'sport']\n const SIRENS: readonly Siren[] = ['off', 'wail', 'yelp']\n\n const command = (c: ControlCommand): void => {\n switch (c) {\n case 'ignition':\n // without the key only the joined wires make the ignition live; pulled apart, they cut it, and joined again they make it live\n if (!hasKey && !state.hotwire.done) return emit({ type: 'refused', command: c, reason: 'no_key' })\n state.ignition = !state.ignition\n // the driver turning the key disarms the alarm and cranks; turning it off leaves the radio playing on the battery\n if (state.ignition && state.alarm !== 'off') state.alarm = 'off'\n if (state.ignition) crankAsked = true\n else state.cruise.on = false\n break\n case 'gearbox':\n state.gearbox = state.gearbox === 'automatic' ? 'manual' : 'automatic'\n // with a clutch to work, a manual starts in neutral (in gear with the clutch up it would stall at once)\n state.gear = options.clutchPedal && state.gearbox === 'manual' && Math.abs(lastSpeed) < 0.5 ? 0 : Math.max(1, state.gear)\n break\n case 'gear_up':\n case 'gear_down':\n if (state.gearbox !== 'manual') return\n state.gear = Math.max(-1, Math.min(options.gears, state.gear + (c === 'gear_up' ? 1 : -1)))\n break\n case 'parking_brake':\n state.parkingBrake = !state.parkingBrake\n break\n case 'drive_mode': {\n if (!options.fourWheelDrive) return emit({ type: 'refused', command: c, reason: 'no_four_wheel_drive' })\n state.driveMode = MODES[(MODES.indexOf(state.driveMode) + 1) % MODES.length] as DriveMode\n state.fourWheelEngaged = state.driveMode === '4x4'\n break\n }\n case 'lights':\n // off → position → low → off; high beam is its own switch over the low beam\n state.lamps.mode = state.lamps.mode === 'high' ? 'off' : (LAMPS[(LAMPS.indexOf(state.lamps.mode) + 1) % LAMPS.length] as LampMode)\n break\n case 'high_beam':\n state.lamps.mode = state.lamps.mode === 'high' ? 'low' : 'high'\n break\n case 'fog_lights':\n if (!hasFog) return emit({ type: 'refused', command: c, reason: 'no_fog_lamps' })\n state.lamps.fog = !state.lamps.fog\n // fog lamps go with the position lamps at least\n if (state.lamps.fog && state.lamps.mode === 'off') state.lamps.mode = 'position'\n break\n case 'interior_light':\n state.lamps.interior = !state.lamps.interior\n break\n case 'alarm':\n // armed → ringing (someone forced it) → off; off → armed\n state.alarm = state.alarm === 'off' ? 'armed' : state.alarm === 'armed' ? 'ringing' : 'off'\n break\n case 'radio':\n state.radio.on = !state.radio.on\n break\n case 'radio_source':\n state.radio.source = state.radio.source === 'radio' ? 'tape' : 'radio'\n break\n case 'radio_track':\n state.radio.track = (state.radio.track + 1) % Math.max(1, options.radioTracks ?? 3)\n break\n case 'exit':\n break\n case 'indicator_left':\n case 'indicator_right': {\n const side = c === 'indicator_left' ? 'left' : 'right'\n // the hazard switch wins over the stalk; the stalk pushed again the same way puts it back\n if (state.indicator === 'hazard') return\n state.indicator = state.indicator === side ? 'off' : side\n turned = 0\n blink = 0\n break\n }\n case 'hazard':\n state.indicator = state.indicator === 'hazard' ? 'off' : 'hazard'\n blink = 0\n break\n case 'wipers':\n state.wipers = WIPERS[(WIPERS.indexOf(state.wipers) + 1) % WIPERS.length] as Wipers\n break\n case 'drive_profile':\n state.profile = PROFILES[(PROFILES.indexOf(state.profile) + 1) % PROFILES.length] as DriveProfile\n break\n case 'traction_control':\n state.tractionControl = !state.tractionControl\n break\n case 'abs':\n state.abs = !state.abs\n break\n case 'cruise':\n if (state.cruise.on) state.cruise.on = false\n else if (!engineRunning) return emit({ type: 'refused', command: c, reason: 'ignition_off' })\n else if (lastSpeed < DEFAULT_CRUISE.minSpeed) return emit({ type: 'refused', command: c, reason: 'too_slow' })\n else state.cruise = { on: true, speed: lastSpeed }\n break\n case 'climate':\n state.climate.on = !state.climate.on\n if (!state.climate.on) state.climate.demist = false\n break\n case 'demist':\n // the air conditioning dries the air: the demister runs it\n state.climate.demist = !state.climate.demist\n if (state.climate.demist) state.climate.on = true\n break\n case 'seatbelt':\n state.seatbelt = !state.seatbelt\n break\n case 'siren':\n if (!options.emergency) return emit({ type: 'refused', command: c, reason: 'no_siren' })\n state.siren = SIRENS[(SIRENS.indexOf(state.siren) + 1) % SIRENS.length] as Siren\n // the siren never sounds with the lights off\n if (state.siren !== 'off') state.beacon = true\n break\n case 'beacon':\n if (!options.emergency) return emit({ type: 'refused', command: c, reason: 'no_siren' })\n state.beacon = !state.beacon\n if (!state.beacon) state.siren = 'off'\n beaconClock = 0\n break\n case 'glovebox':\n state.glovebox = !state.glovebox\n break\n }\n emit({ type: 'command', command: c, state })\n }\n\n const ease = (from: number, to: number, rate: number, dt: number): number => from + Math.sign(to - from) * Math.min(Math.abs(to - from), rate * dt)\n\n return {\n keys,\n state,\n key(code, down) {\n if (!driving.has(code)) return false\n const was = held.has(code)\n if (down) held.add(code)\n else held.delete(code)\n // a command runs on the press, not while the key repeats\n const c = commandOf.get(code)\n if (c && down && !was) command(c)\n return true\n },\n command,\n input(dt, driver) {\n const gas = any(keys.throttle) ? 1 : 0\n const stop = any(keys.brake) ? 1 : 0\n const wheel = (any(keys.left) ? 1 : 0) - (any(keys.right) ? 1 : 0)\n // pedals in a quarter of a second and out faster; the wheel turns in a third of a second and comes back to the centre faster still\n throttle = ease(throttle, gas, gas > throttle ? 4 : 8, dt)\n brake = ease(brake, stop, stop > brake ? 6 : 10, dt)\n steer = ease(steer, wheel, wheel !== 0 && Math.sign(wheel) === Math.sign(steer || wheel) ? 3 : 6, dt)\n const handbrake = state.parkingBrake || any(keys.handbrake)\n // the indicators blink on the relay; a turn the way they point and the wheel back near the centre cancels them\n state.tick = false\n if (state.indicator !== 'off') {\n const before = Math.floor(blink * blinkHz * 2)\n blink += dt\n const now = Math.floor(blink * blinkHz * 2)\n state.blinkOn = now % 2 === 0\n state.tick = now !== before\n if (state.indicator !== 'hazard') {\n const way = state.indicator === 'left' ? steer : -steer\n if (way > 0.5) turned = 1\n else if (turned && way < cancelAt) state.indicator = 'off'\n }\n } else state.blinkOn = false\n // the beacon's two sides take turns\n if (state.beacon) {\n beaconClock += dt\n state.beaconSide = (Math.floor(beaconClock * beaconHz) % 2) as 0 | 1\n }\n // no key: the ignition key held strips the wires, then joins them; the ignition goes live and the starter turns. An armed alarm goes off at the first touch.\n if (!hasKey && !state.hotwire.done && !state.ignition && any(keys.hotwire)) {\n if (state.hotwire.progress === 0) {\n if (state.alarm === 'armed') state.alarm = 'ringing'\n emit({ type: 'hotwire', stage: 'started' })\n }\n state.hotwire.progress = Math.min(1, state.hotwire.progress + dt / hotwireSeconds)\n if (state.hotwire.progress >= 1) {\n state.hotwire.done = true\n state.ignition = true\n crankAsked = true\n emit({ type: 'hotwire', stage: 'joined' })\n }\n }\n state.horn = any(keys.horn)\n state.lamps.flash = any(keys.flash)\n state.washer = any(keys.washer)\n // the clutch goes down fast and comes up as slowly as a foot lets it, so it bites on the way\n state.clutch = ease(state.clutch, any(keys.clutch) ? 1 : 0, any(keys.clutch) ? 8 : 2.5, dt)\n const speed = driver?.state.u ?? 0\n lastSpeed = speed\n // the brake, the clutch or the handbrake cancel cruise control\n if (state.cruise.on && (brake > 0.05 || state.clutch > 0.5 || handbrake)) {\n state.cruise.on = false\n emit({ type: 'cruise_cancelled' })\n }\n // the key off: no gas reaches the engine; the brakes still work\n const tune = DRIVE_PROFILES[state.profile]\n let gasNow = state.ignition ? throttle * tune.throttle : 0\n if (state.cruise.on && state.ignition) gasNow = Math.max(gasNow, cruiseThrottle(state.cruise.speed, speed))\n // the starter: the key turned, or (automatic, key on) the gas pressed after the engine died with the car still\n const gasStart = state.gearbox === 'automatic' && state.ignition && !engineRunning && throttle > 0 && Math.abs(speed) < 0.5\n state.cranking = false\n if (crankAsked || gasStart) {\n crankAsked = false\n if (options.canCrank && !options.canCrank()) emit({ type: 'refused', command: 'ignition', reason: 'battery_flat' })\n else {\n state.cranking = true\n options.onCrank?.()\n }\n }\n const driven = (driver?.state.slip ?? []).filter((_, i) => driver?.spec.wheels?.[i]?.drive ?? true)\n const powerLimit = (state.tractionControl ? tractionLimit(driven) : 1) * (options.powerLimit?.() ?? 1)\n const reversing = state.gearbox === 'manual' ? state.gear < 0 : (driver?.state.gear ?? 1) < 0\n state.reverseLights = reversing\n state.brakeLights = handbrake || (reversing ? gasNow > 0.05 && speed < -0.3 : brake > 0.05)\n const common = { steer, handbrake, horn: state.horn, start: state.cranking, powerLimit }\n if (state.gearbox === 'automatic') return { ...common, throttle: gasNow, brake }\n // manual: the gas drives the chosen gear either way (backwards in reverse) and the brake only brakes; the driver reads the pedals against the direction of travel\n const pedals = state.gear < 0 ? { throttle: brake, brake: gasNow } : { throttle: gasNow, brake }\n return { ...common, ...pedals, gear: state.gear, ...(options.clutchPedal ? { clutch: state.clutch } : {}) }\n },\n after(driver, dt) {\n if (!state.ignition && driver.state.engineOn) (driver.state as { engineOn: boolean }).engineOn = false\n engineRunning = driver.state.engineOn\n if (!engineRunning) state.cruise.on = false\n // the aids reach the driver: ABS on the brakes, the profile on the shift points\n const spec = driver.spec as { abs?: boolean; upshiftFraction?: number; downshiftFraction?: number }\n spec.abs = state.abs\n if (spec.upshiftFraction != null) {\n spec.upshiftFraction = DRIVE_PROFILES[state.profile].upshift\n spec.downshiftFraction = DRIVE_PROFILES[state.profile].downshift\n }\n if (state.driveMode === 'auto' && options.fourWheelDrive) {\n const slip = Math.max(0, ...driver.state.slip)\n if (slip > auto4.slip) {\n state.fourWheelEngaged = true\n calm = 0\n } else if (state.fourWheelEngaged && (calm += dt) > auto4.releaseSeconds) state.fourWheelEngaged = false\n } else state.fourWheelEngaged = state.driveMode === '4x4'\n driver.spec.fourWheelDrive = !!options.fourWheelDrive && state.fourWheelEngaged\n },\n release() {\n held.clear()\n throttle = brake = steer = 0\n state.horn = false\n state.lamps.flash = false\n state.washer = false\n state.clutch = 0\n state.cruise.on = false\n },\n }\n}\n","/** Matches a damage model's wheels to a driver's: each wheel of the spec takes the health of the tyre nearest to it. */\nimport type { SemiSimSpec, VehicleCondition } from './types'\n\nexport type DamagedTyre = {\n /** Where the tyre is in the vehicle's space, metres: x forward, z to the side. */\n readonly x: number\n readonly z: number\n /** 0 flat or gone, 1 whole. */\n readonly health: number\n /** The tyre is gone and the rim is on the road. */\n readonly rim?: boolean\n}\n\nexport type DamageReport = {\n readonly tyres: readonly DamagedTyre[]\n readonly brakes?: number\n readonly engine?: number\n readonly suspension?: number\n}\n\nexport function conditionFromDamage(spec: Pick<SemiSimSpec, 'wheels'>, report: DamageReport): VehicleCondition {\n const tyres = spec.wheels.map((wheel) => {\n let best: DamagedTyre | undefined\n let distance = Infinity\n for (const tyre of report.tyres) {\n const d = Math.hypot(tyre.x - wheel.x, tyre.z - wheel.z)\n if (d < distance) {\n distance = d\n best = tyre\n }\n }\n return best\n })\n return {\n tyres: tyres.map((tyre) => tyre?.health ?? 1),\n rims: tyres.map((tyre) => !!tyre?.rim),\n ...(report.brakes != null ? { brakes: report.brakes } : {}),\n ...(report.engine != null ? { engine: report.engine } : {}),\n ...(report.suspension != null ? { suspension: report.suspension } : {}),\n }\n}\n","/**\n * What keeps a car running besides the engine: the 12 V battery (the lamps, radio, wipers and alarm draw from it, the alternator charges it while\n * the engine turns, and below what the starter needs the car does not start), the coolant temperature (it climbs with the work of the engine, the air\n * through the radiator and the fan take it away, and a damaged radiator boils it: past `limpC` the engine loses power, past `seizeC` it dies) and the\n * spare tyre (one flat wheel can be swapped for it). It reads the driver and the controls and changes only what a real car would: the engine state,\n * the power it gives and the tyres. Every number is an option.\n */\nimport type { ControlState } from './controls'\nimport type { SemiState, VehicleCondition } from './semi/types'\n\nexport interface ElectricalLoads {\n /** Watts of each consumer while on. */\n readonly position: number\n readonly low: number\n readonly high: number\n readonly fog: number\n readonly interior: number\n readonly radio: number\n readonly wipers: number\n readonly indicators: number\n readonly horn: number\n readonly alarm: number\n readonly brakeLights: number\n readonly climate: number\n /** An emergency vehicle's siren amplifier and its beacon (light bar). */\n readonly siren: number\n readonly beacon: number\n}\n\nexport interface VehicleSystemsOptions {\n /** Battery capacity, watt-hours (a 12 V 60 Ah battery holds 720). */\n batteryWh?: number\n /** Charge at the start, 0..1. */\n charge?: number\n /** Alternator output, watts, at idle and from 2000 rpm up. */\n alternatorW?: { idle: number; full: number }\n /** Below this charge the starter does not turn the engine over. */\n crankCharge?: number\n /** Energy of one start, watt-hours. */\n startWh?: number\n loads?: Partial<ElectricalLoads>\n /** Air temperature, °C. */\n ambientC?: number\n /** The thermostat holds the coolant here once warm. */\n thermostatC?: number\n /** Limp mode above this (power cut), engine seizes above `seizeC`. */\n limpC?: number\n seizeC?: number\n /** Warming of the coolant, °C per second at full power; cooling share of the gap to the air per second, at a stop and at 100 km/h. */\n heatPerSecond?: number\n cooling?: { stopped: number; fast: number }\n /** Spare tyres carried. */\n spares?: number\n}\n\nexport const DEFAULT_LOADS: ElectricalLoads = { position: 20, low: 110, high: 130, fog: 110, interior: 10, radio: 25, wipers: 60, indicators: 42, horn: 60, alarm: 5, brakeLights: 42, climate: 180, siren: 100, beacon: 70 }\n\nexport type SystemsEvent = { type: 'battery_flat' } | { type: 'overheating' } | { type: 'seized' } | { type: 'spare_fitted'; wheel: number } | { type: 'no_spare' }\n\nexport interface SystemsState {\n /** 0..1. */\n charge: number\n /** Coolant, °C. */\n coolantC: number\n /** 0 cold (the air) to 1 (the seize point), for a gauge. */\n temperature: number\n overheating: boolean\n seized: boolean\n spares: number\n /** Net watts on the battery this step: positive charging, negative draining. */\n netW: number\n}\n\nexport interface SystemsDriver {\n readonly state: Pick<SemiState, 'engineOn' | 'rpm' | 'u'>\n condition: VehicleCondition\n}\n\nexport interface SystemsStepParams {\n driver: SystemsDriver\n controls: ControlState\n /** The gas the engine got this step, 0..1. */\n throttle: number\n dt: number\n /** What is left of the radiator, 0..1. Default 1. */\n radiator?: number\n /** The coolant temperature from a damage model that tracks it (the vehicle destructible's `runEngine`): it replaces this model's own. */\n coolantC?: number\n}\n\nexport interface VehicleSystems {\n readonly state: SystemsState\n /** The starter can turn the engine over now. */\n canCrank(): boolean\n /** Takes the energy of one start. */\n crank(): void\n /** Share of the torque the engine gives now (limp mode when hot). */\n powerLimit(): number\n /** Advances `dt` seconds; `throttle` is the gas the engine got, `controls` what is switched on. */\n step(params: SystemsStepParams): SystemsEvent[]\n /** Swaps the flat tyre of `wheel` for the spare. */\n fitSpare(driver: SystemsDriver, wheel: number): SystemsEvent\n /** Fills the battery (a jump start or a charger), 0..1 of the capacity. */\n charge(share: number): void\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\n\nexport function createVehicleSystems(options: VehicleSystemsOptions = {}): VehicleSystems {\n const loads: ElectricalLoads = { ...DEFAULT_LOADS, ...options.loads }\n const capacity = options.batteryWh ?? 720\n const alternator = options.alternatorW ?? { idle: 350, full: 1100 }\n const crankCharge = options.crankCharge ?? 0.25\n const startWh = options.startWh ?? 0.6\n const ambient = options.ambientC ?? 25\n const thermostat = options.thermostatC ?? 90\n const limp = options.limpC ?? 115\n const seize = options.seizeC ?? 130\n const heat = options.heatPerSecond ?? 0.5\n const cooling = options.cooling ?? { stopped: 0.004, fast: 0.03 }\n const state: SystemsState = { charge: clamp(options.charge ?? 1, 0, 1), coolantC: ambient, temperature: 0, overheating: false, seized: false, spares: options.spares ?? 1, netW: 0 }\n\n const draw = (c: ControlState): number => {\n const lamps = c.lamps\n let w = lamps.mode === 'off' ? 0 : loads.position\n if (lamps.mode === 'low') w += loads.low\n if (lamps.mode === 'high') w += loads.low + loads.high\n if (lamps.flash) w += loads.high\n if (lamps.fog) w += loads.fog\n if (lamps.interior) w += loads.interior\n if (c.radio.on) w += loads.radio\n if (c.wipers !== 'off' || c.washer) w += loads.wipers\n if (c.indicator !== 'off') w += loads.indicators * (c.indicator === 'hazard' ? 2 : 1) * 0.5\n if (c.horn) w += loads.horn\n if (c.alarm !== 'off') w += loads.alarm\n if (c.brakeLights) w += loads.brakeLights\n if (c.climate.on) w += loads.climate\n if (c.siren !== 'off') w += loads.siren\n if (c.beacon) w += loads.beacon\n return w\n }\n\n return {\n state,\n canCrank: () => state.charge >= crankCharge && !state.seized,\n crank() {\n state.charge = clamp(state.charge - startWh / capacity, 0, 1)\n },\n powerLimit: () => (state.coolantC <= limp ? 1 : clamp(1 - (state.coolantC - limp) / (seize - limp), 0.25, 1)),\n step({ driver, controls, throttle, dt, radiator = 1, coolantC }) {\n const events: SystemsEvent[] = []\n const running = driver.state.engineOn\n const charging = running ? alternator.idle + (alternator.full - alternator.idle) * clamp((driver.state.rpm - 900) / 1100, 0, 1) : 0\n // the key off leaves only what is wired to the battery directly: lamps, hazard, interior light, alarm, radio on memory\n const net = charging - draw(controls)\n state.netW = net\n const before = state.charge\n state.charge = clamp(state.charge + (net * dt) / 3600 / capacity, 0, 1)\n if (before >= crankCharge && state.charge < crankCharge && !running) events.push({ type: 'battery_flat' })\n // coolant: the engine's work heats it, the thermostat holds it until the radiator cannot keep up; a broken radiator barely cools\n const work = running ? clamp(0.15 + 0.85 * throttle * (driver.state.rpm / 6500), 0, 1) : 0\n const air = cooling.stopped + (cooling.fast - cooling.stopped) * clamp(Math.abs(driver.state.u) / 27.8, 0, 1)\n const cool = air * clamp(radiator, 0.05, 1) * (running ? 1 + (controls.climate.on ? 0.15 : 0) : 1)\n const opened = state.coolantC >= thermostat ? 1 : 0.15\n state.coolantC += (heat * work - cool * opened * (state.coolantC - ambient)) * dt\n state.coolantC = coolantC ?? Math.max(ambient, state.coolantC)\n state.temperature = clamp((state.coolantC - ambient) / (seize - ambient), 0, 1)\n const hot = state.coolantC > limp\n if (hot && !state.overheating) events.push({ type: 'overheating' })\n state.overheating = hot\n if (state.coolantC >= seize && !state.seized) {\n state.seized = true\n events.push({ type: 'seized' })\n }\n if (state.seized) (driver.state as { engineOn: boolean }).engineOn = false\n return events\n },\n fitSpare(driver, wheel) {\n if (state.spares <= 0) return { type: 'no_spare' }\n state.spares--\n const tyres = [...(driver.condition.tyres ?? [])]\n tyres[wheel] = 1\n driver.condition = { ...driver.condition, tyres }\n return { type: 'spare_fitted', wheel }\n },\n charge(share) {\n state.charge = clamp(state.charge + share, 0, 1)\n },\n }\n}\n","/**\n * Who leaves the car in a crash. An occupant without a belt keeps the speed the car had (inertia) while the car stops: in a frontal crash past\n * about 30 km/h of change in speed the body goes through the windshield, in a hard side impact or a rollover through the side window on the side it\n * is thrown to. A belted occupant stays in (a belt holds a person to the seat up to crashes far harder than a road car survives). The glass breaks\n * first; the body flies with most of the car's speed before the crash and a little lift. Pure numbers, every threshold an option.\n */\nexport type EjectionExit = 'windshield' | 'left_window' | 'right_window' | 'rear_window'\n\nexport interface EjectionOptions {\n /** Change of speed, m/s, past which an unbelted occupant goes through the windshield (about 30 km/h). */\n frontal: number\n /** Sideways change of speed, m/s, past which an unbelted occupant goes out of a side window. */\n side: number\n /** Share of the speed before the crash the body keeps on the way out (the glass and the dash take the rest). */\n keep: number\n /** Upward speed of the body leaving, m/s (it rides up over the dash). */\n lift: number\n}\n\nexport const DEFAULT_EJECTION: EjectionOptions = { frontal: 8.3, side: 6, keep: 0.8, lift: 2.5 }\n\nexport interface CrashPulse {\n /** Body-frame speed before and after the crash, m/s: forward and to the right. */\n readonly before: { readonly u: number; readonly w: number }\n readonly after: { readonly u: number; readonly w: number }\n /** The car rolled over in it. */\n readonly rolled?: boolean\n}\n\nexport interface Ejection {\n readonly exit: EjectionExit\n /** Body-frame velocity of the body leaving, m/s: forward, to the right, up. */\n readonly velocity: readonly [number, number, number]\n /** Change of speed of the crash, m/s (what the injuries scale with). */\n readonly deltaV: number\n}\n\n/** The ejection of one occupant, or null when the occupant stays in. */\nexport function ejectionOf(pulse: CrashPulse, belted: boolean, options: EjectionOptions = DEFAULT_EJECTION): Ejection | null {\n if (belted) return null\n const du = pulse.after.u - pulse.before.u\n const dw = pulse.after.w - pulse.before.w\n const deltaV = Math.hypot(du, dw)\n // the body moves against the car's change of speed: a car stopped from forward throws it forward\n const frontal = Math.abs(du) >= Math.abs(dw)\n if (frontal && Math.abs(du) < options.frontal && !pulse.rolled) return null\n if (!frontal && Math.abs(dw) < options.side && !pulse.rolled) return null\n const exit: EjectionExit = frontal ? (du < 0 ? 'windshield' : 'rear_window') : dw < 0 ? 'right_window' : 'left_window'\n return { exit, velocity: [pulse.before.u * options.keep, pulse.before.w * options.keep, options.lift], deltaV }\n}\n","/**\n * Parking sensors: the bumper's distance to the nearest obstacle in the way turns into the beep the cabin plays, slower far away, faster close,\n * continuous at the last few centimetres. Pure numbers, the distances are options.\n */\nexport interface ParkingSensorOptions {\n /** Farther than this (metres) it stays quiet. */\n readonly range: number\n /** Closer than this it beeps without pause. */\n readonly solid: number\n /** Pause between beeps at the edge of the range and near `solid`, seconds. */\n readonly slowest: number\n readonly fastest: number\n}\n\nexport const DEFAULT_PARKING_SENSOR: ParkingSensorOptions = { range: 1.5, solid: 0.3, slowest: 0.8, fastest: 0.12 }\n\n/** Seconds between beeps for an obstacle `distance` metres from the bumper: null when quiet, 0 when continuous. */\nexport function parkingBeepInterval(distance: number, options: ParkingSensorOptions = DEFAULT_PARKING_SENSOR): number | null {\n if (distance > options.range) return null\n if (distance <= options.solid) return 0\n const t = (distance - options.solid) / (options.range - options.solid)\n return options.fastest + (options.slowest - options.fastest) * t\n}\n\n/**\n * The bumper's distance to the nearest of `obstacles` (world x, z) in the vehicle's path: ahead when `forward`, behind otherwise. The vehicle is\n * at (x, z) facing `heading` (unit x, z), `length` and `width` metres; obstacles off to the side of its width are not in the way.\n */\nexport function bumperDistance(params: { x: number; z: number; heading: readonly [number, number]; length: number; width: number; forward: boolean; obstacles: ReadonlyArray<readonly [number, number]> }): number {\n const [hx, hz] = params.heading\n const sign = params.forward ? 1 : -1\n let best = Infinity\n for (const [ox, oz] of params.obstacles) {\n const dx = ox - params.x\n const dz = oz - params.z\n const along = (dx * hx + dz * hz) * sign - params.length / 2\n const side = Math.abs(-dx * hz + dz * hx)\n if (along >= 0 && side <= params.width / 2 + 0.2) best = Math.min(best, along)\n }\n return best\n}\n","/**\n * What a vehicle carries besides its people: the glovebox (reached from a front seat, or through an open front door, with its lid open) and the trunk\n * (reached with the lid up, from behind). Each compartment holds item stacks by slot, up to a slot count and a weight; nothing is reached while it is\n * shut, and the weight it carries is there for the driver to add to the vehicle's mass. Items are the host's (a game's catalog, `game-items`): a stack\n * is its id, its count, the weight of one and whatever state the host keeps with it. Every number is an option.\n */\n\nexport type CompartmentId = string\n\nexport interface CompartmentSpec {\n readonly id: CompartmentId\n /** Stacks it holds. */\n readonly slots: number\n /** Weight it takes, kg. */\n readonly capacityKg: number\n /** How it is reached: `cabin` from a front seat or an open front door with its own lid open (a glovebox); `lid` with the trunk lid up. */\n readonly access: 'cabin' | 'lid'\n}\n\n/** A stack in a compartment: the host's item id, how many and the weight of one; `data` is the host's own state of the stack (age, charge), kept as is. */\nexport interface StorageStack {\n readonly itemId: string\n readonly count: number\n readonly unitKg: number\n readonly data?: unknown\n}\n\n/** What reaches the compartments now. */\nexport interface StorageAccess {\n /** Someone sits in a front seat. */\n readonly seated: boolean\n /** A front door is open (someone standing outside reaches the glovebox). */\n readonly frontDoorOpen: boolean\n /** The glovebox lid is open (`ControlState.glovebox`). */\n readonly gloveboxOpen: boolean\n /** The trunk lid is up, 0..1 (open from 0.5). */\n readonly lid: number\n}\n\nexport type StoreResult = 'ok' | 'shut' | 'full' | 'too_heavy' | 'missing'\n\n/** A glovebox: a few small things (papers, a torch, a charger), about 8 litres. */\nexport const GLOVEBOX: CompartmentSpec = { id: 'glovebox', slots: 6, capacityKg: 4, access: 'cabin' }\n\n/** The trunk of a car by its size in litres (a hatch 280, a sedan 450, an estate 600): a slot every 25 litres and a kilo for every 4 litres. */\nexport const trunkFor = (litres = 450): CompartmentSpec => ({ id: 'trunk', slots: Math.max(4, Math.round(litres / 25)), capacityKg: Math.round(litres / 4), access: 'lid' })\n\nexport interface VehicleStorageOptions {\n /** Default: a glovebox and a 450-litre trunk. A motorcycle passes none, a pickup its bed as a `lid` compartment. */\n compartments?: readonly CompartmentSpec[]\n}\n\nexport interface VehicleStorage {\n readonly compartments: readonly CompartmentSpec[]\n /** The compartment can be reached now. */\n reachable(id: CompartmentId, access: StorageAccess): boolean\n /** Stacks by slot (null an empty slot). */\n contents(id: CompartmentId): ReadonlyArray<StorageStack | null>\n /** Weight in one compartment, or in all of them. */\n loadKg(id?: CompartmentId): number\n /** Puts a stack in (it joins a stack of the same item without host state); refused while shut, without a free slot or over the weight. */\n put(id: CompartmentId, stack: StorageStack, access: StorageAccess): StoreResult\n /** Takes the stack of a slot out; null while shut or empty. */\n take(id: CompartmentId, slot: number, access: StorageAccess): StorageStack | null\n /** Fills a compartment at once, reachable or not (what was in it when the vehicle was found); what does not fit is left out and returned. */\n stock(id: CompartmentId, stacks: readonly StorageStack[]): StorageStack[]\n /** Empties every compartment (the vehicle goes away). */\n clear(): void\n}\n\nconst weightOf = (stack: StorageStack): number => stack.unitKg * stack.count\n\nexport function createVehicleStorage(options: VehicleStorageOptions = {}): VehicleStorage {\n const compartments = [...(options.compartments ?? [GLOVEBOX, trunkFor()])]\n const slots = new Map<CompartmentId, Array<StorageStack | null>>(compartments.map((c) => [c.id, Array.from({ length: c.slots }, () => null)]))\n const specOf = (id: CompartmentId): CompartmentSpec | undefined => compartments.find((c) => c.id === id)\n const load = (id: CompartmentId): number => (slots.get(id) ?? []).reduce((kg, s) => kg + (s ? weightOf(s) : 0), 0)\n const reachable = (id: CompartmentId, access: StorageAccess): boolean => {\n const spec = specOf(id)\n if (!spec) return false\n return spec.access === 'lid' ? access.lid >= 0.5 : access.gloveboxOpen && (access.seated || access.frontDoorOpen)\n }\n const place = (id: CompartmentId, stack: StorageStack): StoreResult => {\n const spec = specOf(id)\n const list = slots.get(id)\n if (!spec || !list) return 'missing'\n if (load(id) + weightOf(stack) > spec.capacityKg + 1e-9) return 'too_heavy'\n const same = stack.data === undefined ? list.findIndex((s) => s !== null && s.itemId === stack.itemId && s.data === undefined) : -1\n if (same >= 0) {\n const s = list[same] as StorageStack\n list[same] = { ...s, count: s.count + stack.count }\n return 'ok'\n }\n const free = list.indexOf(null)\n if (free < 0) return 'full'\n list[free] = { ...stack }\n return 'ok'\n }\n return {\n compartments,\n reachable,\n contents: (id) => [...(slots.get(id) ?? [])],\n loadKg: (id) => (id === undefined ? compartments.reduce((kg, c) => kg + load(c.id), 0) : load(id)),\n put(id, stack, access) {\n if (!specOf(id)) return 'missing'\n if (!reachable(id, access)) return 'shut'\n return place(id, stack)\n },\n take(id, slot, access) {\n const list = slots.get(id)\n if (!list || !reachable(id, access)) return null\n const stack = list[slot] ?? null\n if (stack) list[slot] = null\n return stack\n },\n stock(id, stacks) {\n return stacks.filter((s) => place(id, s) !== 'ok')\n },\n clear() {\n for (const list of slots.values()) list.fill(null)\n },\n }\n}\n","/**\n * The glass misting up from inside. The people in the cabin breathe water into its air and wet clothes from the rain bring more; the air\n * that comes in (an open window, the fan, the air conditioning that dries it) takes it out. Fog forms when that moisture is past what the glass\n * holds clear, which drops the colder the glass is than the cabin (a cold day, rain on the glass, speed); the demister blows dry, warm air on it and\n * clears it in a few seconds once the engine is warm. The wipers clean only the outside: they do nothing to it. Every number is an option.\n */\n\nexport interface WindshieldFogOptions {\n /** Moisture of the air outside, 0..1. Default 0.6. */\n outsideHumidity?: number\n /** Moisture one occupant breathes into the cabin, share of saturation per second. Default 0.004. */\n breath?: number\n /** Moisture of wet clothes in the rain, per second at full rain. Default 0.002. */\n wet?: number\n /** Air change of a shut cabin per second, and what a window fully down, the climate fan and the demister add to it. */\n air?: { shut: number; window: number; climate: number; demist: number }\n /** Degrees of glass below the cabin that bring the fog down to half the moisture (0 degrees: fog only at saturation). Default 15. */\n coldSpan?: number\n /** Fog builds up, clears on its own and clears under the warm demister, share of the glass per second. */\n rates?: { build: number; clear: number; demist: number }\n}\n\nexport interface WindshieldFogState {\n /** Moisture of the cabin's air, 0..1 (1 saturated). */\n humidity: number\n /** Share of the glass misted, 0..1. */\n fog: number\n}\n\nexport interface WindshieldFogStep {\n dt: number\n /** People inside. */\n occupants: number\n /** Air temperature outside and in the cabin, °C. */\n outsideC: number\n cabinC: number\n /** Rain on the glass, 0..1. */\n rain?: number\n /** Speed, m/s: the wind over the glass cools it. */\n speed?: number\n /** The windows' opening, 0..1 summed share (one window fully down is 0.25 of a four-door car's four). */\n windows?: number\n climate: { on: boolean; demist: boolean }\n /** How warm the engine is, 0..1 (the demister blows cold air from a cold engine: it dries but does not warm the glass). */\n engineWarm?: number\n}\n\nexport interface WindshieldFog {\n readonly state: WindshieldFogState\n step(params: WindshieldFogStep): WindshieldFogState\n /** Sets the moisture and the fog at once (a car found shut in the rain). */\n set(state: Partial<WindshieldFogState>): void\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\n\nexport function createWindshieldFog(options: WindshieldFogOptions = {}): WindshieldFog {\n const outside = options.outsideHumidity ?? 0.6\n const breath = options.breath ?? 0.004\n const wet = options.wet ?? 0.002\n const air = options.air ?? { shut: 0.002, window: 0.05, climate: 0.01, demist: 0.06 }\n const coldSpan = options.coldSpan ?? 15\n const rates = options.rates ?? { build: 0.05, clear: 0.03, demist: 0.25 }\n const state: WindshieldFogState = { humidity: outside, fog: 0 }\n return {\n state,\n step({ dt, occupants, outsideC, cabinC, rain = 0, speed = 0, windows = 0, climate, engineWarm = 1 }) {\n const exchange = air.shut + air.window * clamp(windows, 0, 1) + (climate.on ? air.climate : 0) + (climate.demist ? air.demist : 0)\n const source = breath * Math.max(0, occupants) + wet * clamp(rain, 0, 1) * (occupants > 0 ? 1 : 0)\n // the air conditioning dries what comes in: with it on, the cabin tends to the outside air with most of its water left on the evaporator\n const towards = climate.on ? outside * 0.4 : outside\n state.humidity = clamp(state.humidity + (source - exchange * (state.humidity - towards)) * dt, 0, 1)\n // the glass is colder than the cabin by the weather (an open window brings the cabin towards the air outside), the rain on it and the wind of\n // speed; the warm demister brings it up to the cabin\n const cold = Math.max(0, cabinC - outsideC) * (1 - 0.7 * clamp(windows, 0, 1)) + 6 * clamp(rain, 0, 1) + 2 * clamp(speed / 27.8, 0, 1)\n const warmed = climate.demist ? cold * (1 - 0.9 * clamp(engineWarm, 0, 1)) : cold\n const clearUpTo = 1 - 0.5 * clamp(warmed / coldSpan, 0, 1)\n const target = clamp((state.humidity - clearUpTo) * 6, 0, 1)\n const down = climate.demist ? rates.demist * (0.3 + 0.7 * clamp(engineWarm, 0, 1)) : rates.clear\n state.fog = target > state.fog ? Math.min(target, state.fog + rates.build * dt) : Math.max(target, state.fog - down * dt)\n return state\n },\n set(next) {\n if (next.humidity !== undefined) state.humidity = clamp(next.humidity, 0, 1)\n if (next.fog !== undefined) state.fog = clamp(next.fog, 0, 1)\n },\n }\n}\n","import type { BodyDesc, Curve, TrackDesc, VehicleDesc, WheelDesc } from '@adatechnology/game-physics'\n\nimport { FLAT_BELOW, RIM_FRICTION, RIM_RADIUS_SHARE, torqueAt } from './semi/driver'\nimport type { SemiPedal, SemiSimSpec, SemiTracks, SemiWheel, VehicleCondition } from './semi/types'\n\nconst GRAVITY = 9.81\n/** Where the torque curve still gives its torque before the redline cuts it (rpm under the redline). */\nconst CURVE_CUT_GAP_RPM = 1\n/** Share of the brake force the front axle takes, and of the handbrake force each locked wheel takes. */\nconst FRONT_BRAKE_SHARE = 0.6\nconst HANDBRAKE_SHARE = 0.5\n/** Suspension travel left when fully compressed, as a share of the free length. */\nconst SUSPENSION_MIN_SHARE = 0.4\n/** The most of the free length the static sag may take. */\nconst MAX_SAG = 0.5\n/** A motorcycle's lean spring and damper per kg m^2 of roll inertia (measured: the engine's own values are for a real bike's inertia), and its lean limit. */\nconst LEAN_SPRING_PER_INERTIA = 400\nconst LEAN_DAMPING_PER_INERTIA = 40\nconst LEAN_LIMIT = 0.7\n/** A track's lateral grip: with the tyre's own (about 0.9) the engine cannot swing a 40 t tracked vehicle round on the spot (it did not turn at all); at 0.6 and under it pivots (measured, specs/008 evidence T6.2c). */\nconst TRACK_LATERAL_FRICTION = 0.5\nconst WHEEL_WIDTH = 0.2\nconst CLUTCH_STRENGTH = 10\nconst CLUTCH_SLIP = 0.03\nconst BICYCLE_WHEEL_INERTIA = 0.1\n/** A wheel with its tyre and brake weighs about 1.5% of the vehicle: its inertia `1/2 m r^2` is this per kg of the vehicle at a 0.32 m radius (0.83 kg m^2 on a 1 t car; the engine's own 0.9 is a car's, and four of them on a 150 kg bike weigh as much as the bike). */\nconst WHEEL_INERTIA_PER_MASS = 0.0008\nconst REFERENCE_RADIUS = 0.32\nconst MIN_WHEEL_INERTIA = 0.02\n/** The wheels' spin damping: the engine's own (0.2) is a drag of 7.8 N per m/s on a car's four wheels (0.4 kN at 50 m/s) the spec's rolling resistance already covers. */\nconst WHEEL_DAMPING = 0.02\n/** The engine's friction: the semi-simulation has none beyond its efficiency (the engine's own, 0.2, would take 85 N m of a 187 N m engine at 4 000 rpm). */\nconst ENGINE_DAMPING = 0.005\n/** The engine's rotating mass per N m of peak torque (kg m^2): 0.19 for a 190 N m car engine; the engine's own 0.5 is a third of a ton of inertia in first gear on a car and a ton on a bike. */\nconst ENGINE_INERTIA_PER_TORQUE = 0.001\n/** What a worn engine and a worn suspension keep of their torque and of their spring and damper (the semi-simulation's own floors). */\nconst ENGINE_FLOOR = 0.55\nconst SUSPENSION_FLOOR = 0.5\n/**\n * Gearbox timing, seconds (the engine's own 0.5 + 0.3 + 0.5 is a slow truck's box and a quarter of a 0-100 km/h of a hatch): the shift itself, the clutch closing after it, and the wait before the next shift.\n * The card has no gearbox type (the semi-simulation shifts automatically and instantly), so a car gets the middle of the real range: a modern automatic or dual-clutch shifts in 0.1-0.3 s and a manual\n * in 0.3-0.6 s of a practised hand, 0.2 s of torque interruption plus 0.1 s of hold-off in all. A motorcycle's box (dog rings, no torque converter, a short clutch) shifts in about 0.1-0.2 s.\n * An estimate from those ranges (manufacturer shift-time figures, e.g. ZF 8HP ~0.2 s, dual-clutch < 0.1 s); the measurement that tied these to real 0-100 km/h times is in specs/008 evidence T6.2b.\n */\nconst CAR_TRANSMISSION = { switchTime: 0.1, clutchReleaseTime: 0.1, switchLatency: 0.1 } as const\nconst MOTORCYCLE_TRANSMISSION = { switchTime: 0.05, clutchReleaseTime: 0.07, switchLatency: 0.05 } as const\n\n/** A cyclist as the engine (the spec's own `pedal` when the options do not give one). */\nexport type PedalOptions = SemiPedal\n\nexport interface VehicleFromSemiOptions {\n /** The body: shape, pose, user, velocity, layer. Its origin is the centre of mass (`centreAtOrigin` is set); mass and inertia come from the spec. */\n readonly chassis: Omit<BodyDesc, 'motion' | 'mass' | 'inertia' | 'centreAtOrigin'>\n /** What is wrong with it now: a flat tyre or a bare rim rides on the rim's radius with its grip, a worn engine gives less, worn brakes brake less. */\n readonly condition?: VehicleCondition\n readonly wheelWidth?: number\n /** Rotational inertia of each wheel with its tyre, kg m^2: by default 0.0008 per kg of the vehicle (a bicycle: 0.1). */\n readonly wheelInertia?: number\n /** A bicycle's engine in place of `spec.engine` (`spec.pedal` when omitted). */\n readonly pedal?: PedalOptions\n}\n\n/** The clutch passes `strength x (engine speed - wheel speed)`: strong enough that the full torque goes through with 3% of slip at the top of the range (never under the engine's own 10: a bicycle's 28 N m at 120 rpm needs 75). */\nconst clutchFor = (peakTorque: number, maxRpm: number): number => Math.max(CLUTCH_STRENGTH, peakTorque / (CLUTCH_SLIP * ((maxRpm * 2 * Math.PI) / 60)))\n\nconst clamp = (x: number, low: number, high: number): number => Math.max(low, Math.min(high, x))\n\nconst torqueCurve = (spec: SemiSimSpec): Curve => {\n const { idleRpm, peakRpm, redlineRpm, peakTorque } = spec.engine\n const at = (rpm: number): number => torqueAt(spec, rpm) / peakTorque\n return [[0, at(0)], [idleRpm / redlineRpm, at(idleRpm)], [peakRpm / redlineRpm, at(peakRpm)], [(redlineRpm - CURVE_CUT_GAP_RPM) / redlineRpm, at(redlineRpm - CURVE_CUT_GAP_RPM)], [1, 0]]\n}\n\n/** Grip across the wheel by slip angle (degrees): rising to `friction` where `corneringStiffness` says, then easing to 0.75 of it sideways. */\nconst lateralCurve = (friction: number, corneringStiffness: number): Curve => [[0, 0], [((friction / corneringStiffness) * 180) / Math.PI, friction], [90, 0.75 * friction]]\n\n/** Grip along the wheel by slip ratio: the peak at 6% slip, 0.8 of it locked. */\nconst longitudinalCurve = (friction: number): Curve => [[0, 0], [0.06, friction], [1, 0.8 * friction]]\n\nconst isFlat = (condition: VehicleCondition, index: number): boolean => (condition.tyres?.[index] ?? 1) < FLAT_BELOW || condition.rims?.[index] === true\n\ninterface WheelContext {\n readonly spec: SemiSimSpec\n readonly condition: VehicleCondition\n readonly options: VehicleFromSemiOptions\n /** The x the front axle starts at: wheels ahead of the mean x. */\n readonly frontFrom: number\n readonly frontCount: number\n readonly rearCount: number\n readonly handbrakeCount: number\n}\n\nconst wheelOf = (wheel: SemiWheel, index: number, context: WheelContext): WheelDesc => {\n const { spec, condition, options } = context\n const cornerMass = spec.mass / spec.wheels.length\n const wear = SUSPENSION_FLOOR + (1 - SUSPENSION_FLOOR) * clamp(condition.suspension ?? 1, 0, 1)\n const free = spec.suspension.restLength\n // the spec's spring is a car's: a heavy vehicle that kept it would sag past its own travel and sit on its belly, so the spring stiffens (the damper with it) until the sag is the share MAX_SAG of the travel\n const stiffening = Math.max(1, (cornerMass * GRAVITY) / (MAX_SAG * free * spec.suspension.spring * wear))\n const spring = spec.suspension.spring * wear * stiffening\n const damper = spec.suspension.damper * wear * stiffening\n const sag = (cornerMass * GRAVITY) / spring\n const flat = isFlat(condition, index)\n const rimRadius = spec.rimRadius ?? RIM_RADIUS_SHARE * spec.wheelRadius\n const friction = flat ? RIM_FRICTION : spec.tyre.friction\n const front = wheel.x >= context.frontFrom\n const brakeShare = front ? FRONT_BRAKE_SHARE / context.frontCount : (1 - FRONT_BRAKE_SHARE) / context.rearCount\n const brakeTorque = spec.brakeForce * clamp(condition.brakes ?? 1, 0, 1) * spec.wheelRadius * brakeShare\n return {\n // x is to the vehicle's left and z ahead; the semi-simulation has z to the right\n position: [-wheel.z, spec.wheelRadius - spec.centreHeight + (free - sag), wheel.x],\n radius: flat ? rimRadius : spec.wheelRadius,\n width: options.wheelWidth ?? WHEEL_WIDTH,\n suspensionMin: free * SUSPENSION_MIN_SHARE,\n suspensionMax: free,\n frequency: Math.sqrt(spring / cornerMass) / (2 * Math.PI),\n damping: damper / (2 * Math.sqrt(spring * cornerMass)),\n maxSteer: wheel.steer ? spec.maxSteer : 0,\n driven: spec.fourWheelDrive || wheel.drive === true,\n maxBrakeTorque: brakeTorque,\n maxHandBrakeTorque: wheel.handbrake ? (spec.brakeForce * spec.wheelRadius * HANDBRAKE_SHARE) / context.handbrakeCount : 0,\n inertia: options.wheelInertia ?? (options.pedal ? BICYCLE_WHEEL_INERTIA : Math.max(MIN_WHEEL_INERTIA, WHEEL_INERTIA_PER_MASS * spec.mass * (spec.wheelRadius / REFERENCE_RADIUS) ** 2)),\n angularDamping: WHEEL_DAMPING,\n longitudinalFriction: longitudinalCurve(friction),\n lateralFriction: lateralCurve(friction, spec.tyre.corneringStiffness),\n }\n}\n\nconst wheelContext = (spec: SemiSimSpec, options: VehicleFromSemiOptions): WheelContext => {\n const meanX = spec.wheels.reduce((sum, wheel) => sum + wheel.x, 0) / spec.wheels.length\n const frontCount = spec.wheels.filter((wheel) => wheel.x >= meanX).length\n return {\n spec,\n condition: options.condition ?? {},\n options,\n frontFrom: meanX,\n frontCount,\n rearCount: Math.max(1, spec.wheels.length - frontCount),\n handbrakeCount: Math.max(1, spec.wheels.filter((wheel) => wheel.handbrake).length),\n }\n}\n\nconst inertiaOf = (spec: SemiSimSpec): readonly [number, number, number] => {\n const xs = spec.wheels.map((wheel) => wheel.x)\n const zs = spec.wheels.map((wheel) => wheel.z)\n const wheelbase = Math.max(...xs) - Math.min(...xs)\n const track = Math.max(...zs) - Math.min(...zs)\n // the semi-simulation's own moments: pitch and roll with 1 m of height, yaw from the plan\n return [(spec.mass * (wheelbase * wheelbase + 1)) / 12, spec.yawInertia ?? (spec.mass * (wheelbase * wheelbase + track * track)) / 12, (spec.mass * (track * track + 1)) / 12]\n}\n\nconst drivetrainOf = (spec: SemiSimSpec, options: VehicleFromSemiOptions): Pick<VehicleDesc, 'maxTorque' | 'engineDamping' | 'engineInertia' | 'minRpm' | 'maxRpm' | 'gears' | 'reverseGears' | 'differentialRatio' | 'torqueCurve' | 'transmission'> => {\n const pedal = options.pedal ?? spec.pedal\n if (pedal) {\n const crankSpeed = (pedal.cadenceRpm * 2 * Math.PI) / 60\n return {\n engineDamping: ENGINE_DAMPING,\n engineInertia: ENGINE_INERTIA_PER_TORQUE * (pedal.watts / crankSpeed),\n maxTorque: (pedal.watts / crankSpeed) * spec.efficiency,\n minRpm: 0,\n maxRpm: pedal.cadenceRpm * 1.5,\n // the engine turns once for every wheel turn / ratio: a gear of 2 turns the wheel twice a pedal turn\n gears: pedal.gears.map((ratio) => 1 / ratio),\n reverseGears: [],\n differentialRatio: 1,\n torqueCurve: [[0, 1], [0.67, 1], [1, 0]],\n transmission: { shiftUpRpm: pedal.cadenceRpm * 0.95, shiftDownRpm: pedal.cadenceRpm * 0.5, clutchStrength: clutchFor(pedal.watts / crankSpeed, pedal.cadenceRpm * 1.5) },\n }\n }\n const health = clamp(options.condition?.engine ?? 1, 0, 1)\n return {\n engineDamping: ENGINE_DAMPING,\n engineInertia: ENGINE_INERTIA_PER_TORQUE * spec.engine.peakTorque,\n maxTorque: spec.engine.peakTorque * spec.efficiency * (ENGINE_FLOOR + (1 - ENGINE_FLOOR) * health),\n minRpm: spec.engine.idleRpm,\n maxRpm: spec.engine.redlineRpm,\n gears: spec.gears,\n reverseGears: [-spec.reverseRatio],\n differentialRatio: spec.finalDrive,\n torqueCurve: torqueCurve(spec),\n transmission: {\n shiftUpRpm: spec.engine.redlineRpm * spec.upshiftFraction,\n shiftDownRpm: spec.engine.redlineRpm * spec.downshiftFraction,\n clutchStrength: clutchFor(spec.engine.peakTorque, spec.engine.redlineRpm),\n ...(spec.wheels.length === 2 ? MOTORCYCLE_TRANSMISSION : CAR_TRANSMISSION),\n },\n }\n}\n\n/** The road wheels of a tracked vehicle, left track (the +x side of the chassis) first, as the wheels of a spec; each track is `TrackDesc` over its own wheels, driven at the rear. */\nconst trackedOf = (spec: SemiSimSpec, tracks: SemiTracks): { readonly spec: SemiSimSpec; readonly tracks: NonNullable<VehicleDesc['tracks']> } => {\n const count = Math.max(2, tracks.roadWheels)\n const alongX = (index: number): number => tracks.rearX + ((tracks.frontX - tracks.rearX) * index) / (count - 1)\n // the spec's z is to the right: the left track is the negative z\n const wheels: SemiWheel[] = [-1, 1].flatMap((side) => Array.from({ length: count }, (_, index) => ({ x: alongX(index), z: (side * tracks.gauge) / 2 })))\n const friction = spec.tyre.friction\n const side = (first: number): TrackDesc => ({ wheels: Array.from({ length: count }, (_, index) => first + index), drivenWheel: first, longitudinalFriction: friction, lateralFriction: TRACK_LATERAL_FRICTION, maxBrakeTorque: (spec.brakeForce * spec.wheelRadius) / 2 })\n return { spec: { ...spec, wheels }, tracks: [side(0), side(count)] }\n}\n\n/**\n * The semi-simulation's vehicle as a physics-engine vehicle (design 7.1): the wheels where the spec has them (x to the left, z ahead, from the centre of mass),\n * the suspension as a frequency and a damping ratio from the spring and the corner's mass, the engine and gearbox, the tyres as the two grip curves, the brake\n * force split 60/40, the mass and the moments of the spec. Two wheels make a motorcycle (a bicycle with `pedal`). The ground's grip is the ground body's own\n * friction, and the air drag and the rolling resistance are `resistanceImpulse`.\n */\nexport const vehicleDescFromSemi = (spec: SemiSimSpec, options: VehicleFromSemiOptions): VehicleDesc => {\n const tracked = spec.tracks ? trackedOf(spec, spec.tracks) : undefined\n const body = tracked ? tracked.spec : spec\n const context = wheelContext(body, options)\n const inertia = inertiaOf(spec)\n const bike = body.wheels.length === 2\n return {\n // no damping of the body's own: it would be a drag of 0.05 m/s per m/s (1.8 kN at 28 m/s on a 1.3 t car) the spec never asked for; `resistanceImpulse` is the drag\n chassis: { linearDamping: 0, angularDamping: 0, ...options.chassis, motion: 'dynamic', mass: spec.mass, inertia, centreAtOrigin: true, allowSleep: true },\n wheels: body.wheels.map((wheel, index) => wheelOf(wheel, index, context)),\n ...drivetrainOf(spec, options),\n ...(tracked ? { controller: 'tracked' as const, tracks: tracked.tracks } : {}),\n ...(bike\n ? { controller: 'motorcycle' as const, motorcycle: { maxLeanAngle: LEAN_LIMIT, leanSpring: LEAN_SPRING_PER_INERTIA * inertia[2], leanDamping: LEAN_DAMPING_PER_INERTIA * inertia[2] } }\n : {}),\n }\n}\n","import type { VehicleInput } from '@adatechnology/game-physics'\n\nimport type { SemiInput } from './semi/types'\n\n/** What the vehicle can do now (the fields of the destructible's `status()` this needs: any object with them works). */\nexport interface DriveStatus {\n /** Engine runs and the gearbox transmits. */\n readonly canDrive: boolean\n /** 1 is normal; this many times longer to stop with worn or missing brakes. */\n readonly brakeFactor: number\n /** -1..1: the sideways pull of a damaged steering or flat tyres (negative is left). */\n readonly steerPull: number\n}\n\nexport interface PhysicsInputOptions {\n /** The steering follows its target by `min(1, steerResponse dt)`: the arcade's 5 per second. */\n readonly steerResponse?: number\n /** Lock lost per m/s of speed (the steering assistance), and the share of it that is never lost. */\n readonly steerFalloff?: number\n readonly steerFloor?: number\n /** Below this speed (m/s), forward or back, a brake asks for reverse and a throttle for forward. */\n readonly reverseBelow?: number\n /** Share of the full lock a full `steerPull` pulls with. */\n readonly pullShare?: number\n}\n\nexport interface PhysicsInputParams {\n readonly input: SemiInput\n /** Signed speed along the front of the vehicle, m/s. */\n readonly speed: number\n /** Seconds since the last call. */\n readonly dt: number\n readonly status?: Partial<DriveStatus>\n}\n\nexport interface PhysicsInputMapper {\n /** The engine's input for this step. It keeps the filtered steering between calls. */\n map(params: PhysicsInputParams): VehicleInput\n reset(): void\n}\n\n/** Starting values, to be calibrated against the vehicle on the engine (T6.2b): the response is the arcade's, the assistance and the pull are not measured yet. */\nexport const DEFAULT_PHYSICS_INPUT: Required<PhysicsInputOptions> = { steerResponse: 5, steerFalloff: 0.012, steerFloor: 0.4, reverseBelow: 0.5, pullShare: 0.2 }\n\nconst clamp = (x: number, low: number, high: number): number => Math.max(low, Math.min(high, x))\n\n/**\n * Pedals to the engine's input (design 7.2): throttle and brake cancel into one pedal; forward from a stop or above, hard brake against the move, reverse from\n * a stop; the power limit of traction control and a hurt engine cuts the throttle; the brake factor of a worn brake softens the brake; steering is the kit's\n * positive-left turned into the engine's positive-right, filtered, eased with the speed, and pulled by a damaged steering. A vehicle that cannot drive gets no\n * throttle (the brake and the steering still work).\n */\nexport const createPhysicsInputMapper = (options: PhysicsInputOptions = {}): PhysicsInputMapper => {\n const rules = { ...DEFAULT_PHYSICS_INPUT, ...options }\n let steering = 0\n return {\n reset() {\n steering = 0\n },\n map({ input, speed, dt, status }) {\n const pedal = clamp(input.throttle, 0, 1) - clamp(input.brake, 0, 1)\n const powerLimit = clamp(input.powerLimit ?? 1, 0, 1)\n const canDrive = status?.canDrive ?? true\n const brakeSoftness = 1 / Math.max(1, status?.brakeFactor ?? 1)\n let forward = 0\n let brake = 0\n if (pedal > 0) {\n if (speed < -rules.reverseBelow) brake = pedal * brakeSoftness\n else forward = pedal * powerLimit\n } else if (pedal < 0) {\n if (speed > rules.reverseBelow) brake = -pedal * brakeSoftness\n else forward = pedal * powerLimit\n }\n const lock = Math.max(rules.steerFloor, 1 - rules.steerFalloff * Math.abs(speed))\n const target = -clamp(input.steer, -1, 1) * lock\n steering += (target - steering) * Math.min(1, dt * rules.steerResponse)\n const pull = clamp(status?.steerPull ?? 0, -1, 1) * rules.pullShare\n return { forward: canDrive ? forward : 0, right: clamp(steering + pull, -1, 1), brake, handBrake: input.handbrake ? 1 : 0 }\n },\n }\n}\n","import type { Vec3 } from '@adatechnology/game-physics'\n\nimport type { SemiSimSpec } from './semi/types'\n\nconst GRAVITY = 9.81\n/** Under this speed (m/s) the rolling resistance fades out instead of flipping the direction of the velocity. */\nconst ROLLING_FADE_SPEED = 0.5\n\n/**\n * The impulse (N s) the air and the tyres take from a vehicle moving at `velocity` (its horizontal part) over one step `dt`, for the body's centre of mass: `-drag |v| v dt` for the air\n * (the spec's drag is `0.5 rho Cd A`) and `-rolling m g dt` along the velocity for the tyres. Apply it every fixed step in the `actors` phase; the wheels' own\n * contact does not know either.\n */\nexport const resistanceImpulse = (spec: Pick<SemiSimSpec, 'drag' | 'rolling' | 'mass'>, velocity: Vec3, dt: number): Vec3 => {\n const speed = Math.hypot(velocity[0], velocity[2])\n if (speed === 0) return [0, 0, 0]\n const rolling = spec.rolling * spec.mass * GRAVITY * Math.min(1, speed / ROLLING_FADE_SPEED)\n const along = -(spec.drag * speed * speed + rolling) * dt\n return [(velocity[0] / speed) * along, 0, (velocity[2] / speed) * along]\n}\n","import type { BodyId, PhysicsLoop, Quat, Vec3 } from '@adatechnology/game-physics'\n\nimport { defaultArcadeSpec } from './arcade'\nimport type { RunOverRules } from './arcade'\nimport { runOver } from './run-over'\nimport type { RunOverOutcome } from './run-over'\n\n/** What the run-over needs of the crowd: `game-crowd`'s `Crowd` is one as it is, and nothing here imports it. */\nexport type RunOverCrowd = {\n readonly store: {\n readonly n: number\n readonly x: Float32Array\n readonly z: Float32Array\n readonly vx: Float32Array\n readonly vz: Float32Array\n readonly mass: Float32Array\n readonly identity: Uint32Array\n }\n damage(index: number, hit: { readonly region: 1; readonly amount: number; readonly distance: number }): { readonly died: boolean }\n kill(index: number): void\n knockDown(index: number, velocity: { readonly x: number; readonly z: number }): void\n}\n\n/** The kinematic capsules of the agents (`createAgentBodies` of `game-crowd`): capsule `i` follows agent `i`. */\nexport type RunOverAgents = { readonly count: number; bodyOf(index: number): BodyId | undefined }\n\n/** A car the run-over watches: its chassis body and the half sizes of its box (x right, y up, z forward, as the engine's vehicles). */\nexport type RunOverVehicle = { readonly body: BodyId; readonly half: Vec3 }\n\nexport type RunOverHit = {\n readonly vehicle: BodyId\n readonly agent: number\n readonly outcome: RunOverOutcome\n /** Closing speed (m/s) and the energy the hit dissipated: half the reduced mass times the closing speed squared (J). */\n readonly speed: number\n readonly energy: number\n /** What `RunOverRules.killVehicleDamage` says the car takes: 0 unless the body died. */\n readonly vehicleDamage: number\n}\n\nexport type RunOverOptions = {\n readonly crowd: RunOverCrowd\n readonly agents: RunOverAgents\n readonly rules?: Partial<RunOverRules>\n /** Told of each hit inside the fixed step (the host's sound, blood, damage to the car). */\n readonly onHit?: (hit: RunOverHit) => void\n}\n\nexport type RunOver = {\n /** Watches a car from the next step on; returns the way to stop. */\n track(vehicle: RunOverVehicle): () => void\n /** The velocity a body that dies in this very call carries (a `CorpseBodies.add` made in the crowd's `corpses` listener reads it); undefined outside a hit. */\n readonly dyingVelocity: Vec3 | undefined\n dispose(): void\n}\n\nconst byIndexDescending = (a: number, b: number): number => b - a\n\n/** Slowest car (m/s) that runs anyone over. */\nconst MIN_SPEED = 1\n/** Mass (kg) of the body the arcade damage (`knockDamage`) is written for, and of an agent whose mass is not seated. */\nconst REFERENCE_MASS = 70\n/** Speed (m/s) a pushed body is moved aside at. */\nconst PUSH_ASIDE_SPEED = 1\n\n/**\n * Cars against the crowd's agents, in the loop's `actors` phase (veiculos.md 7.8). The `vehicle` and `agent` layers do not meet, because an agent is kinematic and would stop a truck as a\n * wall: the car sweeps its box over the step against the `agent` layer instead. A body in the way meets the car as a perfectly inelastic hit (momentum kept: the car loses `m / (M + m)`\n * of the closing speed and the body leaves at the common speed), which `RunOverRules` classes by the closing speed: pushed aside below `knockSpeed` (the car held by `holdDrag`), knocked\n * down (damage `knockDamage` by the energy, stunned) up to `killSpeed`, killed above it. Whoever dies is told to the crowd with the car's velocity in `dyingVelocity`.\n */\nexport const createRunOver = (loop: PhysicsLoop, options: RunOverOptions): RunOver => {\n const { crowd, agents } = options\n const rules = { ...defaultArcadeSpec.runOver, ...options.rules }\n const world = loop.world\n const vehicles: RunOverVehicle[] = []\n /** The agents each car already struck and still overlaps: a body knocked down is under the car for a few steps and is struck once. */\n const struck = new Map<RunOverVehicle, Set<number>>()\n const hits: BodyId[] = []\n const pose = new Float64Array(7)\n const velocity = new Float64Array(6)\n const box = { kind: 'box' as const, half: [0, 0, 0] as [number, number, number] }\n const centre: [number, number, number] = [0, 0, 0]\n const rotation: [number, number, number, number] = [0, 0, 0, 1]\n const impulse: [number, number, number] = [0, 0, 0]\n const point: [number, number, number] = [0, 0, 0]\n const direction: [number, number] = [0, 0]\n const car = { speed: 0, mass: 0 }\n const found: number[] = []\n const now = new Set<number>()\n /** The index of each agent's capsule, made when a hit needs it and again after a hit that may have moved the last agent into a slot. */\n const indexOfBody = new Map<BodyId, number>()\n let isIndexStale = true\n let dying: Vec3 | undefined\n let diedLast = false\n\n /** The agent indices whose capsule is among `bodies`, descending: a death moves the last agent into its slot, so the ones not yet handled keep their index. */\n const agentsOf = (bodies: readonly BodyId[]): number[] => {\n if (isIndexStale) {\n indexOfBody.clear()\n for (let index = 0; index < agents.count; index++) {\n const body = agents.bodyOf(index)\n if (body !== undefined) indexOfBody.set(body, index)\n }\n isIndexStale = false\n }\n found.length = 0\n for (const body of bodies) {\n const index = indexOfBody.get(body)\n if (index !== undefined) found.push(index)\n }\n return found.sort(byIndexDescending)\n }\n\n /** What the body in the way does to the car and to itself; returns the momentum (N s) the car loses. */\n const strike = (index: number, outcome: RunOverOutcome, direction: readonly [number, number], hit: { readonly reduced: number; readonly closing: number; readonly common: number; readonly carMomentum: number }, h: number): number => {\n const { store } = crowd\n if (outcome === 'push') {\n store.x[index]! += -direction[1] * PUSH_ASIDE_SPEED * h\n store.z[index]! += direction[0] * PUSH_ASIDE_SPEED * h\n return hit.carMomentum * (1 - Math.exp(-rules.holdDrag * h))\n }\n dying = [direction[0] * hit.common, 0, direction[1] * hit.common]\n if (outcome === 'kill') crowd.kill(index)\n else if (!crowd.damage(index, { region: 1, amount: (hit.reduced / REFERENCE_MASS) * hit.closing * hit.closing * rules.knockDamage, distance: 0 }).died) {\n dying = undefined\n crowd.knockDown(index, { x: direction[0] * hit.common, z: direction[1] * hit.common })\n }\n const died = dying !== undefined\n dying = undefined\n diedLast = died\n return hit.reduced * hit.closing\n }\n\n const hitOne = (vehicle: RunOverVehicle, index: number, direction: readonly [number, number], car: { speed: number; readonly mass: number }, h: number): RunOverOutcome | undefined => {\n const { store } = crowd\n const mass = store.mass[index]! > 0 ? store.mass[index]! : REFERENCE_MASS\n const closing = car.speed - (store.vx[index]! * direction[0] + store.vz[index]! * direction[1])\n if (closing <= 0) return undefined\n const reduced = (mass * car.mass) / (mass + car.mass)\n const outcome = runOver(closing, rules)\n diedLast = false\n const lost = strike(index, outcome, direction, { reduced, closing, common: car.speed - (mass / (mass + car.mass)) * closing, carMomentum: car.mass * car.speed }, h)\n car.speed -= lost / car.mass\n impulse[0] = -direction[0] * lost\n impulse[2] = -direction[1] * lost\n world.addImpulse(vehicle.body, impulse, point)\n options.onHit?.({ vehicle: vehicle.body, agent: index, outcome, speed: closing, energy: 0.5 * reduced * closing * closing, vehicleDamage: diedLast ? rules.killVehicleDamage : 0 })\n return outcome\n }\n\n const sweep = (vehicle: RunOverVehicle, h: number): void => {\n world.readVelocity(vehicle.body, velocity, 0)\n const speed = Math.hypot(velocity[0]!, velocity[2]!)\n if (speed < MIN_SPEED) return\n world.readPose(vehicle.body, pose, 0)\n direction[0] = velocity[0]! / speed\n direction[1] = velocity[2]! / speed\n const reach = (speed * h) / 2\n box.half[0] = vehicle.half[0] + rules.margin\n box.half[1] = vehicle.half[1]\n box.half[2] = vehicle.half[2] + rules.margin + reach\n centre[0] = pose[0]! + direction[0] * reach\n centre[1] = pose[1]!\n centre[2] = pose[2]! + direction[1] * reach\n for (let k = 0; k < 4; k++) rotation[k] = pose[3 + k]!\n point[1] = pose[1]!\n if (world.overlapShape(box, centre, rotation as Quat, hits, { layers: ['agent'] }) === 0) {\n struck.delete(vehicle)\n return\n }\n car.speed = speed\n car.mass = world.massOf(vehicle.body)\n let before = struck.get(vehicle)\n if (!before) {\n before = new Set<number>()\n struck.set(vehicle, before)\n }\n for (const index of agentsOf(hits)) {\n const identity = crowd.store.identity[index]!\n if (before.has(identity)) {\n now.add(identity)\n continue\n }\n point[0] = crowd.store.x[index]!\n point[2] = crowd.store.z[index]!\n const outcome = hitOne(vehicle, index, direction, car, h)\n if (outcome === 'push') continue\n now.add(identity)\n if (outcome !== undefined) isIndexStale = true\n }\n before.clear()\n for (const identity of now) before.add(identity)\n now.clear()\n }\n\n const beforeStep = (h: number): void => {\n isIndexStale = true\n for (const vehicle of vehicles) sweep(vehicle, h)\n }\n\n const removePhase = loop.add({ beforeStep }, 'actors')\n return {\n track: (vehicle) => {\n vehicles.push(vehicle)\n return () => {\n const at = vehicles.indexOf(vehicle)\n if (at >= 0) vehicles.splice(at, 1)\n struck.delete(vehicle)\n }\n },\n get dyingVelocity() {\n return dying\n },\n dispose: () => {\n removePhase()\n vehicles.length = 0\n struck.clear()\n },\n }\n}\n"],"mappings":";AAoEO,IAAM,oBAAgC;AAAA,EAC3C,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,OAAO;AAAA,EACP,oBAAoB;AAAA,EACpB,cAAc;AAAA,EACd,MAAM;AAAA,EACN,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,UAAU;AAAA,EACV,eAAe;AAAA,EACf,WAAW;AAAA,EACX,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,wBAAwB;AAAA,EACxB,iBAAiB;AAAA,EACjB,OAAO,EAAE,UAAU,KAAK,aAAa,GAAG,QAAQ,GAAG,cAAc,IAAI,WAAW,GAAG,YAAY,KAAK,QAAQ,OAAO,aAAa,GAAG;AAAA,EACnI,SAAS,EAAE,YAAY,GAAG,WAAW,GAAG,aAAa,KAAK,aAAa,KAAK,aAAa,KAAK,UAAU,GAAG,WAAW,MAAM,mBAAmB,GAAG,UAAU,KAAK,QAAQ,IAAI;AAC/K;AAKO,SAAS,eAAe,MAA4C,GAAW,GAAW,KAAsC;AACrI,QAAM,IAAI,KAAK,IAAI,GAAG;AACtB,QAAM,IAAI,KAAK,IAAI,GAAG;AACtB,QAAM,KAAK,KAAK,SAAS;AACzB,QAAM,KAAK,KAAK,QAAQ;AACxB,QAAM,MAA+B,CAAC;AACtC,aAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,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,SAAO;AAAA,IACL,OAAO,CAAC,YAAY;AAClB,eAAS,KAAK,OAAO;AACrB,aAAO,MAAM;AACX,cAAM,KAAK,SAAS,QAAQ,OAAO;AACnC,YAAI,MAAM,EAAG,UAAS,OAAO,IAAI,CAAC;AAClC,eAAO,OAAO,OAAO;AAAA,MACvB;AAAA,IACF;AAAA,IACA,IAAI,gBAAgB;AAClB,aAAO;AAAA,IACT;AAAA,IACA,SAAS,MAAM;AACb,kBAAY;AACZ,eAAS,SAAS;AAClB,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AACF;","names":["sp","clamp","command","clamp","clamp","clamp","side","clamp","GRAVITY","direction","car"]}
1
+ {"version":3,"sources":["../src/arcade.ts","../src/run-over.ts","../src/semi/fuel.ts","../src/semi/surfaces.ts","../src/semi/driver.ts","../src/semi/impact.ts","../src/semi/vehicle-type.ts","../src/semi/from-stats.ts","../src/driving-aids.ts","../src/controls.ts","../src/semi/condition.ts","../src/systems.ts","../src/ejection.ts","../src/parking-sensor.ts","../src/storage.ts","../src/windshield-fog.ts","../src/physics-desc.ts","../src/physics-input.ts","../src/physics-resistance.ts","../src/physics-run-over.ts"],"sourcesContent":["import type { DriveInput, Driver, DriverState, DrivingEvent, DrivingWorld, StepResult } from './types'\n\nexport interface RunOverRules {\n /** Above this speed (m/s) a body is knocked down. */\n knockSpeed: number\n /** Above this speed a body is killed. */\n killSpeed: number\n /** Knock damage is `speed² * knockDamage`. */\n knockDamage: number\n /** Seconds a knocked body is stunned. */\n stunSeconds: number\n /** Fraction of the vehicle speed given to a knocked body. */\n throwFactor: number\n /** Sideways speed added to a knocked body. */\n sideKick: number\n /** The vehicle keeps this fraction of its speed after knocking a body. */\n knockSlow: number\n /** Damage the vehicle takes for each body killed. */\n killVehicleDamage: number\n /** Below `knockSpeed` the vehicle slows by `exp(-holdDrag * dt)` for each body in the way. */\n holdDrag: number\n /** Metres added around the vehicle's footprint when testing a body. */\n margin: number\n}\n\nexport interface CrashRules {\n /** Below this speed an impact is only a bump (no event, but the vehicle still bounces). */\n minSpeed: number\n /** Above this speed the impact damages the vehicle by `speed * damage`. */\n damageSpeed: number\n damage: number\n /** Camera shake is `speed / shakeDivisor`. */\n shakeDivisor: number\n /** Above this speed the driver is hurt by `speed * hurtFactor`. */\n hurtSpeed: number\n hurtFactor: number\n /** The speed after an impact is `v * bounce`. */\n bounce: number\n noiseRadius: number\n}\n\n/** The numbers of the game's drivable car (G 70188-70290). Every one is an option. */\nexport interface ArcadeSpec {\n length: number\n width: number\n accel: number\n /** Deceleration when accelerating against a reverse move, or braking against a forward move. */\n brakeAgainstMotion: number\n reverseAccel: number\n /** Coasting drag: `v *= exp(-drag * dt)`. */\n drag: number\n handbrakeDrag: number\n maxForward: number\n maxReverse: number\n /** Largest steering angle, radians. */\n steerMax: number\n /** The steering angle follows its target by `min(1, steerResponse * dt)`. */\n steerResponse: number\n /** Distance used in `yaw += steer * v / wheelbase * dt`. */\n wheelbase: number\n engineNoiseInterval: number\n engineNoiseBase: number\n engineNoiseSpeedFactor: number\n hornNoiseRadius: number\n crash: CrashRules\n runOver: RunOverRules\n}\n\nexport const defaultArcadeSpec: ArcadeSpec = {\n length: 4.3,\n width: 1.9,\n accel: 5.5,\n brakeAgainstMotion: 12,\n reverseAccel: 3,\n drag: 0.5,\n handbrakeDrag: 3,\n maxForward: 17,\n maxReverse: -5,\n steerMax: 0.55,\n steerResponse: 5,\n wheelbase: 2.6,\n engineNoiseInterval: 0.5,\n engineNoiseBase: 25,\n engineNoiseSpeedFactor: 2,\n hornNoiseRadius: 120,\n crash: { minSpeed: 0.5, damageSpeed: 4, damage: 9, shakeDivisor: 20, hurtSpeed: 9, hurtFactor: 1.2, bounce: -0.25, noiseRadius: 25 },\n runOver: { knockSpeed: 3, killSpeed: 8, knockDamage: 2.5, stunSeconds: 1.4, throwFactor: 0.8, sideKick: 2, knockSlow: 0.93, killVehicleDamage: 3, holdDrag: 2.5, margin: 0.3 },\n}\n\nexport type ArcadeOptions = Partial<Omit<ArcadeSpec, 'crash' | 'runOver'>> & { crash?: Partial<CrashRules>; runOver?: Partial<RunOverRules> }\n\n/** The eight points the game tests for a wall: the four corners, the middle of the front and rear, and the middle of both sides. */\nexport function vehicleCorners(spec: Pick<ArcadeSpec, 'length' | 'width'>, x: number, z: number, yaw: number): Array<[number, number]> {\n const c = Math.cos(yaw)\n const s = Math.sin(yaw)\n const hl = spec.length / 2\n const hw = spec.width / 2\n const out: Array<[number, number]> = []\n for (const [a, b] of [[hl, hw], [hl, -hw], [-hl, hw], [-hl, -hw], [hl, 0], [-hl, 0], [0, hw], [0, -hw]] as const) out.push([x + a * c + b * s, z - a * s + b * c])\n return out\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\n/**\n * The arcade driver: the game's car, extracted. A pure step function over `DriverState`: no three.js, no game. Port of `carUpdate`\n * (jogo.js 70233-70290) with the same order of operations, so a scripted run gives the same positions and events.\n */\nexport function createArcadeDriver(options: ArcadeOptions = {}): Driver & { readonly spec: ArcadeSpec } {\n const spec: ArcadeSpec = {\n ...defaultArcadeSpec,\n ...options,\n crash: { ...defaultArcadeSpec.crash, ...(options.crash || {}) },\n runOver: { ...defaultArcadeSpec.runOver, ...(options.runOver || {}) },\n }\n const state: DriverState = { x: 0, z: 0, yaw: 0, v: 0, steer: 0, noiseTimer: 0 }\n\n const step = (input: DriveInput, dt: number, world: DrivingWorld): StepResult => {\n const events: DrivingEvent[] = []\n const f = (input.throttle > 0 ? 1 : 0) - (input.brake > 0 ? 1 : 0)\n if (f > 0) state.v += (state.v < 0 ? spec.brakeAgainstMotion : spec.accel) * dt * Math.min(1, input.throttle)\n else if (f < 0) state.v -= (state.v > 0 ? spec.brakeAgainstMotion : spec.reverseAccel) * dt * Math.min(1, input.brake)\n else state.v *= Math.exp(-spec.drag * dt)\n if (input.handbrake) state.v *= Math.exp(-spec.handbrakeDrag * dt)\n state.v = clamp(state.v, spec.maxReverse, spec.maxForward)\n state.steer = lerp(state.steer, clamp(input.steer, -1, 1) * spec.steerMax, Math.min(1, dt * spec.steerResponse))\n const nyaw = state.yaw + ((state.steer * state.v) / spec.wheelbase) * dt\n const fx = Math.cos(nyaw)\n const fz = -Math.sin(nyaw)\n const nx = state.x + fx * state.v * dt\n const nz = state.z + fz * state.v * dt\n if (!world.blocked(nx, nz, nyaw)) {\n state.x = nx\n state.z = nz\n state.yaw = nyaw\n } else if (Math.abs(state.v) > spec.crash.minSpeed) {\n const sp = Math.abs(state.v)\n if (sp > spec.crash.damageSpeed) {\n events.push({ type: 'crash', speed: sp, damage: sp * spec.crash.damage, shake: sp / spec.crash.shakeDivisor, hurtDriver: sp > spec.crash.hurtSpeed ? sp * spec.crash.hurtFactor : 0 })\n events.push({ type: 'noise', radius: spec.crash.noiseRadius, x: state.x, z: state.z, source: 'crash' })\n }\n state.v *= spec.crash.bounce\n }\n // run-over: speed is read once, before the loop, as the game does\n const sp = Math.abs(state.v)\n const ro = spec.runOver\n const bodies = world.bodies ? world.bodies() : []\n for (let i = 0; i < bodies.length; i++) {\n const body = bodies[i]\n if (!body) continue\n const dx = body.x - state.x\n const dz = body.z - state.z\n const a = dx * fx + dz * fz\n const b = -dx * fz + dz * fx\n if (Math.abs(a) > spec.length / 2 + ro.margin || Math.abs(b) > spec.width / 2 + ro.margin) continue\n if (sp > ro.killSpeed) events.push({ type: 'run_over', outcome: 'kill', index: i, speed: sp, vehicleDamage: ro.killVehicleDamage })\n else if (sp > ro.knockSpeed) {\n events.push({\n type: 'run_over',\n outcome: 'knock',\n index: i,\n speed: sp,\n damage: sp * sp * ro.knockDamage,\n stunSeconds: ro.stunSeconds,\n vx: fx * sp * ro.throwFactor + (b > 0 ? -fz : fz) * ro.sideKick,\n vz: fz * sp * ro.throwFactor + (b > 0 ? fx : -fx) * ro.sideKick,\n slow: ro.knockSlow,\n })\n state.v *= ro.knockSlow\n } else {\n state.v *= Math.exp(-ro.holdDrag * dt)\n events.push({ type: 'run_over', outcome: 'push', index: i, speed: sp, dx: (b > 0 ? -fz : fz) * dt, dz: (b > 0 ? fx : -fx) * dt })\n }\n }\n state.noiseTimer -= dt\n if (state.noiseTimer <= 0) {\n state.noiseTimer = spec.engineNoiseInterval\n events.push({ type: 'noise', radius: spec.engineNoiseBase + sp * spec.engineNoiseSpeedFactor, x: state.x, z: state.z, source: 'engine' })\n }\n if (input.horn) {\n events.push({ type: 'noise', radius: spec.hornNoiseRadius, x: state.x, z: state.z, source: 'horn' })\n events.push({ type: 'horn' })\n }\n return { state, events }\n }\n\n return {\n spec,\n state,\n step,\n place(x, z, yaw) {\n state.x = x\n state.z = z\n state.yaw = yaw\n state.v = 0\n state.steer = 0\n },\n }\n}\n","import type { RunOverRules } from './arcade'\nimport { defaultArcadeSpec } from './arcade'\n\nexport type RunOverOutcome = 'push' | 'knock' | 'kill'\n\n/** What a vehicle moving at `speed` (m/s) does to a body it touches: pushes it (and is held), knocks it down, or kills it. */\nexport function runOver(speed: number, rules: Partial<RunOverRules> = {}): RunOverOutcome {\n const { knockSpeed, killSpeed } = { ...defaultArcadeSpec.runOver, ...rules }\n const s = Math.abs(speed)\n return s > killSpeed ? 'kill' : s > knockSpeed ? 'knock' : 'push'\n}\n","export interface FuelModel {\n /** Litres per second at idle. */\n idleRate: number\n /** Extra litres per second at full throttle and redline. */\n fullRate: number\n /** Extra consumption per unit of cargo mass over the vehicle's own mass (0.5 = +50% when the load equals the vehicle). */\n loadFactor: number\n /** Extra consumption of a wrecked engine (0.4 = up to +40% at zero health). */\n damagedEngineExtra: number\n}\n\nexport const defaultFuelModel: FuelModel = { idleRate: 0.0003, fullRate: 0.0035, loadFactor: 0.5, damagedEngineExtra: 0.4 }\n\n/**\n * Litres per second: it depends on the RPM, the throttle, the weight of the cargo and the state of the engine\n * (Frota document, section 04: \"a damaged engine spends up to 40% more\").\n */\nexport function fuelRate(model: FuelModel, rpmFraction: number, throttle: number, loadRatio: number, engineHealth: number): number {\n const base = model.idleRate + model.fullRate * Math.max(0, Math.min(1, rpmFraction)) * Math.max(0, Math.min(1, throttle))\n return base * (1 + model.loadFactor * Math.max(0, loadRatio)) * (1 + model.damagedEngineExtra * (1 - Math.max(0, Math.min(1, engineHealth))))\n}\n","import { applyPatches, mergeById, removeIds } from '@adatechnology/game-contracts'\n\n/** A kind of ground the tyres run on. */\nexport interface Surface {\n id: string\n /** Multiplier of the tyre grip (dry asphalt = 1). */\n grip: number\n /** Above this speed (km/h) the tyres float: grip drops linearly to `grip * aquaplaningFactor` over `aquaplaningBand` km/h. */\n aquaplaningKmh?: number\n aquaplaningFactor?: number\n aquaplaningBand?: number\n /** A vehicle without four-wheel drive sinks: its rolling resistance becomes the spec's `bogResistance`. */\n bogs?: boolean\n}\n\n/** The table of the Frota document, section 03 (Surfaces). Every number is a default a game can replace. */\nexport const defaultSurfaces: readonly Surface[] = [\n { id: 'dry_asphalt', grip: 1 },\n { id: 'wet_asphalt', grip: 0.75, aquaplaningKmh: 90, aquaplaningFactor: 0.4, aquaplaningBand: 30 },\n { id: 'dirt', grip: 0.65 },\n { id: 'grass', grip: 0.55 },\n { id: 'mud', grip: 0.4, bogs: true },\n /** Blood and bodies after a run-over; a driver applies it for a few seconds with `contaminate`. */\n { id: 'blood', grip: 0.5 },\n]\n\nexport interface SurfaceOptions {\n packs?: ReadonlyArray<{ surfaces?: readonly Surface[] }>\n patch?: Readonly<Record<string, Partial<Surface>>>\n remove?: readonly string[]\n}\n\nexport interface SurfaceRegistry {\n get(id: string): Surface\n readonly surfaces: readonly Surface[]\n}\n\n/** The registry of surfaces: the document's table, plus packs, patches and removals by id. An unknown id falls back to dry asphalt. */\nexport function createSurfaces(options: SurfaceOptions = {}): SurfaceRegistry {\n const entries = mergeById(defaultSurfaces, options.packs?.flatMap((pack) => pack.surfaces ?? []))\n applyPatches(entries, options.patch)\n removeIds(entries, options.remove)\n const fallback = entries.get('dry_asphalt') ?? ({ id: 'dry_asphalt', grip: 1 } as Surface)\n return {\n get: (id) => entries.get(id) ?? fallback,\n get surfaces() {\n return [...entries.values()]\n },\n }\n}\n\n/** Grip of a surface at a speed, with aquaplaning. */\nexport function surfaceGrip(surface: Surface, speedMetresPerSecond: number): number {\n if (surface.aquaplaningKmh == null) return surface.grip\n const kmh = Math.abs(speedMetresPerSecond) * 3.6\n const band = surface.aquaplaningBand ?? 30\n const t = Math.max(0, Math.min(1, (kmh - surface.aquaplaningKmh) / band))\n return surface.grip * (1 - (1 - (surface.aquaplaningFactor ?? 0.4)) * t)\n}\n","import type { Driver } from '../types'\nimport { fuelRate, defaultFuelModel } from './fuel'\nimport type { FuelModel } from './fuel'\nimport { createSurfaces, surfaceGrip } from './surfaces'\nimport type { SurfaceRegistry } from './surfaces'\nimport type { SemiEvent, SemiInput, SemiSimSpec, SemiState, SemiWorld, VehicleCondition } from './types'\n\nconst G = 9.81\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\nconst MAX_SUBSTEP = 1 / 240\nexport const FLAT_BELOW = 0.2\n/**\n * A wheel without its tyre (chosen by the physics of a bare rim on asphalt): the rim is about seven tenths of the wheel's radius (the sidewall is gone),\n * steel or aluminium sliding on asphalt holds about 0.4 of the load (rubber 1.05), and the flange gouging the road drags like a coefficient of 0.25\n * against the 0.015 of a tyre: the corner drops, grips less and brakes, so the car pulls to that side and loses speed. A flat tyre sags this much, metres,\n * and drags six times a whole one.\n */\nexport const RIM_RADIUS_SHARE = 0.7\nexport const RIM_FRICTION = 0.4\nconst RIM_ROLLING = 0.25\nexport const FLAT_SAG = 0.05\nconst FLAT_ROLLING = 6\nexport const STALL_HEALTH = 0.3\n/** Clutch: engaged past this share it drags the engine; below this share of the idle, with less gas than `STALL_GAS`, the engine dies. */\nconst CLUTCH_BITE = 0.7\nconst STALL_RPM = 0.5\nconst STALL_GAS = 0.35\n\n/** A mid-size passenger car, so a game can start from numbers that drive like a car. Every field can be replaced. */\nexport const defaultSemiSpec: SemiSimSpec = {\n mass: 1300,\n centreHeight: 0.5,\n wheels: [\n { x: 1.3, z: -0.75, steer: true },\n { x: 1.3, z: 0.75, steer: true },\n { x: -1.3, z: -0.75, drive: true, handbrake: true },\n { x: -1.3, z: 0.75, drive: true, handbrake: true },\n ],\n wheelRadius: 0.32,\n fourWheelDrive: false,\n drag: 0.4,\n rolling: 0.015,\n bogResistance: 0.3,\n maxSteer: 0.55,\n brakeForce: 14000,\n engine: { idleRpm: 900, peakRpm: 4200, redlineRpm: 6500, peakTorque: 220 },\n gears: [3.6, 2.2, 1.5, 1.1, 0.85],\n reverseRatio: 3.4,\n finalDrive: 3.7,\n efficiency: 0.85,\n upshiftFraction: 0.85,\n downshiftFraction: 0.35,\n suspension: { restLength: 0.4, spring: 32000, damper: 3200 },\n tyre: { friction: 1.05, corneringStiffness: 9 },\n tank: { capacity: 45 },\n}\n\nexport interface SemiSimOptions {\n surfaces?: SurfaceRegistry\n}\n\nexport interface SemiDriver extends Omit<Driver, 'step' | 'state'> {\n readonly spec: SemiSimSpec\n readonly state: SemiState\n condition: VehicleCondition\n /** Sets the load carried, kilograms; the mass, the wheel loads and the fuel use follow. */\n setCargo(kg: number): void\n /** A surface that overrides the ground under the wheels for `seconds` (blood after a run-over). */\n contaminate(surfaceId: string, seconds: number): void\n /** Fills the tank (litres). */\n refuel(litres: number): void\n step(input: SemiInput, dt: number, world?: SemiWorld): { state: SemiState; events: SemiEvent[] }\n}\n\nexport const torqueAt = (spec: SemiSimSpec, rpm: number): number => {\n const e = spec.engine\n if (rpm >= e.redlineRpm) return 0\n const t = rpm <= e.peakRpm ? 0.7 + 0.3 * clamp((rpm - e.idleRpm) / (e.peakRpm - e.idleRpm), 0, 1) : 1 - 0.4 * ((rpm - e.peakRpm) / (e.redlineRpm - e.peakRpm))\n return e.peakTorque * t\n}\n\n/**\n * The semi-simulation driver (Frota document, section 03): a single rigid body with a low centre of mass, a spring and damper on each wheel\n * measured against the ground under it, separate longitudinal and lateral tyre forces inside a friction circle, an automatic gearbox with a\n * simulated RPM, a handbrake that locks the rear wheels, surfaces with their grip, and damage that changes how it drives. No team code exists\n * for it: the numbers are the document's and the tests check them.\n */\n/** Sliding friction of a locked tyre against its rolling grip, and how much of its side grip is left. */\nconst SLIDING_GRIP = 0.75\nconst LOCKED_STEER = 0.15\n/** Brakes: air temperature, where they start to fade and where only `BRAKE_FADED` of their force is left, joules per °C per kg of vehicle, cooling time. */\nconst AMBIENT_C = 25\nconst BRAKE_FADE_FROM_C = 350\nconst BRAKE_FADE_TO_C = 650\nconst BRAKE_FADED = 0.5\nconst BRAKE_HEAT_CAPACITY = 3\nconst BRAKE_COOL_S = 60\n\nexport function createSemiSimDriver(specification: Partial<SemiSimSpec> = {}, options: SemiSimOptions = {}): SemiDriver {\n const spec: SemiSimSpec = { ...defaultSemiSpec, ...specification }\n const surfaces = options.surfaces ?? createSurfaces()\n const fuelModel: FuelModel = { ...defaultFuelModel, ...spec.tank }\n const wheelbase = Math.max(...spec.wheels.map((w) => w.x)) - Math.min(...spec.wheels.map((w) => w.x))\n const track = Math.max(...spec.wheels.map((w) => w.z)) - Math.min(...spec.wheels.map((w) => w.z))\n const baseMass = spec.mass\n let cargo = 0\n let contamination: { id: string; left: number } | null = null\n const n = spec.wheels.length\n const state: SemiState = {\n x: 0,\n z: 0,\n yaw: 0,\n u: 0,\n w: 0,\n yawRate: 0,\n height: spec.suspension.restLength + spec.wheelRadius - (spec.mass * G) / (specification.wheels ? specification.wheels.length : defaultSemiSpec.wheels.length) / spec.suspension.spring,\n heightRate: 0,\n pitch: 0,\n pitchRate: 0,\n roll: 0,\n rollRate: 0,\n rpm: spec.engine.idleRpm,\n gear: 1,\n engineOn: true,\n bogged: false,\n fuel: spec.tank.capacity,\n loads: new Array<number>(n).fill((baseMass * G) / n),\n slip: new Array<number>(n).fill(0),\n steerAngle: 0,\n }\n const driver: SemiDriver = {\n spec,\n state,\n condition: {},\n setCargo(kg) {\n cargo = Math.max(0, kg)\n },\n contaminate(surfaceId, seconds) {\n contamination = { id: surfaceId, left: seconds }\n },\n refuel(litres) {\n state.fuel = Math.min(spec.tank.capacity, state.fuel + litres)\n },\n place(x, z, yaw) {\n state.x = x\n state.z = z\n state.yaw = yaw\n state.u = state.w = state.yawRate = 0\n },\n step(input, dt, world = {}) {\n const events: SemiEvent[] = []\n const steps = Math.max(1, Math.ceil(dt / MAX_SUBSTEP))\n const h = dt / steps\n for (let s = 0; s < steps; s++) substep(input, h, world, events)\n return { state, events }\n },\n }\n\n const stallWatch = { throttleTime: 0 }\n\n function substep(input: SemiInput, dt: number, world: SemiWorld, events: SemiEvent[]): void {\n const cond = driver.condition\n const mass = baseMass + cargo\n const engineHealth = clamp(cond.engine ?? 1, 0, 1)\n const suspensionHealth = clamp(cond.suspension ?? 1, 0, 1)\n const brakeHealth = clamp(cond.brakes ?? 1, 0, 1)\n const inertia = (spec.yawInertia ?? (baseMass * (wheelbase * wheelbase + track * track)) / 12) * (mass / baseMass)\n const pitchInertia = (mass * (wheelbase * wheelbase + 1)) / 12\n const rollInertia = (mass * (track * track + 1)) / 12\n if (contamination) {\n contamination.left -= dt\n if (contamination.left <= 0) contamination = null\n }\n const cs = Math.cos(state.yaw)\n const sn = Math.sin(state.yaw)\n // steering: the front wheels follow the input, slower when fast (the wheel angle limit shrinks a little)\n const target = clamp(input.steer, -1, 1) * spec.maxSteer\n state.steerAngle += (target - state.steerAngle) * Math.min(1, dt * 8)\n // gearbox: automatic by default. From a stop, the brake reverses and the throttle goes forward again.\n let gear = state.gear\n if (input.gear != null) gear = input.gear\n else if (state.u < 0.5 && input.brake > 0 && input.throttle <= 0) gear = -1\n else if (gear <= 0 && !(gear === -1 && state.u < 0.5 && input.throttle <= 0)) gear = 1\n const ratioOf = (g: number): number => (g < 0 ? spec.reverseRatio : g === 0 ? 0 : (spec.gears[g - 1] as number))\n const driveWheels = spec.wheels.map((w, i) => ({ w, i })).filter(({ w }) => (spec.fourWheelDrive ? true : w.drive))\n // the wheel speed that drives the engine: mean longitudinal speed of the driven wheels / radius\n let driveSpeed = 0\n for (const { w } of driveWheels) driveSpeed += state.u + state.yawRate * w.z\n driveSpeed /= Math.max(1, driveWheels.length)\n const wheelRpm = (Math.abs(driveSpeed) / spec.wheelRadius) * (60 / (2 * Math.PI))\n if (input.gear == null && gear > 0) {\n if (wheelRpm * ratioOf(gear) * spec.finalDrive > spec.engine.redlineRpm * spec.upshiftFraction && gear < spec.gears.length) gear++\n else if (gear > 1 && wheelRpm * ratioOf(gear) * spec.finalDrive < spec.engine.redlineRpm * spec.downshiftFraction) gear--\n }\n if (gear !== state.gear) {\n state.gear = gear\n events.push({ type: 'shift', gear })\n }\n const reversing = state.gear < 0\n const accelInput = reversing ? input.brake : input.throttle\n const brakeInput = clamp(reversing ? input.throttle : input.brake, 0, 1)\n const ratio = ratioOf(state.gear) * spec.finalDrive\n // the clutch: pressed it frees the engine from the wheels; released in gear below about half the idle it drags the engine down\n const engaged = input.clutch == null || state.gear === 0 ? 1 : 1 - clamp(input.clutch, 0, 1)\n const coupled = wheelRpm * ratio\n const free = spec.engine.idleRpm + clamp(accelInput, 0, 1) * (spec.engine.redlineRpm * 0.7 - spec.engine.idleRpm)\n state.rpm = clamp(coupled * engaged + Math.max(coupled, free) * (1 - engaged), spec.engine.idleRpm, spec.engine.redlineRpm + 200)\n if (input.clutch != null && state.gear !== 0 && state.engineOn && engaged > CLUTCH_BITE && coupled < spec.engine.idleRpm * STALL_RPM && accelInput < STALL_GAS) {\n state.engineOn = false\n events.push({ type: 'stall' })\n }\n if (!state.engineOn || state.fuel <= 0) state.rpm = 0\n // engine torque: a wrecked engine fails to deliver at full throttle, and under 30% it can die uphill\n let throttle = clamp(accelInput, 0, 1)\n if (engineHealth < STALL_HEALTH && throttle > 0.8) {\n stallWatch.throttleTime += dt\n if (state.pitch > 0.06 && stallWatch.throttleTime > 0.5 && state.engineOn) {\n state.engineOn = false\n events.push({ type: 'stall' })\n }\n throttle *= 0.5\n } else stallWatch.throttleTime = 0\n const starting = input.start ?? (accelInput > 0 && Math.abs(state.u) < 0.5)\n if (!state.engineOn && starting && engineHealth >= STALL_HEALTH && state.fuel > 0) state.engineOn = true\n if (state.fuel <= 0 && state.engineOn) {\n state.engineOn = false\n events.push({ type: 'out_of_fuel' })\n }\n const engineTorque = state.engineOn ? torqueAt(spec, state.rpm) * throttle * (0.55 + 0.45 * engineHealth) * clamp(input.powerLimit ?? 1, 0, 1) * engaged : 0\n const driveForceTotal = state.gear === 0 ? 0 : ((reversing ? -1 : 1) * engineTorque * ratio * spec.efficiency) / spec.wheelRadius\n // fuel\n if (state.engineOn) {\n const burned = fuelRate(fuelModel, state.rpm / spec.engine.redlineRpm, throttle, cargo / baseMass, engineHealth) * dt\n state.fuel = Math.max(0, state.fuel - burned)\n }\n\n // ground under each wheel, and the suspension\n const ride = spec.suspension.restLength\n let sumN = 0\n let sumNA = 0\n let sumNB = 0\n const wheelState: Array<{ n: number; grip: number; surface: string; bog: boolean; flat: boolean; rim: boolean }> = []\n let bogging = false\n for (let i = 0; i < n; i++) {\n const w = spec.wheels[i] as (typeof spec.wheels)[number]\n const wx = state.x + w.x * cs + w.z * sn\n const wz = state.z - w.x * sn + w.z * cs\n const ground = world.ground ? world.ground(wx, wz) : {}\n const surface = surfaces.get(contamination && contamination.left > 0 && surfaces.get(contamination.id).grip < surfaces.get(ground.surface ?? 'dry_asphalt').grip ? contamination.id : (ground.surface ?? 'dry_asphalt'))\n const tyreHealth = cond.tyres ? clamp(cond.tyres[i] ?? 1, 0, 1) : 1\n const rim = !!cond.rims?.[i]\n const flat = rim || tyreHealth < FLAT_BELOW\n const radius = rim ? (spec.rimRadius ?? spec.wheelRadius * RIM_RADIUS_SHARE) : flat ? spec.wheelRadius - FLAT_SAG : spec.wheelRadius\n const top = state.height + w.x * state.pitch - w.z * state.roll\n const length = top - (ground.height ?? 0) - radius\n const compression = ride - length\n const rate = -(state.heightRate + w.x * state.pitchRate - w.z * state.rollRate)\n const k = spec.suspension.spring * (0.5 + 0.5 * suspensionHealth)\n const c = spec.suspension.damper * (0.5 + 0.5 * suspensionHealth)\n const load = Math.max(0, k * compression + c * rate)\n const bog = !!surface.bogs && !spec.fourWheelDrive\n if (bog) bogging = true\n const grip = surfaceGrip(surface, state.u) * (rim ? RIM_FRICTION / spec.tyre.friction : flat ? 0.5 : 1)\n wheelState.push({ n: load, grip, surface: surface.id, bog, flat, rim })\n sumN += load\n sumNA += load * w.x\n sumNB += load * w.z\n }\n // brakes fade as they heat up from hard stops, and cool down in the air\n const brakeHeat = state.brakeHeat ?? AMBIENT_C\n const fade = 1 - clamp((brakeHeat - BRAKE_FADE_FROM_C) / (BRAKE_FADE_TO_C - BRAKE_FADE_FROM_C), 0, 1) * (1 - BRAKE_FADED)\n let brakeWork = 0\n // forces on the ground, per wheel\n let fFwd = 0\n let fRight = 0\n let torque = 0\n let pitchTorque = 0\n let rollTorque = 0\n const handbrake = !!input.handbrake\n const loadSum = Math.max(1, wheelState.reduce((a, b) => a + b.n, 0))\n const drivenCount = Math.max(1, driveWheels.length)\n for (let i = 0; i < n; i++) {\n const w = spec.wheels[i] as (typeof spec.wheels)[number]\n const ws = wheelState[i] as (typeof wheelState)[number]\n const delta = w.steer ? state.steerAngle : 0\n const cd = Math.cos(delta)\n const sd = Math.sin(delta)\n const vxw = state.u + state.yawRate * w.z\n const vyw = state.w - state.yawRate * w.x\n const vl = vxw * cd - vyw * sd\n const vc = vxw * sd + vyw * cd\n const capacity = spec.tyre.friction * ws.grip * ws.n\n // longitudinal request: drive, brake, rolling and handbrake lock\n let fl = 0\n if (driveWheels.some((d) => d.i === i)) fl += driveForceTotal / drivenCount\n const locked = handbrake && w.handbrake\n const brakeShare = (spec.brakeForce * brakeHealth * fade * brakeInput * ws.n) / loadSum\n const moving = Math.abs(vl) > 0.05\n // without ABS a brake asking more than the tyre holds locks the wheel: it slides on less grip and steers no more\n const lockedByBrake = spec.abs === false && moving && brakeShare > capacity\n if (locked || lockedByBrake) fl += moving ? -Math.sign(vl) * capacity * (lockedByBrake ? SLIDING_GRIP : 1) : 0\n else if (brakeShare > 0 && moving) fl += -Math.sign(vl) * brakeShare\n if (brakeShare > 0 && moving) brakeWork += Math.min(brakeShare, capacity) * Math.abs(vl) * dt\n const rolling = ws.bog && accelInput > 0 ? spec.bogResistance : ws.rim ? RIM_ROLLING : spec.rolling * (ws.flat ? FLAT_ROLLING : 1)\n // lateral: slip angle into a saturating curve, separate from the longitudinal one\n const alpha = Math.atan2(vc, Math.abs(vl) + 0.5)\n let fc = -Math.tanh((spec.tyre.corneringStiffness * alpha)) * capacity\n if (locked) fc *= 0.6\n if (lockedByBrake) fc *= LOCKED_STEER\n // friction circle\n const total = Math.hypot(fl, fc)\n let used = 1\n if (total > capacity && total > 0) used = capacity / total\n fl *= used\n fc *= used\n // rolling resistance is the ground's, not the tyre's: it is not limited by the friction circle\n if (moving) fl += -Math.sign(vl) * rolling * ws.n\n const slipRatio = capacity > 0 ? clamp(total / capacity, 0, 1) : 0\n state.slip[i] = slipRatio\n if (ws.surface === 'wet_asphalt' && Math.abs(state.u) * 3.6 > (surfaces.get(ws.surface).aquaplaningKmh ?? 1e9) && slipRatio >= 0.99) events.push({ type: 'aquaplaning', wheel: i })\n // to the body\n const fx = fl * cd + fc * sd\n const fy = -fl * sd + fc * cd\n fFwd += fx\n fRight += fy\n torque += w.z * fx - w.x * fy\n pitchTorque += fx * spec.centreHeight\n rollTorque += -fy * spec.centreHeight\n }\n const bogNow = bogging && Math.abs(state.u) < 1 && accelInput > 0\n if (bogNow && !state.bogged) events.push({ type: 'bogged' })\n state.bogged = bogNow\n state.brakeHeat = brakeHeat + brakeWork / (baseMass * BRAKE_HEAT_CAPACITY) - (brakeHeat - AMBIENT_C) * Math.min(1, dt / BRAKE_COOL_S)\n // air drag\n fFwd += -spec.drag * state.u * Math.abs(state.u)\n fRight += -spec.drag * state.w * Math.abs(state.w)\n // planar integration in the body frame\n const du = fFwd / mass - state.yawRate * state.w\n const dw = fRight / mass + state.yawRate * state.u\n state.u += du * dt\n state.w += dw * dt\n // a stopped vehicle does not creep: the sticking friction holds it\n if (Math.abs(state.u) < 0.02 && accelInput <= 0) state.u = 0\n state.yawRate += (torque / inertia) * dt\n state.yaw += state.yawRate * dt\n const csn = Math.cos(state.yaw)\n const snn = Math.sin(state.yaw)\n state.x += (state.u * csn + state.w * snn) * dt\n state.z += (-state.u * snn + state.w * csn) * dt\n // vertical, pitch and roll from the wheel loads\n const ay = (sumN - mass * G) / mass\n state.heightRate += ay * dt\n state.height += state.heightRate * dt\n state.pitchRate += ((sumNA + pitchTorque) / pitchInertia) * dt\n state.pitch += state.pitchRate * dt\n state.rollRate += ((-sumNB + rollTorque) / rollInertia) * dt\n state.roll += state.rollRate * dt\n for (let i = 0; i < n; i++) state.loads[i] = (wheelState[i] as (typeof wheelState)[number]).n\n }\n\n return driver\n}\n","/** Kinetic energy of a vehicle against a body: `0.5 * mass * speed²` (joules, with kg and m/s). Frota document, section 08. */\nexport const impactEnergy = (vehicleMass: number, relativeSpeed: number): number => 0.5 * vehicleMass * relativeSpeed * relativeSpeed\n\n/** Damage to the body that was hit: `energy * bumperMultiplier * zoneFactor`. The zone factors (head, torso, legs) belong to the game. */\nexport const bodyDamage = (energy: number, bumperMultiplier: number, zoneFactor: number): number => energy * bumperMultiplier * zoneFactor\n\n/** Damage to the vehicle: `energy * 0.04 * (1 - frontArmor)`, with the armour from 0 to 1. */\nexport const vehicleDamageFromImpact = (energy: number, frontArmor: number, factor = 0.04): number => energy * factor * (1 - frontArmor)\n\n/** Speed the vehicle loses: `bodyMass / (vehicleMass + bodyMass) * speed`. */\nexport const speedLoss = (bodyMass: number, vehicleMass: number, speed: number): number => (bodyMass / (vehicleMass + bodyMass)) * speed\n","import type { SemiPedal, SemiSimSpec, SemiTracks, SemiWheel } from './types'\n\n/** What a vehicle is built as: the wheels it has, the engine and gearbox it carries, how it is driven. A car when a body says nothing. */\nexport type VehicleType = 'car' | 'motorcycle' | 'bicycle' | 'truck' | 'tractor' | 'tracked'\n\n/** One axle as the model has it: metres ahead of the middle of the vehicle, the distance between its outer wheels (0 for a single wheel) and the radius of its tyres. */\nexport interface AxleDimensions {\n readonly x: number\n readonly track: number\n readonly radius: number\n}\n\n/** The tracks as the model has them (x ahead of the middle of the vehicle). */\nexport interface TrackDimensions {\n readonly gauge: number\n readonly rearX: number\n readonly frontX: number\n readonly roadWheels: number\n readonly radius: number\n}\n\n/** A cyclist sustains this much: the middle of the 150-400 W range of design 14.2 (specs/008-motor-fisico-jolt/design/veiculos.md), at the cadence and with the gears of the T6.2 bicycle test. */\nexport const CYCLIST: SemiPedal = { watts: 250, cadenceRpm: 80, gears: [1.5, 2.5, 3.5] }\n\n/** The engine and gearbox a type carries (five gears at most: the physics engine's automatic gearbox stops upshifting with six, measured on the scooter in specs/008 evidence T6.2c): the speeds the engine turns at, the gears below the top one (the top gear is set by the top speed) and the final drive. */\nexport interface TypeDrivetrain {\n readonly engine: Pick<SemiSimSpec['engine'], 'idleRpm' | 'peakRpm' | 'redlineRpm'>\n readonly gears: readonly number[]\n readonly finalDrive: number\n readonly efficiency: number\n /** The ratio between neighbouring gears from the top gear down: the steps of the box. */\n readonly step: number\n /** Share of the redline the engine turns at in the top gear at the top speed: the rest is headroom for the tyre's slip (a slipping wheel spins the engine past the limiter). */\n readonly topShare: number\n /** Shifts, shares of the redline. */\n readonly upshift: number\n readonly downshift: number\n}\n\nconst MOTORCYCLE: TypeDrivetrain = { engine: { idleRpm: 1300, peakRpm: 7500, redlineRpm: 10000 }, gears: [2.8, 2.0, 1.5, 1.2, 1.0], finalDrive: 3, efficiency: 0.9, step: 1.25, topShare: 0.8, upshift: 0.6, downshift: 0.3 }\nconst TRUCK: TypeDrivetrain = { engine: { idleRpm: 600, peakRpm: 1500, redlineRpm: 2500 }, gears: [7, 4.7, 3.2, 2.2, 1.5], finalDrive: 4.5, efficiency: 0.85, step: 1.5, topShare: 0.95, upshift: 0.85, downshift: 0.35 }\nconst TRACTOR: TypeDrivetrain = { engine: { idleRpm: 800, peakRpm: 1600, redlineRpm: 2300 }, gears: [7, 4.7, 3.2, 2.2, 1.5], finalDrive: 4.5, efficiency: 0.85, step: 1.5, topShare: 0.95, upshift: 0.85, downshift: 0.35 }\nconst TRACKED: TypeDrivetrain = { engine: { idleRpm: 600, peakRpm: 1500, redlineRpm: 2500 }, gears: [7, 4.7, 3.2, 2.2, 1.5], finalDrive: 4.5, efficiency: 0.85, step: 1.5, topShare: 0.95, upshift: 0.85, downshift: 0.35 }\n\n/** The drivetrain of a type; undefined for a car (the semi-simulation's own defaults) and a bicycle (the cyclist). */\nexport const drivetrainOfType = (type: VehicleType): TypeDrivetrain | undefined => {\n if (type === 'motorcycle') return MOTORCYCLE\n if (type === 'truck') return TRUCK\n if (type === 'tractor') return TRACTOR\n if (type === 'tracked') return TRACKED\n return undefined\n}\n\n/** A two-wheeler has no track: a single wheel on the centre line per axle. */\nexport const isTwoWheeler = (type: VehicleType): boolean => type === 'motorcycle' || type === 'bicycle'\n\nexport interface WheelPlanParams {\n readonly axles: readonly AxleDimensions[]\n readonly fourWheelDrive: boolean\n readonly twoWheeler: boolean\n}\n\n/** The wheels of a vehicle from its axles (front first): the front axle steers, the others drive unless all do, and the last one holds the handbrake. A bike drives its rear wheel only. */\nexport const wheelsOfAxles = ({ axles, fourWheelDrive, twoWheeler }: WheelPlanParams): SemiWheel[] => {\n const front = axles[0]!.x\n const rear = axles[axles.length - 1]!.x\n const middle = (front + rear) / 2\n return axles.flatMap((axle, index): SemiWheel[] => {\n const isFront = index === 0\n const isRear = index === axles.length - 1\n const common = { x: axle.x - middle, ...(isFront ? { steer: true } : {}), ...(isRear ? { handbrake: true } : {}) }\n const drive = twoWheeler ? isRear : fourWheelDrive || !isFront\n const wheel = (z: number): SemiWheel => ({ ...common, z, ...(drive ? { drive: true } : {}) })\n return axle.track > 0 ? [wheel(-axle.track / 2), wheel(axle.track / 2)] : [wheel(0)]\n })\n}\n\n/** The four-wheel stand-in of a tracked vehicle for the semi-simulation: two wheels a side at the ends of the track, the front pair steering. */\nexport const trackStandIn = (tracks: SemiTracks): SemiWheel[] => {\n const side = tracks.gauge / 2\n return [\n { x: tracks.frontX, z: -side, steer: true, drive: true },\n { x: tracks.frontX, z: side, steer: true, drive: true },\n { x: tracks.rearX, z: -side, drive: true, handbrake: true },\n { x: tracks.rearX, z: side, drive: true, handbrake: true },\n ]\n}\n\n/** The tracks of a body re-centred on the middle of the track run. */\nexport const tracksOfBody = (tracks: TrackDimensions): SemiTracks => {\n const middle = (tracks.frontX + tracks.rearX) / 2\n return { gauge: tracks.gauge, rearX: tracks.rearX - middle, frontX: tracks.frontX - middle, roadWheels: tracks.roadWheels, roadRadius: tracks.radius }\n}\n","import { defaultSemiSpec, torqueAt } from './driver'\nimport type { SemiPedal, SemiSimSpec } from './types'\nimport { CYCLIST, drivetrainOfType, isTwoWheeler, trackStandIn, tracksOfBody, wheelsOfAxles } from './vehicle-type'\nimport type { AxleDimensions, TrackDimensions, VehicleType } from './vehicle-type'\n\n/** The design ratings of a vehicle (the shape of `fleetStats` in `game-vehicles-fleet`; any object with these fields works). */\nexport interface DesignStats {\n /** 0-10. */\n acceleration: number\n /** 0-10. */\n handling: number\n maxSpeedKmh: number\n}\n\nexport interface BodyDimensions {\n mass: number\n wheelbase: number\n track: number\n fourWheelDrive?: boolean\n /** What it is built as (a car when omitted): the wheels, the engine, the gearbox and the controller come from the type. */\n type?: VehicleType\n /** The axles of the model, front first. Without them the vehicle has two, from `wheelbase` and `track` (a single wheel each for a two-wheeler). */\n axles?: readonly AxleDimensions[]\n /** A tracked vehicle's tracks. */\n tracks?: TrackDimensions\n}\n\n/** A motorcycle is simulated with its rider on (the real 0-100 km/h figures are measured with one): the mass of a rider, an assumption of the spec. */\nexport const RIDER_MASS_KG = 75\n\n/**\n * Power per kg of bike and rider by acceleration rating: the real power-to-weight of the two bikes that anchor the 0-100 km/h band of the class (`accelerationByClass.motorcycles`),\n * rating 1 the Honda PCX 160 (11.8 kW at 8 500 rpm, 132 kg: https://zigwheels.com/honda-bikes/pcx150/specifications) and rating 10 the Kawasaki Ninja 400 (33.4 kW at 10 000 rpm, 168 kg:\n * https://www.motorcyclespecs.co.za/model/kawasaki/kawasaki_ninja_400_21.html), linear in between.\n */\nconst MOTORCYCLE_POWER_RATING_1 = 11800 / (132 + RIDER_MASS_KG)\nconst MOTORCYCLE_POWER_RATING_10 = 33400 / (168 + RIDER_MASS_KG)\nconst motorcyclePower = (rating: number): number => MOTORCYCLE_POWER_RATING_1 + ((MOTORCYCLE_POWER_RATING_10 - MOTORCYCLE_POWER_RATING_1) * (rating - 1)) / 9\n\n/**\n * What the physics engine's cars and motorbikes get on top of the ficha's torque. The torque per kg was set against the semi-simulation, which has no rotating inertia (an engine and its wheels\n * turn as the vehicle speeds up), no gearshift that cuts the drive and no spinning wheel; the engine's vehicle has all three (its automatic gearbox cannot shift up while a driven wheel spins,\n * so first gear runs to the limiter) and took 1.2 to 1.8 times the semi-simulation's 0-100 km/h (evidence T6.2b, T6.2d). No source, calibrated by measurement (T6.2e replaces both with a gearbox of the adapter's own): the car's is the smallest scale that puts every\n * car, SUV, pickup, van and the quad inside its band; the motorbike's is the 1.3 the bikes were fitted to before (no source found for it) and keeps the ten bikes in their bands, a higher one tips them\n * over under braking. A vehicle with a real figure behind its power (the trucks, the tractor, the tracks) keeps 1.\n */\nexport const PHYSICS_TORQUE_SCALE = { car: 1.45, motorcycle: 1.3 } as const\n\n/** The default engine's power per kg at a rating: its torque per kg times its peak speed (unchanged for a car). */\nconst carPower = (rating: number): number => (0.06 + 0.015 * rating) * ((defaultSemiSpec.engine.peakRpm * 2 * Math.PI) / 60)\n\n/**\n * A main battle tank's power per kg (W/kg): the real figure of the Western MBTs, M1 Abrams 17.74 to 20.05 kW/t (1.12 MW: https://en.wikipedia.org/wiki/M1_Abrams) and Leopard 2A6 17.8 kW/t\n * (1.1 MW, 62.3 t: https://en.wikipedia.org/wiki/Leopard_2); the car's torque per kg gave the 41 t tank 52 kW/t. The top of the range: the physics engine's 41 t tank pivots from 20 kW/t up (not at 17.8).\n * Their 0-32 km/h is 6 to 7 s (weak sources: wikis and blogs); the tank here takes about 10 s to 52 km/h.\n */\nconst TRACKED_POWER = 20.05\n\nconst peakTorqueOf = (type: VehicleType, rating: number, mass: number, peakRpm: number): number => {\n const power = type === 'motorcycle' ? motorcyclePower(rating) : type === 'tracked' ? TRACKED_POWER : carPower(rating)\n return (mass * power * 60) / (2 * Math.PI * peakRpm)\n}\n\n/** The cyclist with a bicycle geared so that the top gear turns the cranks at his cadence at the top speed, the lower ones a step of 1.4 apart (wheel turns per crank turn). */\nconst cyclistFor = (top: number, wheelRadius: number): SemiPedal => {\n const topGear = top / (2 * Math.PI * wheelRadius) / (CYCLIST.cadenceRpm / 60)\n return { ...CYCLIST, gears: [topGear / 1.4 ** 2, topGear / 1.4, topGear] }\n}\n\nconst axlesOfBody = (body: BodyDimensions, twoWheeler: boolean): readonly AxleDimensions[] =>\n body.axles ?? [{ x: body.wheelbase / 2, track: twoWheeler ? 0 : body.track, radius: defaultSemiSpec.wheelRadius }, { x: -body.wheelbase / 2, track: twoWheeler ? 0 : body.track, radius: defaultSemiSpec.wheelRadius }]\n\n/** The radius the engine turns: the driven axles' tyres (every axle's when all drive, the rear one's on a bike). */\nconst drivenRadius = (axles: readonly AxleDimensions[], driveAll: boolean, twoWheeler: boolean): number => {\n const driven = twoWheeler ? axles.slice(-1) : driveAll ? axles : axles.slice(1)\n return driven.reduce((sum, axle) => sum + axle.radius, 0) / driven.length\n}\n\n/**\n * A semi-simulation spec from the design ratings and the body: the grip follows the handling, the torque follows the acceleration (a motorcycle's from its real power to weight), the air drag\n * is set so that the top gear tops out at the design top speed (a bicycle's from the cyclist's watts), and the brake force follows the mass. The `type` sets the wheels (two for a bike, one\n * pair per axle for the rest, the model's own when `axles` is given), the engine and the gearbox, and a tracked vehicle gets its tracks.\n */\nexport function semiSpecFromStats(stats: DesignStats, body: BodyDimensions, base: Partial<SemiSimSpec> = {}): SemiSimSpec {\n const type = body.type ?? 'car'\n const mass = body.mass + (type === 'motorcycle' ? RIDER_MASS_KG : 0)\n const twoWheeler = isTwoWheeler(type)\n const drivetrain = drivetrainOfType(type)\n const tracks = type === 'tracked' && body.tracks ? tracksOfBody(body.tracks) : undefined\n const axles = axlesOfBody(body, twoWheeler)\n const driveAll = !!body.fourWheelDrive\n const wheelRadius = tracks?.roadRadius ?? drivenRadius(axles, driveAll, twoWheeler)\n const spec: SemiSimSpec = {\n ...defaultSemiSpec,\n ...(drivetrain ? { engine: { ...defaultSemiSpec.engine, ...drivetrain.engine }, gears: drivetrain.gears, finalDrive: drivetrain.finalDrive, efficiency: drivetrain.efficiency, upshiftFraction: drivetrain.upshift, downshiftFraction: drivetrain.downshift } : {}),\n ...(type === 'bicycle' ? { finalDrive: 1, efficiency: 0.95 } : {}),\n wheelRadius,\n centreHeight: twoWheeler ? 0.6 : Math.max(defaultSemiSpec.centreHeight, wheelRadius + 0.1),\n ...base,\n }\n const wheels = tracks ? trackStandIn(tracks) : wheelsOfAxles({ axles, fourWheelDrive: driveAll, twoWheeler })\n const pedal = type === 'bicycle' ? cyclistFor(stats.maxSpeedKmh / 3.6, wheelRadius) : undefined\n const peakTorque = pedal ? (pedal.watts * 60) / (2 * Math.PI * pedal.cadenceRpm) : peakTorqueOf(type, stats.acceleration, mass, spec.engine.peakRpm)\n const engine = pedal ? { idleRpm: 40, peakRpm: pedal.cadenceRpm, redlineRpm: pedal.cadenceRpm * 1.5, peakTorque } : { ...spec.engine, peakTorque }\n const top = stats.maxSpeedKmh / 3.6\n // the last gear puts the redline at the top speed\n const topShare = drivetrain?.topShare ?? 0.95\n const lastRatio = (engine.redlineRpm * topShare * 2 * Math.PI * spec.wheelRadius) / (60 * top * spec.finalDrive)\n const stack = drivetrain?.gears ?? spec.gears\n const step = drivetrain?.step ?? 1.25\n const gears = pedal ? pedal.gears.map((ratio) => 1 / ratio) : [...stack.slice(0, -1).map((g, i, all) => Math.max(g, lastRatio * step ** (all.length - i))), lastRatio]\n // a car keeps the 0.76 of its first calibration; the other types use the torque their own curve gives at the speed the last gear puts the redline at\n const torqueAtTop = type === 'car' ? peakTorque * 0.76 : torqueAt({ ...spec, engine }, engine.redlineRpm * topShare)\n const topRatio = pedal ? gears[gears.length - 1]! : lastRatio\n // a cyclist's thrust at the top speed is the sustained power over the speed; an engine's is its torque there through the last gear\n const thrust = pedal ? (pedal.watts * spec.efficiency) / top : (torqueAtTop * topRatio * spec.finalDrive * spec.efficiency) / spec.wheelRadius\n const rollingForce = spec.rolling * mass * 9.81\n const drag = Math.max(0.01, (thrust - rollingForce) / (top * top))\n // the brakes grow with the mass, so a bus is not stopped by a hatch's brakes: the default car's ratio (about 1.1 g) up to 2 t, easing to the 0.6 g of a loaded truck or bus at 10 t (the tyres still cap it)\n const carRatio = defaultSemiSpec.brakeForce / (defaultSemiSpec.mass * 9.81)\n const heavyShare = Math.max(0, Math.min(1, (mass - 2000) / 8000))\n const brakeForce = base.brakeForce ?? mass * 9.81 * (carRatio + (0.6 - carRatio) * heavyShare)\n return {\n ...spec,\n mass,\n wheels,\n fourWheelDrive: driveAll,\n engine,\n gears,\n drag,\n brakeForce,\n ...(type === 'car' || type === 'motorcycle' ? { physicsTorqueScale: PHYSICS_TORQUE_SCALE[type] } : {}),\n tyre: { ...spec.tyre, friction: 0.8 + 0.03 * stats.handling },\n ...(pedal ? { pedal } : {}),\n ...(tracks ? { tracks } : {}),\n }\n}\n","/**\n * The driver aids the controls apply between the pedals and the engine: the drive profile (economy shifts early and softens the gas, sport holds the\n * gears and sharpens it), traction control (cuts the torque while a driven wheel spins past its grip) and cruise control (holds the set speed with the\n * gas; the brake or the clutch cancels it, the gas pedal overrides it while pressed). Pure functions over numbers, every threshold an option.\n */\nexport type DriveProfile = 'eco' | 'normal' | 'sport'\n\nexport interface ProfileTuning {\n /** Multiplies the gas pedal. */\n readonly throttle: number\n /** Upshift and downshift points, shares of the redline (the semi driver's `upshiftFraction` and `downshiftFraction`). */\n readonly upshift: number\n readonly downshift: number\n}\n\nexport const DRIVE_PROFILES: Readonly<Record<DriveProfile, ProfileTuning>> = {\n eco: { throttle: 0.7, upshift: 0.55, downshift: 0.25 },\n normal: { throttle: 1, upshift: 0.85, downshift: 0.35 },\n sport: { throttle: 1, upshift: 0.97, downshift: 0.55 },\n}\n\nexport interface TractionOptions {\n /** Grip in use of a driven wheel (1 = sliding) above which the torque is cut. */\n readonly slip: number\n /** Torque left at full spin. */\n readonly floor: number\n}\n\nexport const DEFAULT_TRACTION: TractionOptions = { slip: 0.97, floor: 0.35 }\n\n/** Share of the torque traction control lets through for the worst driven wheel's grip in use (1 = sliding). */\nexport function tractionLimit(slips: readonly number[], options: TractionOptions = DEFAULT_TRACTION): number {\n const worst = Math.max(0, ...slips)\n if (worst <= options.slip) return 1\n return Math.max(options.floor, 1 - (worst - options.slip) / (1 - options.slip))\n}\n\nexport interface CruiseOptions {\n /** Gas per m/s under the set speed. */\n readonly gain: number\n /** Lowest speed it engages at, m/s (about 30 km/h). */\n readonly minSpeed: number\n}\n\nexport const DEFAULT_CRUISE: CruiseOptions = { gain: 0.35, minSpeed: 8.3 }\n\n/** Gas cruise control asks for to hold `target` at `speed` (m/s); none above the target, the car coasts down to it. */\nexport function cruiseThrottle(target: number, speed: number, options: CruiseOptions = DEFAULT_CRUISE): number {\n return Math.max(0, Math.min(1, (target - speed) * options.gain + 0.12))\n}\n","/**\n * The controls of a vehicle someone drives: pedals (the clutch too), wheel, gearbox (automatic or manual), handbrake (held or pulled), ignition and\n * starter, drive mode (4x2, 4x4, automatic 4x4), drive profile (eco, normal, sport), traction control, ABS, cruise control, lamps (position, low,\n * high, flash, fog, interior), wipers and washer, climate and demister, horn, alarm and radio, the hotwire of a car without its key (the ignition key held\n * strips and joins the wires under the column), the siren and the beacon of an emergency vehicle, and the glovebox lid. It turns key codes into a `SemiInput` for the semi driver and keeps\n * what the cabin shows; it draws and plays nothing (an adapter reads `state` for the lamps and the sounds). Every key is an option.\n */\nimport { cruiseThrottle, DEFAULT_CRUISE, DRIVE_PROFILES, tractionLimit } from './driving-aids'\nimport type { DriveProfile } from './driving-aids'\nimport type { SemiInput } from './semi/types'\n\nexport type ControlCommand =\n | 'ignition'\n | 'gearbox'\n | 'gear_up'\n | 'gear_down'\n | 'parking_brake'\n | 'drive_mode'\n | 'lights'\n | 'high_beam'\n | 'fog_lights'\n | 'interior_light'\n | 'alarm'\n | 'radio'\n | 'radio_source'\n | 'radio_track'\n | 'exit'\n | 'indicator_left'\n | 'indicator_right'\n | 'hazard'\n | 'wipers'\n | 'seatbelt'\n | 'drive_profile'\n | 'traction_control'\n | 'abs'\n | 'cruise'\n | 'climate'\n | 'demist'\n | 'siren'\n | 'beacon'\n | 'glovebox'\n\nexport type ControlKeyMap = {\n readonly throttle: readonly string[]\n readonly brake: readonly string[]\n readonly left: readonly string[]\n readonly right: readonly string[]\n readonly handbrake: readonly string[]\n readonly horn: readonly string[]\n readonly clutch: readonly string[]\n /** Flashes the high beam while held. */\n readonly flash: readonly string[]\n readonly washer: readonly string[]\n /** Held without the key (`hasKey: false`): strips and joins the wires under the column until the engine turns over. */\n readonly hotwire: readonly string[]\n} & { readonly [command in ControlCommand]: readonly string[] }\n\n/** Keys of a keyboard (`KeyboardEvent.code`). The host keeps them from its own bindings while someone drives. */\nexport const DEFAULT_CONTROL_KEYS: ControlKeyMap = {\n throttle: ['KeyW', 'ArrowUp'],\n brake: ['KeyS', 'ArrowDown'],\n left: ['KeyA', 'ArrowLeft'],\n right: ['KeyD', 'ArrowRight'],\n handbrake: ['Space'],\n horn: ['KeyH'],\n clutch: ['KeyC'],\n flash: ['KeyX'],\n washer: ['KeyZ'],\n hotwire: ['KeyI'],\n ignition: ['KeyI'],\n gearbox: ['KeyM'],\n gear_up: ['KeyE'],\n gear_down: ['KeyQ'],\n parking_brake: ['KeyP'],\n drive_mode: ['KeyG'],\n lights: ['KeyL'],\n high_beam: ['KeyK'],\n fog_lights: ['KeyN'],\n interior_light: ['KeyU'],\n alarm: ['KeyY'],\n radio: ['KeyR'],\n radio_source: ['KeyT'],\n radio_track: ['BracketRight'],\n exit: ['KeyF'],\n indicator_left: ['Comma'],\n indicator_right: ['Period'],\n hazard: ['KeyB'],\n wipers: ['KeyO'],\n seatbelt: ['KeyJ'],\n drive_profile: ['Digit7'],\n traction_control: ['Digit8'],\n abs: ['Digit9'],\n cruise: ['Digit0'],\n climate: ['Minus'],\n demist: ['Equal'],\n siren: ['Semicolon'],\n beacon: ['Quote'],\n glovebox: ['Slash'],\n}\nconst HELD_KEYS = ['throttle', 'brake', 'left', 'right', 'handbrake', 'horn', 'clutch', 'flash', 'washer', 'hotwire']\n\nexport type Gearbox = 'automatic' | 'manual'\nexport type DriveMode = '4x2' | '4x4' | 'auto'\nexport type LampMode = 'off' | 'position' | 'low' | 'high'\nexport type AlarmState = 'off' | 'armed' | 'ringing'\nexport type RadioSource = 'radio' | 'tape'\nexport type Indicator = 'off' | 'left' | 'right' | 'hazard'\nexport type Wipers = 'off' | 'intermittent' | 'slow' | 'fast'\n/** The siren's tone: the slow rise and fall, or the fast warble of a junction. */\nexport type Siren = 'off' | 'wail' | 'yelp'\n\nexport interface ControlState {\n ignition: boolean\n gearbox: Gearbox\n /** The gear the driver chose (manual): -1 reverse, 0 neutral, 1.. forward. */\n gear: number\n /** Pulled and left pulled (P); Space holds it only while pressed. */\n parkingBrake: boolean\n driveMode: DriveMode\n /** The front axle drives now (4x4, or automatic 4x4 that felt the rear slip). */\n fourWheelEngaged: boolean\n /** `flash`: the high beam lit while the flash key is held, over any mode. */\n lamps: { mode: LampMode; fog: boolean; interior: boolean; flash: boolean }\n /** What the rear lamps show this step: brake (pedal or handbrake) and reversing. */\n brakeLights: boolean\n reverseLights: boolean\n horn: boolean\n alarm: AlarmState\n /** `track`: the station or the song on the tape, 0-based (`radioTracks` of them). */\n radio: { on: boolean; source: RadioSource; track: number }\n indicator: Indicator\n /** The indicator lamps are lit this instant (they blink at `blinkHz`); `tick` is true on the step the relay clicks. */\n blinkOn: boolean\n tick: boolean\n wipers: Wipers\n /** The washer squirts while its key is held (the wipers sweep with it). */\n washer: boolean\n seatbelt: boolean\n /** Clutch pedal, 0 up to 1 down (manual gearbox). */\n clutch: number\n profile: DriveProfile\n tractionControl: boolean\n abs: boolean\n /** Cruise control: the speed it holds, m/s. */\n cruise: { on: boolean; speed: number }\n climate: { on: boolean; demist: boolean }\n /** The starter turns this step. */\n cranking: boolean\n /** Without the key: how far the wires under the column are (0 untouched, 1 joined: the ignition is live), and whether they are joined now. */\n hotwire: { progress: number; done: boolean }\n siren: Siren\n /** The beacon (light bar) is on, and which of its two sides is lit this instant (it alternates at `beaconHz`). */\n beacon: boolean\n beaconSide: 0 | 1\n /** The glovebox lid is open. */\n glovebox: boolean\n}\n\nexport type ControlEvent =\n | { type: 'command'; command: ControlCommand; state: ControlState }\n | { type: 'refused'; command: ControlCommand; reason: 'no_four_wheel_drive' | 'no_fog_lamps' | 'ignition_off' | 'battery_flat' | 'too_slow' | 'no_key' | 'no_siren' }\n | { type: 'cruise_cancelled' }\n /** The wires under the column: stripped (first touch), joined (the ignition is live and the starter turns). */\n | { type: 'hotwire'; stage: 'started' | 'joined' }\n\nexport interface VehicleControlOptions {\n /** Forward gears of the gearbox. */\n gears: number\n /** The vehicle can drive both axles (4x4 and automatic 4x4 are offered). */\n fourWheelDrive?: boolean\n /** The vehicle has fog lamps. Default true. */\n fogLamps?: boolean\n keys?: Partial<ControlKeyMap>\n gearbox?: Gearbox\n /** Automatic 4x4: the front axle comes in above this slip of a driven wheel (1 = sliding) and goes out after `releaseSeconds` below it. */\n autoFourWheel?: { slip: number; releaseSeconds: number }\n /** The engine runs from the start (a vehicle the player gets into with the engine on). Default false: the key turns it on (I) or the gas pedal starts it. */\n running?: boolean\n /** Blinks a second of the indicators (default 1.5, the 90 a minute of the road codes). */\n blinkHz?: number\n /** The steering wheel coming back this far (0..1 of the lock) after a turn cancels the indicator, as the column does. Default 0.15. */\n indicatorCancel?: number\n /** Stations or songs the radio steps through (`radio_track`). Default 3. */\n radioTracks?: number\n /** The driver works the clutch (C) in manual: released in gear too slowly or without gas, the engine stalls. Default false (the clutch is automated). */\n clutchPedal?: boolean\n /** The starter can turn the engine over (a battery with charge); asked at every crank. Default always. */\n canCrank?: () => boolean\n /** A crank happened (takes the battery's energy). */\n onCrank?: () => void\n /** Share of the torque the engine gives besides the aids (an overheated engine). Default 1. */\n powerLimit?: () => number\n /** The driver has the key. Default true. Without it the ignition refuses and the hotwire key (held) joins the wires. */\n hasKey?: boolean\n /** Seconds of the hotwire key held to strip and join the wires. Default 8. */\n hotwireSeconds?: number\n /** The vehicle has a siren and a beacon (an emergency vehicle). Default false: both refuse. */\n emergency?: boolean\n /** The beacon's sides swap this many times a second. Default 2.5. */\n beaconHz?: number\n onEvent?: (event: ControlEvent) => void\n}\n\n/** What the controls read of the driver each step, and the one thing they change on it (which axles drive). */\nexport interface ControlledDriver {\n readonly spec: { fourWheelDrive: boolean; abs?: boolean; upshiftFraction?: number; downshiftFraction?: number; readonly wheels?: ReadonlyArray<{ drive?: boolean }> }\n readonly state: { u: number; gear: number; slip: readonly number[]; engineOn: boolean }\n}\n\nexport interface VehicleControls {\n /** A key went down or up. True when it is a driving key (the host keeps it from its own bindings). */\n key(code: string, down: boolean): boolean\n /** Runs a command as its key would (a button of a panel). */\n command(command: ControlCommand): void\n /** The input for this step, pedals and wheel eased over `dt` seconds. */\n input(dt: number, driver?: ControlledDriver): SemiInput\n /** After the driver stepped: the automatic 4x4 watches the slip, the ignition the engine. */\n after(driver: ControlledDriver, dt: number): void\n readonly state: ControlState\n readonly keys: ControlKeyMap\n /** Lets go of every key (the window lost focus, the driver got out). */\n release(): void\n}\n\nexport function createVehicleControls(options: VehicleControlOptions): VehicleControls {\n const keys: ControlKeyMap = { ...DEFAULT_CONTROL_KEYS, ...options.keys }\n const auto4 = options.autoFourWheel ?? { slip: 0.18, releaseSeconds: 2 }\n const hasFog = options.fogLamps !== false\n const held = new Set<string>()\n const any = (codes: readonly string[]): boolean => codes.some((c) => held.has(c))\n const commandOf = new Map<string, ControlCommand>()\n for (const [command, codes] of Object.entries(keys)) if (!HELD_KEYS.includes(command)) for (const code of codes) commandOf.set(code, command as ControlCommand)\n const driving = new Set<string>(Object.values(keys).flat())\n\n const state: ControlState = {\n ignition: !!options.running,\n gearbox: options.gearbox ?? 'automatic',\n gear: 1,\n parkingBrake: false,\n driveMode: options.fourWheelDrive ? 'auto' : '4x2',\n fourWheelEngaged: false,\n lamps: { mode: 'off', fog: false, interior: false, flash: false },\n brakeLights: false,\n reverseLights: false,\n horn: false,\n alarm: 'off',\n radio: { on: false, source: 'radio', track: 0 },\n indicator: 'off',\n blinkOn: false,\n tick: false,\n wipers: 'off',\n washer: false,\n seatbelt: false,\n clutch: 0,\n profile: 'normal',\n tractionControl: true,\n abs: true,\n cruise: { on: false, speed: 0 },\n climate: { on: false, demist: false },\n cranking: false,\n hotwire: { progress: 0, done: false },\n siren: 'off',\n beacon: false,\n beaconSide: 0,\n glovebox: false,\n }\n const hasKey = options.hasKey !== false\n const hotwireSeconds = Math.max(0.1, options.hotwireSeconds ?? 8)\n const beaconHz = options.beaconHz ?? 2.5\n let beaconClock = 0\n let crankAsked = false\n let lastSpeed = 0\n let engineRunning = !!options.running\n const blinkHz = options.blinkHz ?? 1.5\n const cancelAt = options.indicatorCancel ?? 0.15\n let blink = 0\n let turned = 0\n let throttle = 0\n let brake = 0\n let steer = 0\n let calm = 0\n const emit = (event: ControlEvent): void => options.onEvent?.(event)\n const LAMPS: readonly LampMode[] = ['off', 'position', 'low']\n const MODES: readonly DriveMode[] = ['4x2', '4x4', 'auto']\n const WIPERS: readonly Wipers[] = ['off', 'intermittent', 'slow', 'fast']\n const PROFILES: readonly DriveProfile[] = ['eco', 'normal', 'sport']\n const SIRENS: readonly Siren[] = ['off', 'wail', 'yelp']\n\n const command = (c: ControlCommand): void => {\n switch (c) {\n case 'ignition':\n // without the key only the joined wires make the ignition live; pulled apart, they cut it, and joined again they make it live\n if (!hasKey && !state.hotwire.done) return emit({ type: 'refused', command: c, reason: 'no_key' })\n state.ignition = !state.ignition\n // the driver turning the key disarms the alarm and cranks; turning it off leaves the radio playing on the battery\n if (state.ignition && state.alarm !== 'off') state.alarm = 'off'\n if (state.ignition) crankAsked = true\n else state.cruise.on = false\n break\n case 'gearbox':\n state.gearbox = state.gearbox === 'automatic' ? 'manual' : 'automatic'\n // with a clutch to work, a manual starts in neutral (in gear with the clutch up it would stall at once)\n state.gear = options.clutchPedal && state.gearbox === 'manual' && Math.abs(lastSpeed) < 0.5 ? 0 : Math.max(1, state.gear)\n break\n case 'gear_up':\n case 'gear_down':\n if (state.gearbox !== 'manual') return\n state.gear = Math.max(-1, Math.min(options.gears, state.gear + (c === 'gear_up' ? 1 : -1)))\n break\n case 'parking_brake':\n state.parkingBrake = !state.parkingBrake\n break\n case 'drive_mode': {\n if (!options.fourWheelDrive) return emit({ type: 'refused', command: c, reason: 'no_four_wheel_drive' })\n state.driveMode = MODES[(MODES.indexOf(state.driveMode) + 1) % MODES.length] as DriveMode\n state.fourWheelEngaged = state.driveMode === '4x4'\n break\n }\n case 'lights':\n // off → position → low → off; high beam is its own switch over the low beam\n state.lamps.mode = state.lamps.mode === 'high' ? 'off' : (LAMPS[(LAMPS.indexOf(state.lamps.mode) + 1) % LAMPS.length] as LampMode)\n break\n case 'high_beam':\n state.lamps.mode = state.lamps.mode === 'high' ? 'low' : 'high'\n break\n case 'fog_lights':\n if (!hasFog) return emit({ type: 'refused', command: c, reason: 'no_fog_lamps' })\n state.lamps.fog = !state.lamps.fog\n // fog lamps go with the position lamps at least\n if (state.lamps.fog && state.lamps.mode === 'off') state.lamps.mode = 'position'\n break\n case 'interior_light':\n state.lamps.interior = !state.lamps.interior\n break\n case 'alarm':\n // armed → ringing (someone forced it) → off; off → armed\n state.alarm = state.alarm === 'off' ? 'armed' : state.alarm === 'armed' ? 'ringing' : 'off'\n break\n case 'radio':\n state.radio.on = !state.radio.on\n break\n case 'radio_source':\n state.radio.source = state.radio.source === 'radio' ? 'tape' : 'radio'\n break\n case 'radio_track':\n state.radio.track = (state.radio.track + 1) % Math.max(1, options.radioTracks ?? 3)\n break\n case 'exit':\n break\n case 'indicator_left':\n case 'indicator_right': {\n const side = c === 'indicator_left' ? 'left' : 'right'\n // the hazard switch wins over the stalk; the stalk pushed again the same way puts it back\n if (state.indicator === 'hazard') return\n state.indicator = state.indicator === side ? 'off' : side\n turned = 0\n blink = 0\n break\n }\n case 'hazard':\n state.indicator = state.indicator === 'hazard' ? 'off' : 'hazard'\n blink = 0\n break\n case 'wipers':\n state.wipers = WIPERS[(WIPERS.indexOf(state.wipers) + 1) % WIPERS.length] as Wipers\n break\n case 'drive_profile':\n state.profile = PROFILES[(PROFILES.indexOf(state.profile) + 1) % PROFILES.length] as DriveProfile\n break\n case 'traction_control':\n state.tractionControl = !state.tractionControl\n break\n case 'abs':\n state.abs = !state.abs\n break\n case 'cruise':\n if (state.cruise.on) state.cruise.on = false\n else if (!engineRunning) return emit({ type: 'refused', command: c, reason: 'ignition_off' })\n else if (lastSpeed < DEFAULT_CRUISE.minSpeed) return emit({ type: 'refused', command: c, reason: 'too_slow' })\n else state.cruise = { on: true, speed: lastSpeed }\n break\n case 'climate':\n state.climate.on = !state.climate.on\n if (!state.climate.on) state.climate.demist = false\n break\n case 'demist':\n // the air conditioning dries the air: the demister runs it\n state.climate.demist = !state.climate.demist\n if (state.climate.demist) state.climate.on = true\n break\n case 'seatbelt':\n state.seatbelt = !state.seatbelt\n break\n case 'siren':\n if (!options.emergency) return emit({ type: 'refused', command: c, reason: 'no_siren' })\n state.siren = SIRENS[(SIRENS.indexOf(state.siren) + 1) % SIRENS.length] as Siren\n // the siren never sounds with the lights off\n if (state.siren !== 'off') state.beacon = true\n break\n case 'beacon':\n if (!options.emergency) return emit({ type: 'refused', command: c, reason: 'no_siren' })\n state.beacon = !state.beacon\n if (!state.beacon) state.siren = 'off'\n beaconClock = 0\n break\n case 'glovebox':\n state.glovebox = !state.glovebox\n break\n }\n emit({ type: 'command', command: c, state })\n }\n\n const ease = (from: number, to: number, rate: number, dt: number): number => from + Math.sign(to - from) * Math.min(Math.abs(to - from), rate * dt)\n\n return {\n keys,\n state,\n key(code, down) {\n if (!driving.has(code)) return false\n const was = held.has(code)\n if (down) held.add(code)\n else held.delete(code)\n // a command runs on the press, not while the key repeats\n const c = commandOf.get(code)\n if (c && down && !was) command(c)\n return true\n },\n command,\n input(dt, driver) {\n const gas = any(keys.throttle) ? 1 : 0\n const stop = any(keys.brake) ? 1 : 0\n const wheel = (any(keys.left) ? 1 : 0) - (any(keys.right) ? 1 : 0)\n // pedals in a quarter of a second and out faster; the wheel turns in a third of a second and comes back to the centre faster still\n throttle = ease(throttle, gas, gas > throttle ? 4 : 8, dt)\n brake = ease(brake, stop, stop > brake ? 6 : 10, dt)\n steer = ease(steer, wheel, wheel !== 0 && Math.sign(wheel) === Math.sign(steer || wheel) ? 3 : 6, dt)\n const handbrake = state.parkingBrake || any(keys.handbrake)\n // the indicators blink on the relay; a turn the way they point and the wheel back near the centre cancels them\n state.tick = false\n if (state.indicator !== 'off') {\n const before = Math.floor(blink * blinkHz * 2)\n blink += dt\n const now = Math.floor(blink * blinkHz * 2)\n state.blinkOn = now % 2 === 0\n state.tick = now !== before\n if (state.indicator !== 'hazard') {\n const way = state.indicator === 'left' ? steer : -steer\n if (way > 0.5) turned = 1\n else if (turned && way < cancelAt) state.indicator = 'off'\n }\n } else state.blinkOn = false\n // the beacon's two sides take turns\n if (state.beacon) {\n beaconClock += dt\n state.beaconSide = (Math.floor(beaconClock * beaconHz) % 2) as 0 | 1\n }\n // no key: the ignition key held strips the wires, then joins them; the ignition goes live and the starter turns. An armed alarm goes off at the first touch.\n if (!hasKey && !state.hotwire.done && !state.ignition && any(keys.hotwire)) {\n if (state.hotwire.progress === 0) {\n if (state.alarm === 'armed') state.alarm = 'ringing'\n emit({ type: 'hotwire', stage: 'started' })\n }\n state.hotwire.progress = Math.min(1, state.hotwire.progress + dt / hotwireSeconds)\n if (state.hotwire.progress >= 1) {\n state.hotwire.done = true\n state.ignition = true\n crankAsked = true\n emit({ type: 'hotwire', stage: 'joined' })\n }\n }\n state.horn = any(keys.horn)\n state.lamps.flash = any(keys.flash)\n state.washer = any(keys.washer)\n // the clutch goes down fast and comes up as slowly as a foot lets it, so it bites on the way\n state.clutch = ease(state.clutch, any(keys.clutch) ? 1 : 0, any(keys.clutch) ? 8 : 2.5, dt)\n const speed = driver?.state.u ?? 0\n lastSpeed = speed\n // the brake, the clutch or the handbrake cancel cruise control\n if (state.cruise.on && (brake > 0.05 || state.clutch > 0.5 || handbrake)) {\n state.cruise.on = false\n emit({ type: 'cruise_cancelled' })\n }\n // the key off: no gas reaches the engine; the brakes still work\n const tune = DRIVE_PROFILES[state.profile]\n let gasNow = state.ignition ? throttle * tune.throttle : 0\n if (state.cruise.on && state.ignition) gasNow = Math.max(gasNow, cruiseThrottle(state.cruise.speed, speed))\n // the starter: the key turned, or (automatic, key on) the gas pressed after the engine died with the car still\n const gasStart = state.gearbox === 'automatic' && state.ignition && !engineRunning && throttle > 0 && Math.abs(speed) < 0.5\n state.cranking = false\n if (crankAsked || gasStart) {\n crankAsked = false\n if (options.canCrank && !options.canCrank()) emit({ type: 'refused', command: 'ignition', reason: 'battery_flat' })\n else {\n state.cranking = true\n options.onCrank?.()\n }\n }\n const driven = (driver?.state.slip ?? []).filter((_, i) => driver?.spec.wheels?.[i]?.drive ?? true)\n const powerLimit = (state.tractionControl ? tractionLimit(driven) : 1) * (options.powerLimit?.() ?? 1)\n const reversing = state.gearbox === 'manual' ? state.gear < 0 : (driver?.state.gear ?? 1) < 0\n state.reverseLights = reversing\n state.brakeLights = handbrake || (reversing ? gasNow > 0.05 && speed < -0.3 : brake > 0.05)\n const common = { steer, handbrake, horn: state.horn, start: state.cranking, powerLimit }\n if (state.gearbox === 'automatic') return { ...common, throttle: gasNow, brake }\n // manual: the gas drives the chosen gear either way (backwards in reverse) and the brake only brakes; the driver reads the pedals against the direction of travel\n const pedals = state.gear < 0 ? { throttle: brake, brake: gasNow } : { throttle: gasNow, brake }\n return { ...common, ...pedals, gear: state.gear, ...(options.clutchPedal ? { clutch: state.clutch } : {}) }\n },\n after(driver, dt) {\n if (!state.ignition && driver.state.engineOn) (driver.state as { engineOn: boolean }).engineOn = false\n engineRunning = driver.state.engineOn\n if (!engineRunning) state.cruise.on = false\n // the aids reach the driver: ABS on the brakes, the profile on the shift points\n const spec = driver.spec as { abs?: boolean; upshiftFraction?: number; downshiftFraction?: number }\n spec.abs = state.abs\n if (spec.upshiftFraction != null) {\n spec.upshiftFraction = DRIVE_PROFILES[state.profile].upshift\n spec.downshiftFraction = DRIVE_PROFILES[state.profile].downshift\n }\n if (state.driveMode === 'auto' && options.fourWheelDrive) {\n const slip = Math.max(0, ...driver.state.slip)\n if (slip > auto4.slip) {\n state.fourWheelEngaged = true\n calm = 0\n } else if (state.fourWheelEngaged && (calm += dt) > auto4.releaseSeconds) state.fourWheelEngaged = false\n } else state.fourWheelEngaged = state.driveMode === '4x4'\n driver.spec.fourWheelDrive = !!options.fourWheelDrive && state.fourWheelEngaged\n },\n release() {\n held.clear()\n throttle = brake = steer = 0\n state.horn = false\n state.lamps.flash = false\n state.washer = false\n state.clutch = 0\n state.cruise.on = false\n },\n }\n}\n","/** Matches a damage model's wheels to a driver's: each wheel of the spec takes the health of the tyre nearest to it. */\nimport type { SemiSimSpec, VehicleCondition } from './types'\n\nexport type DamagedTyre = {\n /** Where the tyre is in the vehicle's space, metres: x forward, z to the side. */\n readonly x: number\n readonly z: number\n /** 0 flat or gone, 1 whole. */\n readonly health: number\n /** The tyre is gone and the rim is on the road. */\n readonly rim?: boolean\n}\n\nexport type DamageReport = {\n readonly tyres: readonly DamagedTyre[]\n readonly brakes?: number\n readonly engine?: number\n readonly suspension?: number\n}\n\nexport function conditionFromDamage(spec: Pick<SemiSimSpec, 'wheels'>, report: DamageReport): VehicleCondition {\n const tyres = spec.wheels.map((wheel) => {\n let best: DamagedTyre | undefined\n let distance = Infinity\n for (const tyre of report.tyres) {\n const d = Math.hypot(tyre.x - wheel.x, tyre.z - wheel.z)\n if (d < distance) {\n distance = d\n best = tyre\n }\n }\n return best\n })\n return {\n tyres: tyres.map((tyre) => tyre?.health ?? 1),\n rims: tyres.map((tyre) => !!tyre?.rim),\n ...(report.brakes != null ? { brakes: report.brakes } : {}),\n ...(report.engine != null ? { engine: report.engine } : {}),\n ...(report.suspension != null ? { suspension: report.suspension } : {}),\n }\n}\n","/**\n * What keeps a car running besides the engine: the 12 V battery (the lamps, radio, wipers and alarm draw from it, the alternator charges it while\n * the engine turns, and below what the starter needs the car does not start), the coolant temperature (it climbs with the work of the engine, the air\n * through the radiator and the fan take it away, and a damaged radiator boils it: past `limpC` the engine loses power, past `seizeC` it dies) and the\n * spare tyre (one flat wheel can be swapped for it). It reads the driver and the controls and changes only what a real car would: the engine state,\n * the power it gives and the tyres. Every number is an option.\n */\nimport type { ControlState } from './controls'\nimport type { SemiState, VehicleCondition } from './semi/types'\n\nexport interface ElectricalLoads {\n /** Watts of each consumer while on. */\n readonly position: number\n readonly low: number\n readonly high: number\n readonly fog: number\n readonly interior: number\n readonly radio: number\n readonly wipers: number\n readonly indicators: number\n readonly horn: number\n readonly alarm: number\n readonly brakeLights: number\n readonly climate: number\n /** An emergency vehicle's siren amplifier and its beacon (light bar). */\n readonly siren: number\n readonly beacon: number\n}\n\nexport interface VehicleSystemsOptions {\n /** Battery capacity, watt-hours (a 12 V 60 Ah battery holds 720). */\n batteryWh?: number\n /** Charge at the start, 0..1. */\n charge?: number\n /** Alternator output, watts, at idle and from 2000 rpm up. */\n alternatorW?: { idle: number; full: number }\n /** Below this charge the starter does not turn the engine over. */\n crankCharge?: number\n /** Energy of one start, watt-hours. */\n startWh?: number\n loads?: Partial<ElectricalLoads>\n /** Air temperature, °C. */\n ambientC?: number\n /** The thermostat holds the coolant here once warm. */\n thermostatC?: number\n /** Limp mode above this (power cut), engine seizes above `seizeC`. */\n limpC?: number\n seizeC?: number\n /** Warming of the coolant, °C per second at full power; cooling share of the gap to the air per second, at a stop and at 100 km/h. */\n heatPerSecond?: number\n cooling?: { stopped: number; fast: number }\n /** Spare tyres carried. */\n spares?: number\n}\n\nexport const DEFAULT_LOADS: ElectricalLoads = { position: 20, low: 110, high: 130, fog: 110, interior: 10, radio: 25, wipers: 60, indicators: 42, horn: 60, alarm: 5, brakeLights: 42, climate: 180, siren: 100, beacon: 70 }\n\nexport type SystemsEvent = { type: 'battery_flat' } | { type: 'overheating' } | { type: 'seized' } | { type: 'spare_fitted'; wheel: number } | { type: 'no_spare' }\n\nexport interface SystemsState {\n /** 0..1. */\n charge: number\n /** Coolant, °C. */\n coolantC: number\n /** 0 cold (the air) to 1 (the seize point), for a gauge. */\n temperature: number\n overheating: boolean\n seized: boolean\n spares: number\n /** Net watts on the battery this step: positive charging, negative draining. */\n netW: number\n}\n\nexport interface SystemsDriver {\n readonly state: Pick<SemiState, 'engineOn' | 'rpm' | 'u'>\n condition: VehicleCondition\n}\n\nexport interface SystemsStepParams {\n driver: SystemsDriver\n controls: ControlState\n /** The gas the engine got this step, 0..1. */\n throttle: number\n dt: number\n /** What is left of the radiator, 0..1. Default 1. */\n radiator?: number\n /** The coolant temperature from a damage model that tracks it (the vehicle destructible's `runEngine`): it replaces this model's own. */\n coolantC?: number\n}\n\nexport interface VehicleSystems {\n readonly state: SystemsState\n /** The starter can turn the engine over now. */\n canCrank(): boolean\n /** Takes the energy of one start. */\n crank(): void\n /** Share of the torque the engine gives now (limp mode when hot). */\n powerLimit(): number\n /** Advances `dt` seconds; `throttle` is the gas the engine got, `controls` what is switched on. */\n step(params: SystemsStepParams): SystemsEvent[]\n /** Swaps the flat tyre of `wheel` for the spare. */\n fitSpare(driver: SystemsDriver, wheel: number): SystemsEvent\n /** Fills the battery (a jump start or a charger), 0..1 of the capacity. */\n charge(share: number): void\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\n\nexport function createVehicleSystems(options: VehicleSystemsOptions = {}): VehicleSystems {\n const loads: ElectricalLoads = { ...DEFAULT_LOADS, ...options.loads }\n const capacity = options.batteryWh ?? 720\n const alternator = options.alternatorW ?? { idle: 350, full: 1100 }\n const crankCharge = options.crankCharge ?? 0.25\n const startWh = options.startWh ?? 0.6\n const ambient = options.ambientC ?? 25\n const thermostat = options.thermostatC ?? 90\n const limp = options.limpC ?? 115\n const seize = options.seizeC ?? 130\n const heat = options.heatPerSecond ?? 0.5\n const cooling = options.cooling ?? { stopped: 0.004, fast: 0.03 }\n const state: SystemsState = { charge: clamp(options.charge ?? 1, 0, 1), coolantC: ambient, temperature: 0, overheating: false, seized: false, spares: options.spares ?? 1, netW: 0 }\n\n const draw = (c: ControlState): number => {\n const lamps = c.lamps\n let w = lamps.mode === 'off' ? 0 : loads.position\n if (lamps.mode === 'low') w += loads.low\n if (lamps.mode === 'high') w += loads.low + loads.high\n if (lamps.flash) w += loads.high\n if (lamps.fog) w += loads.fog\n if (lamps.interior) w += loads.interior\n if (c.radio.on) w += loads.radio\n if (c.wipers !== 'off' || c.washer) w += loads.wipers\n if (c.indicator !== 'off') w += loads.indicators * (c.indicator === 'hazard' ? 2 : 1) * 0.5\n if (c.horn) w += loads.horn\n if (c.alarm !== 'off') w += loads.alarm\n if (c.brakeLights) w += loads.brakeLights\n if (c.climate.on) w += loads.climate\n if (c.siren !== 'off') w += loads.siren\n if (c.beacon) w += loads.beacon\n return w\n }\n\n return {\n state,\n canCrank: () => state.charge >= crankCharge && !state.seized,\n crank() {\n state.charge = clamp(state.charge - startWh / capacity, 0, 1)\n },\n powerLimit: () => (state.coolantC <= limp ? 1 : clamp(1 - (state.coolantC - limp) / (seize - limp), 0.25, 1)),\n step({ driver, controls, throttle, dt, radiator = 1, coolantC }) {\n const events: SystemsEvent[] = []\n const running = driver.state.engineOn\n const charging = running ? alternator.idle + (alternator.full - alternator.idle) * clamp((driver.state.rpm - 900) / 1100, 0, 1) : 0\n // the key off leaves only what is wired to the battery directly: lamps, hazard, interior light, alarm, radio on memory\n const net = charging - draw(controls)\n state.netW = net\n const before = state.charge\n state.charge = clamp(state.charge + (net * dt) / 3600 / capacity, 0, 1)\n if (before >= crankCharge && state.charge < crankCharge && !running) events.push({ type: 'battery_flat' })\n // coolant: the engine's work heats it, the thermostat holds it until the radiator cannot keep up; a broken radiator barely cools\n const work = running ? clamp(0.15 + 0.85 * throttle * (driver.state.rpm / 6500), 0, 1) : 0\n const air = cooling.stopped + (cooling.fast - cooling.stopped) * clamp(Math.abs(driver.state.u) / 27.8, 0, 1)\n const cool = air * clamp(radiator, 0.05, 1) * (running ? 1 + (controls.climate.on ? 0.15 : 0) : 1)\n const opened = state.coolantC >= thermostat ? 1 : 0.15\n state.coolantC += (heat * work - cool * opened * (state.coolantC - ambient)) * dt\n state.coolantC = coolantC ?? Math.max(ambient, state.coolantC)\n state.temperature = clamp((state.coolantC - ambient) / (seize - ambient), 0, 1)\n const hot = state.coolantC > limp\n if (hot && !state.overheating) events.push({ type: 'overheating' })\n state.overheating = hot\n if (state.coolantC >= seize && !state.seized) {\n state.seized = true\n events.push({ type: 'seized' })\n }\n if (state.seized) (driver.state as { engineOn: boolean }).engineOn = false\n return events\n },\n fitSpare(driver, wheel) {\n if (state.spares <= 0) return { type: 'no_spare' }\n state.spares--\n const tyres = [...(driver.condition.tyres ?? [])]\n tyres[wheel] = 1\n driver.condition = { ...driver.condition, tyres }\n return { type: 'spare_fitted', wheel }\n },\n charge(share) {\n state.charge = clamp(state.charge + share, 0, 1)\n },\n }\n}\n","/**\n * Who leaves the car in a crash. An occupant without a belt keeps the speed the car had (inertia) while the car stops: in a frontal crash past\n * about 30 km/h of change in speed the body goes through the windshield, in a hard side impact or a rollover through the side window on the side it\n * is thrown to. A belted occupant stays in (a belt holds a person to the seat up to crashes far harder than a road car survives). The glass breaks\n * first; the body flies with most of the car's speed before the crash and a little lift. Pure numbers, every threshold an option.\n */\nexport type EjectionExit = 'windshield' | 'left_window' | 'right_window' | 'rear_window'\n\nexport interface EjectionOptions {\n /** Change of speed, m/s, past which an unbelted occupant goes through the windshield (about 30 km/h). */\n frontal: number\n /** Sideways change of speed, m/s, past which an unbelted occupant goes out of a side window. */\n side: number\n /** Share of the speed before the crash the body keeps on the way out (the glass and the dash take the rest). */\n keep: number\n /** Upward speed of the body leaving, m/s (it rides up over the dash). */\n lift: number\n}\n\nexport const DEFAULT_EJECTION: EjectionOptions = { frontal: 8.3, side: 6, keep: 0.8, lift: 2.5 }\n\nexport interface CrashPulse {\n /** Body-frame speed before and after the crash, m/s: forward and to the right. */\n readonly before: { readonly u: number; readonly w: number }\n readonly after: { readonly u: number; readonly w: number }\n /** The car rolled over in it. */\n readonly rolled?: boolean\n}\n\nexport interface Ejection {\n readonly exit: EjectionExit\n /** Body-frame velocity of the body leaving, m/s: forward, to the right, up. */\n readonly velocity: readonly [number, number, number]\n /** Change of speed of the crash, m/s (what the injuries scale with). */\n readonly deltaV: number\n}\n\n/** The ejection of one occupant, or null when the occupant stays in. */\nexport function ejectionOf(pulse: CrashPulse, belted: boolean, options: EjectionOptions = DEFAULT_EJECTION): Ejection | null {\n if (belted) return null\n const du = pulse.after.u - pulse.before.u\n const dw = pulse.after.w - pulse.before.w\n const deltaV = Math.hypot(du, dw)\n // the body moves against the car's change of speed: a car stopped from forward throws it forward\n const frontal = Math.abs(du) >= Math.abs(dw)\n if (frontal && Math.abs(du) < options.frontal && !pulse.rolled) return null\n if (!frontal && Math.abs(dw) < options.side && !pulse.rolled) return null\n const exit: EjectionExit = frontal ? (du < 0 ? 'windshield' : 'rear_window') : dw < 0 ? 'right_window' : 'left_window'\n return { exit, velocity: [pulse.before.u * options.keep, pulse.before.w * options.keep, options.lift], deltaV }\n}\n","/**\n * Parking sensors: the bumper's distance to the nearest obstacle in the way turns into the beep the cabin plays, slower far away, faster close,\n * continuous at the last few centimetres. Pure numbers, the distances are options.\n */\nexport interface ParkingSensorOptions {\n /** Farther than this (metres) it stays quiet. */\n readonly range: number\n /** Closer than this it beeps without pause. */\n readonly solid: number\n /** Pause between beeps at the edge of the range and near `solid`, seconds. */\n readonly slowest: number\n readonly fastest: number\n}\n\nexport const DEFAULT_PARKING_SENSOR: ParkingSensorOptions = { range: 1.5, solid: 0.3, slowest: 0.8, fastest: 0.12 }\n\n/** Seconds between beeps for an obstacle `distance` metres from the bumper: null when quiet, 0 when continuous. */\nexport function parkingBeepInterval(distance: number, options: ParkingSensorOptions = DEFAULT_PARKING_SENSOR): number | null {\n if (distance > options.range) return null\n if (distance <= options.solid) return 0\n const t = (distance - options.solid) / (options.range - options.solid)\n return options.fastest + (options.slowest - options.fastest) * t\n}\n\n/**\n * The bumper's distance to the nearest of `obstacles` (world x, z) in the vehicle's path: ahead when `forward`, behind otherwise. The vehicle is\n * at (x, z) facing `heading` (unit x, z), `length` and `width` metres; obstacles off to the side of its width are not in the way.\n */\nexport function bumperDistance(params: { x: number; z: number; heading: readonly [number, number]; length: number; width: number; forward: boolean; obstacles: ReadonlyArray<readonly [number, number]> }): number {\n const [hx, hz] = params.heading\n const sign = params.forward ? 1 : -1\n let best = Infinity\n for (const [ox, oz] of params.obstacles) {\n const dx = ox - params.x\n const dz = oz - params.z\n const along = (dx * hx + dz * hz) * sign - params.length / 2\n const side = Math.abs(-dx * hz + dz * hx)\n if (along >= 0 && side <= params.width / 2 + 0.2) best = Math.min(best, along)\n }\n return best\n}\n","/**\n * What a vehicle carries besides its people: the glovebox (reached from a front seat, or through an open front door, with its lid open) and the trunk\n * (reached with the lid up, from behind). Each compartment holds item stacks by slot, up to a slot count and a weight; nothing is reached while it is\n * shut, and the weight it carries is there for the driver to add to the vehicle's mass. Items are the host's (a game's catalog, `game-items`): a stack\n * is its id, its count, the weight of one and whatever state the host keeps with it. Every number is an option.\n */\n\nexport type CompartmentId = string\n\nexport interface CompartmentSpec {\n readonly id: CompartmentId\n /** Stacks it holds. */\n readonly slots: number\n /** Weight it takes, kg. */\n readonly capacityKg: number\n /** How it is reached: `cabin` from a front seat or an open front door with its own lid open (a glovebox); `lid` with the trunk lid up. */\n readonly access: 'cabin' | 'lid'\n}\n\n/** A stack in a compartment: the host's item id, how many and the weight of one; `data` is the host's own state of the stack (age, charge), kept as is. */\nexport interface StorageStack {\n readonly itemId: string\n readonly count: number\n readonly unitKg: number\n readonly data?: unknown\n}\n\n/** What reaches the compartments now. */\nexport interface StorageAccess {\n /** Someone sits in a front seat. */\n readonly seated: boolean\n /** A front door is open (someone standing outside reaches the glovebox). */\n readonly frontDoorOpen: boolean\n /** The glovebox lid is open (`ControlState.glovebox`). */\n readonly gloveboxOpen: boolean\n /** The trunk lid is up, 0..1 (open from 0.5). */\n readonly lid: number\n}\n\nexport type StoreResult = 'ok' | 'shut' | 'full' | 'too_heavy' | 'missing'\n\n/** A glovebox: a few small things (papers, a torch, a charger), about 8 litres. */\nexport const GLOVEBOX: CompartmentSpec = { id: 'glovebox', slots: 6, capacityKg: 4, access: 'cabin' }\n\n/** The trunk of a car by its size in litres (a hatch 280, a sedan 450, an estate 600): a slot every 25 litres and a kilo for every 4 litres. */\nexport const trunkFor = (litres = 450): CompartmentSpec => ({ id: 'trunk', slots: Math.max(4, Math.round(litres / 25)), capacityKg: Math.round(litres / 4), access: 'lid' })\n\nexport interface VehicleStorageOptions {\n /** Default: a glovebox and a 450-litre trunk. A motorcycle passes none, a pickup its bed as a `lid` compartment. */\n compartments?: readonly CompartmentSpec[]\n}\n\nexport interface VehicleStorage {\n readonly compartments: readonly CompartmentSpec[]\n /** The compartment can be reached now. */\n reachable(id: CompartmentId, access: StorageAccess): boolean\n /** Stacks by slot (null an empty slot). */\n contents(id: CompartmentId): ReadonlyArray<StorageStack | null>\n /** Weight in one compartment, or in all of them. */\n loadKg(id?: CompartmentId): number\n /** Puts a stack in (it joins a stack of the same item without host state); refused while shut, without a free slot or over the weight. */\n put(id: CompartmentId, stack: StorageStack, access: StorageAccess): StoreResult\n /** Takes the stack of a slot out; null while shut or empty. */\n take(id: CompartmentId, slot: number, access: StorageAccess): StorageStack | null\n /** Fills a compartment at once, reachable or not (what was in it when the vehicle was found); what does not fit is left out and returned. */\n stock(id: CompartmentId, stacks: readonly StorageStack[]): StorageStack[]\n /** Empties every compartment (the vehicle goes away). */\n clear(): void\n}\n\nconst weightOf = (stack: StorageStack): number => stack.unitKg * stack.count\n\nexport function createVehicleStorage(options: VehicleStorageOptions = {}): VehicleStorage {\n const compartments = [...(options.compartments ?? [GLOVEBOX, trunkFor()])]\n const slots = new Map<CompartmentId, Array<StorageStack | null>>(compartments.map((c) => [c.id, Array.from({ length: c.slots }, () => null)]))\n const specOf = (id: CompartmentId): CompartmentSpec | undefined => compartments.find((c) => c.id === id)\n const load = (id: CompartmentId): number => (slots.get(id) ?? []).reduce((kg, s) => kg + (s ? weightOf(s) : 0), 0)\n const reachable = (id: CompartmentId, access: StorageAccess): boolean => {\n const spec = specOf(id)\n if (!spec) return false\n return spec.access === 'lid' ? access.lid >= 0.5 : access.gloveboxOpen && (access.seated || access.frontDoorOpen)\n }\n const place = (id: CompartmentId, stack: StorageStack): StoreResult => {\n const spec = specOf(id)\n const list = slots.get(id)\n if (!spec || !list) return 'missing'\n if (load(id) + weightOf(stack) > spec.capacityKg + 1e-9) return 'too_heavy'\n const same = stack.data === undefined ? list.findIndex((s) => s !== null && s.itemId === stack.itemId && s.data === undefined) : -1\n if (same >= 0) {\n const s = list[same] as StorageStack\n list[same] = { ...s, count: s.count + stack.count }\n return 'ok'\n }\n const free = list.indexOf(null)\n if (free < 0) return 'full'\n list[free] = { ...stack }\n return 'ok'\n }\n return {\n compartments,\n reachable,\n contents: (id) => [...(slots.get(id) ?? [])],\n loadKg: (id) => (id === undefined ? compartments.reduce((kg, c) => kg + load(c.id), 0) : load(id)),\n put(id, stack, access) {\n if (!specOf(id)) return 'missing'\n if (!reachable(id, access)) return 'shut'\n return place(id, stack)\n },\n take(id, slot, access) {\n const list = slots.get(id)\n if (!list || !reachable(id, access)) return null\n const stack = list[slot] ?? null\n if (stack) list[slot] = null\n return stack\n },\n stock(id, stacks) {\n return stacks.filter((s) => place(id, s) !== 'ok')\n },\n clear() {\n for (const list of slots.values()) list.fill(null)\n },\n }\n}\n","/**\n * The glass misting up from inside. The people in the cabin breathe water into its air and wet clothes from the rain bring more; the air\n * that comes in (an open window, the fan, the air conditioning that dries it) takes it out. Fog forms when that moisture is past what the glass\n * holds clear, which drops the colder the glass is than the cabin (a cold day, rain on the glass, speed); the demister blows dry, warm air on it and\n * clears it in a few seconds once the engine is warm. The wipers clean only the outside: they do nothing to it. Every number is an option.\n */\n\nexport interface WindshieldFogOptions {\n /** Moisture of the air outside, 0..1. Default 0.6. */\n outsideHumidity?: number\n /** Moisture one occupant breathes into the cabin, share of saturation per second. Default 0.004. */\n breath?: number\n /** Moisture of wet clothes in the rain, per second at full rain. Default 0.002. */\n wet?: number\n /** Air change of a shut cabin per second, and what a window fully down, the climate fan and the demister add to it. */\n air?: { shut: number; window: number; climate: number; demist: number }\n /** Degrees of glass below the cabin that bring the fog down to half the moisture (0 degrees: fog only at saturation). Default 15. */\n coldSpan?: number\n /** Fog builds up, clears on its own and clears under the warm demister, share of the glass per second. */\n rates?: { build: number; clear: number; demist: number }\n}\n\nexport interface WindshieldFogState {\n /** Moisture of the cabin's air, 0..1 (1 saturated). */\n humidity: number\n /** Share of the glass misted, 0..1. */\n fog: number\n}\n\nexport interface WindshieldFogStep {\n dt: number\n /** People inside. */\n occupants: number\n /** Air temperature outside and in the cabin, °C. */\n outsideC: number\n cabinC: number\n /** Rain on the glass, 0..1. */\n rain?: number\n /** Speed, m/s: the wind over the glass cools it. */\n speed?: number\n /** The windows' opening, 0..1 summed share (one window fully down is 0.25 of a four-door car's four). */\n windows?: number\n climate: { on: boolean; demist: boolean }\n /** How warm the engine is, 0..1 (the demister blows cold air from a cold engine: it dries but does not warm the glass). */\n engineWarm?: number\n}\n\nexport interface WindshieldFog {\n readonly state: WindshieldFogState\n step(params: WindshieldFogStep): WindshieldFogState\n /** Sets the moisture and the fog at once (a car found shut in the rain). */\n set(state: Partial<WindshieldFogState>): void\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.max(a, Math.min(b, x))\n\nexport function createWindshieldFog(options: WindshieldFogOptions = {}): WindshieldFog {\n const outside = options.outsideHumidity ?? 0.6\n const breath = options.breath ?? 0.004\n const wet = options.wet ?? 0.002\n const air = options.air ?? { shut: 0.002, window: 0.05, climate: 0.01, demist: 0.06 }\n const coldSpan = options.coldSpan ?? 15\n const rates = options.rates ?? { build: 0.05, clear: 0.03, demist: 0.25 }\n const state: WindshieldFogState = { humidity: outside, fog: 0 }\n return {\n state,\n step({ dt, occupants, outsideC, cabinC, rain = 0, speed = 0, windows = 0, climate, engineWarm = 1 }) {\n const exchange = air.shut + air.window * clamp(windows, 0, 1) + (climate.on ? air.climate : 0) + (climate.demist ? air.demist : 0)\n const source = breath * Math.max(0, occupants) + wet * clamp(rain, 0, 1) * (occupants > 0 ? 1 : 0)\n // the air conditioning dries what comes in: with it on, the cabin tends to the outside air with most of its water left on the evaporator\n const towards = climate.on ? outside * 0.4 : outside\n state.humidity = clamp(state.humidity + (source - exchange * (state.humidity - towards)) * dt, 0, 1)\n // the glass is colder than the cabin by the weather (an open window brings the cabin towards the air outside), the rain on it and the wind of\n // speed; the warm demister brings it up to the cabin\n const cold = Math.max(0, cabinC - outsideC) * (1 - 0.7 * clamp(windows, 0, 1)) + 6 * clamp(rain, 0, 1) + 2 * clamp(speed / 27.8, 0, 1)\n const warmed = climate.demist ? cold * (1 - 0.9 * clamp(engineWarm, 0, 1)) : cold\n const clearUpTo = 1 - 0.5 * clamp(warmed / coldSpan, 0, 1)\n const target = clamp((state.humidity - clearUpTo) * 6, 0, 1)\n const down = climate.demist ? rates.demist * (0.3 + 0.7 * clamp(engineWarm, 0, 1)) : rates.clear\n state.fog = target > state.fog ? Math.min(target, state.fog + rates.build * dt) : Math.max(target, state.fog - down * dt)\n return state\n },\n set(next) {\n if (next.humidity !== undefined) state.humidity = clamp(next.humidity, 0, 1)\n if (next.fog !== undefined) state.fog = clamp(next.fog, 0, 1)\n },\n }\n}\n","import type { BodyDesc, Curve, TrackDesc, VehicleDesc, WheelDesc } from '@adatechnology/game-physics'\n\nimport { FLAT_BELOW, RIM_FRICTION, RIM_RADIUS_SHARE, torqueAt } from './semi/driver'\nimport type { SemiPedal, SemiSimSpec, SemiTracks, SemiWheel, VehicleCondition } from './semi/types'\n\nconst GRAVITY = 9.81\n/** Where the torque curve still gives its torque before the redline cuts it (rpm under the redline). */\nconst CURVE_CUT_GAP_RPM = 1\n/** Share of the brake force the front axle takes, and of the handbrake force each locked wheel takes. */\nconst FRONT_BRAKE_SHARE = 0.6\nconst HANDBRAKE_SHARE = 0.5\n/** Suspension travel left when fully compressed, as a share of the free length. */\nconst SUSPENSION_MIN_SHARE = 0.4\n/** The most of the free length the static sag may take. */\nconst MAX_SAG = 0.5\n/** A motorcycle's lean spring and damper per kg m^2 of roll inertia (measured: the engine's own values are for a real bike's inertia), and its lean limit. */\nconst LEAN_SPRING_PER_INERTIA = 400\nconst LEAN_DAMPING_PER_INERTIA = 40\nconst LEAN_LIMIT = 0.7\n/** A track's lateral grip: with the tyre's own (about 0.9) the engine cannot swing a 40 t tracked vehicle round on the spot (it did not turn at all); at 0.6 and under it pivots (measured, specs/008 evidence T6.2c). */\nconst TRACK_LATERAL_FRICTION = 0.5\nconst WHEEL_WIDTH = 0.2\nconst CLUTCH_STRENGTH = 10\nconst CLUTCH_SLIP = 0.03\nconst BICYCLE_WHEEL_INERTIA = 0.1\n/** The slowest pedalling the cyclist's engine keeps his 250 W at: the engine's idle (`semiSpecFromStats` sets it for a bicycle). */\nconst BICYCLE_IDLE_CADENCE_RPM = 40\n/** A wheel with its tyre and brake weighs about 1.5% of the vehicle: its inertia `1/2 m r^2` is this per kg of the vehicle at a 0.32 m radius (0.83 kg m^2 on a 1 t car; the engine's own 0.9 is a car's, and four of them on a 150 kg bike weigh as much as the bike). */\nconst WHEEL_INERTIA_PER_MASS = 0.0008\nconst REFERENCE_RADIUS = 0.32\nconst MIN_WHEEL_INERTIA = 0.02\n/** The wheels' spin damping: the engine's own (0.2) is a drag of 7.8 N per m/s on a car's four wheels (0.4 kN at 50 m/s) the spec's rolling resistance already covers. */\nconst WHEEL_DAMPING = 0.02\n/** The engine's friction: the semi-simulation has none beyond its efficiency (the engine's own, 0.2, would take 85 N m of a 187 N m engine at 4 000 rpm). */\nconst ENGINE_DAMPING = 0.005\n/** The engine's rotating mass per N m of peak torque (kg m^2): 0.19 for a 190 N m car engine; the engine's own 0.5 is a third of a ton of inertia in first gear on a car and a ton on a bike. */\nconst ENGINE_INERTIA_PER_TORQUE = 0.001\n/** What a worn engine and a worn suspension keep of their torque and of their spring and damper (the semi-simulation's own floors). */\nconst ENGINE_FLOOR = 0.55\nconst SUSPENSION_FLOOR = 0.5\n/**\n * Gearbox timing, seconds (the engine's own 0.5 + 0.3 + 0.5 is a slow truck's box and a quarter of a 0-100 km/h of a hatch): the shift itself, the clutch closing after it, and the wait before the next shift.\n * The card has no gearbox type (the semi-simulation shifts automatically and instantly), so a car gets the middle of the real range: a modern automatic or dual-clutch shifts in 0.1-0.3 s and a manual\n * in 0.3-0.6 s of a practised hand, 0.2 s of torque interruption plus 0.1 s of hold-off in all. A motorcycle's box (dog rings, no torque converter, a short clutch) shifts in about 0.1-0.2 s.\n * An estimate from those ranges (manufacturer shift-time figures, e.g. ZF 8HP ~0.2 s, dual-clutch < 0.1 s); the measurement that tied these to real 0-100 km/h times is in specs/008 evidence T6.2b.\n */\nconst CAR_TRANSMISSION = { switchTime: 0.1, clutchReleaseTime: 0.1, switchLatency: 0.1 } as const\nconst MOTORCYCLE_TRANSMISSION = { switchTime: 0.05, clutchReleaseTime: 0.07, switchLatency: 0.05 } as const\n\n/** A cyclist as the engine (the spec's own `pedal` when the options do not give one). */\nexport type PedalOptions = SemiPedal\n\nexport interface VehicleFromSemiOptions {\n /** The body: shape, pose, user, velocity, layer. Its origin is the centre of mass (`centreAtOrigin` is set); mass and inertia come from the spec. */\n readonly chassis: Omit<BodyDesc, 'motion' | 'mass' | 'inertia' | 'centreAtOrigin'>\n /** What is wrong with it now: a flat tyre or a bare rim rides on the rim's radius with its grip, a worn engine gives less, worn brakes brake less. */\n readonly condition?: VehicleCondition\n readonly wheelWidth?: number\n /** Rotational inertia of each wheel with its tyre, kg m^2: by default 0.0008 per kg of the vehicle (a bicycle: 0.1). */\n readonly wheelInertia?: number\n /** A bicycle's engine in place of `spec.engine` (`spec.pedal` when omitted). */\n readonly pedal?: PedalOptions\n}\n\n/** The clutch passes `strength x (engine speed - wheel speed)`: strong enough that the full torque goes through with 3% of slip at the top of the range (never under the engine's own 10: a bicycle's 28 N m at 120 rpm needs 75). */\nconst clutchFor = (peakTorque: number, maxRpm: number): number => Math.max(CLUTCH_STRENGTH, peakTorque / (CLUTCH_SLIP * ((maxRpm * 2 * Math.PI) / 60)))\n\nconst clamp = (x: number, low: number, high: number): number => Math.max(low, Math.min(high, x))\n\n/** A cyclist holds his watts down to the idle cadence (the torque rises as the cadence falls, a start in a low gear pushes hard), and has none past the redline: torque by cadence over the redline cadence. */\nconst pedalCurve = (pedal: SemiPedal): Curve => {\n const redline = pedal.cadenceRpm * 1.5\n const idle = BICYCLE_IDLE_CADENCE_RPM\n const heldWatts = (cadence: number): number => pedal.cadenceRpm / cadence\n return [[0, heldWatts(idle)], [idle / redline, heldWatts(idle)], [pedal.cadenceRpm / redline, 1], [1, 0]]\n}\n\nconst torqueCurve = (spec: SemiSimSpec): Curve => {\n const { idleRpm, peakRpm, redlineRpm, peakTorque } = spec.engine\n const at = (rpm: number): number => torqueAt(spec, rpm) / peakTorque\n return [[0, at(0)], [idleRpm / redlineRpm, at(idleRpm)], [peakRpm / redlineRpm, at(peakRpm)], [(redlineRpm - CURVE_CUT_GAP_RPM) / redlineRpm, at(redlineRpm - CURVE_CUT_GAP_RPM)], [1, 0]]\n}\n\n/** Grip across the wheel by slip angle (degrees): rising to `friction` where `corneringStiffness` says, then easing to 0.75 of it sideways. */\nconst lateralCurve = (friction: number, corneringStiffness: number): Curve => [[0, 0], [((friction / corneringStiffness) * 180) / Math.PI, friction], [90, 0.75 * friction]]\n\n/** Grip along the wheel by slip ratio: the peak at 6% slip, 0.8 of it locked. */\nconst longitudinalCurve = (friction: number): Curve => [[0, 0], [0.06, friction], [1, 0.8 * friction]]\n\nconst isFlat = (condition: VehicleCondition, index: number): boolean => (condition.tyres?.[index] ?? 1) < FLAT_BELOW || condition.rims?.[index] === true\n\ninterface WheelContext {\n readonly spec: SemiSimSpec\n readonly condition: VehicleCondition\n readonly options: VehicleFromSemiOptions\n /** The x the front axle starts at: wheels ahead of the mean x. */\n readonly frontFrom: number\n readonly frontCount: number\n readonly rearCount: number\n readonly handbrakeCount: number\n}\n\nconst wheelOf = (wheel: SemiWheel, index: number, context: WheelContext): WheelDesc => {\n const { spec, condition, options } = context\n const cornerMass = spec.mass / spec.wheels.length\n const wear = SUSPENSION_FLOOR + (1 - SUSPENSION_FLOOR) * clamp(condition.suspension ?? 1, 0, 1)\n const free = spec.suspension.restLength\n // the spec's spring is a car's: a heavy vehicle that kept it would sag past its own travel and sit on its belly, so the spring stiffens (the damper with it) until the sag is the share MAX_SAG of the travel\n const stiffening = Math.max(1, (cornerMass * GRAVITY) / (MAX_SAG * free * spec.suspension.spring * wear))\n const spring = spec.suspension.spring * wear * stiffening\n const damper = spec.suspension.damper * wear * stiffening\n const sag = (cornerMass * GRAVITY) / spring\n const flat = isFlat(condition, index)\n const rimRadius = spec.rimRadius ?? RIM_RADIUS_SHARE * spec.wheelRadius\n const friction = flat ? RIM_FRICTION : spec.tyre.friction\n const front = wheel.x >= context.frontFrom\n const brakeShare = front ? FRONT_BRAKE_SHARE / context.frontCount : (1 - FRONT_BRAKE_SHARE) / context.rearCount\n const brakeTorque = spec.brakeForce * clamp(condition.brakes ?? 1, 0, 1) * spec.wheelRadius * brakeShare\n return {\n // x is to the vehicle's left and z ahead; the semi-simulation has z to the right\n position: [-wheel.z, spec.wheelRadius - spec.centreHeight + (free - sag), wheel.x],\n radius: flat ? rimRadius : spec.wheelRadius,\n width: options.wheelWidth ?? WHEEL_WIDTH,\n suspensionMin: free * SUSPENSION_MIN_SHARE,\n suspensionMax: free,\n frequency: Math.sqrt(spring / cornerMass) / (2 * Math.PI),\n damping: damper / (2 * Math.sqrt(spring * cornerMass)),\n maxSteer: wheel.steer ? spec.maxSteer : 0,\n driven: spec.fourWheelDrive || wheel.drive === true,\n maxBrakeTorque: brakeTorque,\n maxHandBrakeTorque: wheel.handbrake ? (spec.brakeForce * spec.wheelRadius * HANDBRAKE_SHARE) / context.handbrakeCount : 0,\n inertia: options.wheelInertia ?? (options.pedal ? BICYCLE_WHEEL_INERTIA : Math.max(MIN_WHEEL_INERTIA, WHEEL_INERTIA_PER_MASS * spec.mass * (spec.wheelRadius / REFERENCE_RADIUS) ** 2)),\n angularDamping: WHEEL_DAMPING,\n longitudinalFriction: longitudinalCurve(friction),\n lateralFriction: lateralCurve(friction, spec.tyre.corneringStiffness),\n }\n}\n\nconst wheelContext = (spec: SemiSimSpec, options: VehicleFromSemiOptions): WheelContext => {\n const meanX = spec.wheels.reduce((sum, wheel) => sum + wheel.x, 0) / spec.wheels.length\n const frontCount = spec.wheels.filter((wheel) => wheel.x >= meanX).length\n return {\n spec,\n condition: options.condition ?? {},\n options,\n frontFrom: meanX,\n frontCount,\n rearCount: Math.max(1, spec.wheels.length - frontCount),\n handbrakeCount: Math.max(1, spec.wheels.filter((wheel) => wheel.handbrake).length),\n }\n}\n\nconst inertiaOf = (spec: SemiSimSpec): readonly [number, number, number] => {\n const xs = spec.wheels.map((wheel) => wheel.x)\n const zs = spec.wheels.map((wheel) => wheel.z)\n const wheelbase = Math.max(...xs) - Math.min(...xs)\n const track = Math.max(...zs) - Math.min(...zs)\n // the semi-simulation's own moments: pitch and roll with 1 m of height, yaw from the plan\n return [(spec.mass * (wheelbase * wheelbase + 1)) / 12, spec.yawInertia ?? (spec.mass * (wheelbase * wheelbase + track * track)) / 12, (spec.mass * (track * track + 1)) / 12]\n}\n\nconst drivetrainOf = (spec: SemiSimSpec, options: VehicleFromSemiOptions): Pick<VehicleDesc, 'maxTorque' | 'engineDamping' | 'engineInertia' | 'minRpm' | 'maxRpm' | 'gears' | 'reverseGears' | 'differentialRatio' | 'torqueCurve' | 'transmission'> => {\n const pedal = options.pedal ?? spec.pedal\n if (pedal) {\n const crankSpeed = (pedal.cadenceRpm * 2 * Math.PI) / 60\n return {\n engineDamping: ENGINE_DAMPING,\n engineInertia: ENGINE_INERTIA_PER_TORQUE * (pedal.watts / crankSpeed),\n maxTorque: (pedal.watts / crankSpeed) * spec.efficiency,\n minRpm: 0,\n maxRpm: pedal.cadenceRpm * 1.5,\n // the engine turns once for every wheel turn / ratio: a gear of 2 turns the wheel twice a pedal turn\n gears: pedal.gears.map((ratio) => 1 / ratio),\n reverseGears: [],\n differentialRatio: 1,\n torqueCurve: pedalCurve(pedal),\n transmission: { shiftUpRpm: pedal.cadenceRpm * 0.95, shiftDownRpm: pedal.cadenceRpm * 0.5, clutchStrength: clutchFor(pedal.watts / crankSpeed, pedal.cadenceRpm * 1.5) },\n }\n }\n const health = clamp(options.condition?.engine ?? 1, 0, 1)\n return {\n engineDamping: ENGINE_DAMPING,\n engineInertia: ENGINE_INERTIA_PER_TORQUE * spec.engine.peakTorque,\n maxTorque: spec.engine.peakTorque * (spec.physicsTorqueScale ?? 1) * spec.efficiency * (ENGINE_FLOOR + (1 - ENGINE_FLOOR) * health),\n minRpm: spec.engine.idleRpm,\n maxRpm: spec.engine.redlineRpm,\n gears: spec.gears,\n reverseGears: [-spec.reverseRatio],\n differentialRatio: spec.finalDrive,\n torqueCurve: torqueCurve(spec),\n transmission: {\n shiftUpRpm: spec.engine.redlineRpm * spec.upshiftFraction,\n shiftDownRpm: spec.engine.redlineRpm * spec.downshiftFraction,\n clutchStrength: clutchFor(spec.engine.peakTorque, spec.engine.redlineRpm),\n ...(spec.wheels.length === 2 ? MOTORCYCLE_TRANSMISSION : CAR_TRANSMISSION),\n },\n }\n}\n\n/** The road wheels of a tracked vehicle, left track (the +x side of the chassis) first, as the wheels of a spec; each track is `TrackDesc` over its own wheels, driven at the rear. */\nconst trackedOf = (spec: SemiSimSpec, tracks: SemiTracks): { readonly spec: SemiSimSpec; readonly tracks: NonNullable<VehicleDesc['tracks']> } => {\n const count = Math.max(2, tracks.roadWheels)\n const alongX = (index: number): number => tracks.rearX + ((tracks.frontX - tracks.rearX) * index) / (count - 1)\n // the spec's z is to the right: the left track is the negative z\n const wheels: SemiWheel[] = [-1, 1].flatMap((side) => Array.from({ length: count }, (_, index) => ({ x: alongX(index), z: (side * tracks.gauge) / 2 })))\n const friction = spec.tyre.friction\n const side = (first: number): TrackDesc => ({ wheels: Array.from({ length: count }, (_, index) => first + index), drivenWheel: first, longitudinalFriction: friction, lateralFriction: TRACK_LATERAL_FRICTION, maxBrakeTorque: (spec.brakeForce * spec.wheelRadius) / 2 })\n return { spec: { ...spec, wheels }, tracks: [side(0), side(count)] }\n}\n\n/**\n * The semi-simulation's vehicle as a physics-engine vehicle (design 7.1): the wheels where the spec has them (x to the left, z ahead, from the centre of mass),\n * the suspension as a frequency and a damping ratio from the spring and the corner's mass, the engine and gearbox, the tyres as the two grip curves, the brake\n * force split 60/40, the mass and the moments of the spec. Two wheels make a motorcycle (a bicycle with `pedal`). The ground's grip is the ground body's own\n * friction, and the air drag and the rolling resistance are `resistanceImpulse`.\n */\nexport const vehicleDescFromSemi = (spec: SemiSimSpec, options: VehicleFromSemiOptions): VehicleDesc => {\n const tracked = spec.tracks ? trackedOf(spec, spec.tracks) : undefined\n const body = tracked ? tracked.spec : spec\n const context = wheelContext(body, options)\n const inertia = inertiaOf(spec)\n const bike = body.wheels.length === 2\n return {\n // no damping of the body's own: it would be a drag of 0.05 m/s per m/s (1.8 kN at 28 m/s on a 1.3 t car) the spec never asked for; `resistanceImpulse` is the drag\n chassis: { linearDamping: 0, angularDamping: 0, ...options.chassis, motion: 'dynamic', mass: spec.mass, inertia, centreAtOrigin: true, allowSleep: true },\n wheels: body.wheels.map((wheel, index) => wheelOf(wheel, index, context)),\n ...drivetrainOf(spec, options),\n ...(tracked ? { controller: 'tracked' as const, tracks: tracked.tracks } : {}),\n ...(bike\n ? { controller: 'motorcycle' as const, motorcycle: { maxLeanAngle: LEAN_LIMIT, leanSpring: LEAN_SPRING_PER_INERTIA * inertia[2], leanDamping: LEAN_DAMPING_PER_INERTIA * inertia[2] } }\n : {}),\n }\n}\n","import type { VehicleInput } from '@adatechnology/game-physics'\n\nimport type { SemiInput } from './semi/types'\n\n/** What the vehicle can do now (the fields of the destructible's `status()` this needs: any object with them works). */\nexport interface DriveStatus {\n /** Engine runs and the gearbox transmits. */\n readonly canDrive: boolean\n /** 1 is normal; this many times longer to stop with worn or missing brakes. */\n readonly brakeFactor: number\n /** -1..1: the sideways pull of a damaged steering or flat tyres (negative is left). */\n readonly steerPull: number\n}\n\nexport interface PhysicsInputOptions {\n /** The steering follows its target by `min(1, steerResponse dt)`: the arcade's 5 per second. */\n readonly steerResponse?: number\n /** Lock lost per m/s of speed (the steering assistance), and the share of it that is never lost. */\n readonly steerFalloff?: number\n readonly steerFloor?: number\n /** Below this speed (m/s), forward or back, a brake asks for reverse and a throttle for forward. */\n readonly reverseBelow?: number\n /** Share of the full lock a full `steerPull` pulls with. */\n readonly pullShare?: number\n}\n\nexport interface PhysicsInputParams {\n readonly input: SemiInput\n /** Signed speed along the front of the vehicle, m/s. */\n readonly speed: number\n /** Seconds since the last call. */\n readonly dt: number\n readonly status?: Partial<DriveStatus>\n}\n\nexport interface PhysicsInputMapper {\n /** The engine's input for this step. It keeps the filtered steering between calls. */\n map(params: PhysicsInputParams): VehicleInput\n reset(): void\n}\n\n/** Starting values, to be calibrated against the vehicle on the engine (T6.2b): the response is the arcade's, the assistance and the pull are not measured yet. */\nexport const DEFAULT_PHYSICS_INPUT: Required<PhysicsInputOptions> = { steerResponse: 5, steerFalloff: 0.012, steerFloor: 0.4, reverseBelow: 0.5, pullShare: 0.2 }\n\nconst clamp = (x: number, low: number, high: number): number => Math.max(low, Math.min(high, x))\n\n/**\n * Pedals to the engine's input (design 7.2): throttle and brake cancel into one pedal; forward from a stop or above, hard brake against the move, reverse from\n * a stop; the power limit of traction control and a hurt engine cuts the throttle; the brake factor of a worn brake softens the brake; steering is the kit's\n * positive-left turned into the engine's positive-right, filtered, eased with the speed, and pulled by a damaged steering. A vehicle that cannot drive gets no\n * throttle (the brake and the steering still work).\n */\nexport const createPhysicsInputMapper = (options: PhysicsInputOptions = {}): PhysicsInputMapper => {\n const rules = { ...DEFAULT_PHYSICS_INPUT, ...options }\n let steering = 0\n return {\n reset() {\n steering = 0\n },\n map({ input, speed, dt, status }) {\n const pedal = clamp(input.throttle, 0, 1) - clamp(input.brake, 0, 1)\n const powerLimit = clamp(input.powerLimit ?? 1, 0, 1)\n const canDrive = status?.canDrive ?? true\n const brakeSoftness = 1 / Math.max(1, status?.brakeFactor ?? 1)\n let forward = 0\n let brake = 0\n if (pedal > 0) {\n if (speed < -rules.reverseBelow) brake = pedal * brakeSoftness\n else forward = pedal * powerLimit\n } else if (pedal < 0) {\n if (speed > rules.reverseBelow) brake = -pedal * brakeSoftness\n else forward = pedal * powerLimit\n }\n const lock = Math.max(rules.steerFloor, 1 - rules.steerFalloff * Math.abs(speed))\n const target = -clamp(input.steer, -1, 1) * lock\n steering += (target - steering) * Math.min(1, dt * rules.steerResponse)\n const pull = clamp(status?.steerPull ?? 0, -1, 1) * rules.pullShare\n return { forward: canDrive ? forward : 0, right: clamp(steering + pull, -1, 1), brake, handBrake: input.handbrake ? 1 : 0 }\n },\n }\n}\n","import type { Vec3 } from '@adatechnology/game-physics'\n\nimport type { SemiSimSpec } from './semi/types'\n\nconst GRAVITY = 9.81\n/** Under this speed (m/s) the rolling resistance fades out instead of flipping the direction of the velocity. */\nconst ROLLING_FADE_SPEED = 0.5\n\n/**\n * The impulse (N s) the air and the tyres take from a vehicle moving at `velocity` (its horizontal part) over one step `dt`, for the body's centre of mass: `-drag |v| v dt` for the air\n * (the spec's drag is `0.5 rho Cd A`) and `-rolling m g dt` along the velocity for the tyres. Apply it every fixed step in the `actors` phase; the wheels' own\n * contact does not know either.\n */\nexport const resistanceImpulse = (spec: Pick<SemiSimSpec, 'drag' | 'rolling' | 'mass'>, velocity: Vec3, dt: number): Vec3 => {\n const speed = Math.hypot(velocity[0], velocity[2])\n if (speed === 0) return [0, 0, 0]\n const rolling = spec.rolling * spec.mass * GRAVITY * Math.min(1, speed / ROLLING_FADE_SPEED)\n const along = -(spec.drag * speed * speed + rolling) * dt\n return [(velocity[0] / speed) * along, 0, (velocity[2] / speed) * along]\n}\n","import type { BodyId, PhysicsLoop, Quat, Vec3 } from '@adatechnology/game-physics'\n\nimport { defaultArcadeSpec } from './arcade'\nimport type { RunOverRules } from './arcade'\nimport { runOver } from './run-over'\nimport type { RunOverOutcome } from './run-over'\n\n/** What the run-over needs of the crowd: `game-crowd`'s `Crowd` is one as it is, and nothing here imports it. */\nexport type RunOverCrowd = {\n readonly store: {\n readonly n: number\n readonly x: Float32Array\n readonly z: Float32Array\n readonly vx: Float32Array\n readonly vz: Float32Array\n readonly mass: Float32Array\n readonly identity: Uint32Array\n }\n damage(index: number, hit: { readonly region: 1; readonly amount: number; readonly distance: number }): { readonly died: boolean }\n kill(index: number): void\n knockDown(index: number, velocity: { readonly x: number; readonly z: number }): void\n}\n\n/** The kinematic capsules of the agents (`createAgentBodies` of `game-crowd`): capsule `i` follows agent `i`. */\nexport type RunOverAgents = { readonly count: number; bodyOf(index: number): BodyId | undefined }\n\n/** A car the run-over watches: its chassis body and the half sizes of its box (x right, y up, z forward, as the engine's vehicles). */\nexport type RunOverVehicle = { readonly body: BodyId; readonly half: Vec3 }\n\nexport type RunOverHit = {\n readonly vehicle: BodyId\n readonly agent: number\n readonly outcome: RunOverOutcome\n /** Closing speed (m/s) and the energy the hit dissipated: half the reduced mass times the closing speed squared (J). */\n readonly speed: number\n readonly energy: number\n /** What `RunOverRules.killVehicleDamage` says the car takes: 0 unless the body died. */\n readonly vehicleDamage: number\n}\n\nexport type RunOverOptions = {\n readonly crowd: RunOverCrowd\n readonly agents: RunOverAgents\n readonly rules?: Partial<RunOverRules>\n /** Told of each hit inside the fixed step (the host's sound, blood, damage to the car). */\n readonly onHit?: (hit: RunOverHit) => void\n}\n\nexport type RunOver = {\n /** Watches a car from the next step on; returns the way to stop. */\n track(vehicle: RunOverVehicle): () => void\n /** The velocity a body that dies in this very call carries (a `CorpseBodies.add` made in the crowd's `corpses` listener reads it); undefined outside a hit. */\n readonly dyingVelocity: Vec3 | undefined\n dispose(): void\n}\n\nconst byIndexDescending = (a: number, b: number): number => b - a\n\n/** Slowest car (m/s) that runs anyone over. */\nconst MIN_SPEED = 1\n/** Mass (kg) of the body the arcade damage (`knockDamage`) is written for, and of an agent whose mass is not seated. */\nconst REFERENCE_MASS = 70\n/** Speed (m/s) a pushed body is moved aside at. */\nconst PUSH_ASIDE_SPEED = 1\n\n/**\n * Cars against the crowd's agents, in the loop's `actors` phase (veiculos.md 7.8). The `vehicle` and `agent` layers do not meet, because an agent is kinematic and would stop a truck as a\n * wall: the car sweeps its box over the step against the `agent` layer instead. A body in the way meets the car as a perfectly inelastic hit (momentum kept: the car loses `m / (M + m)`\n * of the closing speed and the body leaves at the common speed), which `RunOverRules` classes by the closing speed: pushed aside below `knockSpeed` (the car held by `holdDrag`), knocked\n * down (damage `knockDamage` by the energy, stunned) up to `killSpeed`, killed above it. Whoever dies is told to the crowd with the car's velocity in `dyingVelocity`.\n */\nexport const createRunOver = (loop: PhysicsLoop, options: RunOverOptions): RunOver => {\n const { crowd, agents } = options\n const rules = { ...defaultArcadeSpec.runOver, ...options.rules }\n const world = loop.world\n const vehicles: RunOverVehicle[] = []\n /** The agents each car already struck and still overlaps: a body knocked down is under the car for a few steps and is struck once. */\n const struck = new Map<RunOverVehicle, Set<number>>()\n const hits: BodyId[] = []\n const pose = new Float64Array(7)\n const velocity = new Float64Array(6)\n const box = { kind: 'box' as const, half: [0, 0, 0] as [number, number, number] }\n const centre: [number, number, number] = [0, 0, 0]\n const rotation: [number, number, number, number] = [0, 0, 0, 1]\n const impulse: [number, number, number] = [0, 0, 0]\n const point: [number, number, number] = [0, 0, 0]\n const direction: [number, number] = [0, 0]\n const car = { speed: 0, mass: 0 }\n const found: number[] = []\n const now = new Set<number>()\n /** The index of each agent's capsule, made when a hit needs it and again after a hit that may have moved the last agent into a slot. */\n const indexOfBody = new Map<BodyId, number>()\n let isIndexStale = true\n let dying: Vec3 | undefined\n let diedLast = false\n\n /** The agent indices whose capsule is among `bodies`, descending: a death moves the last agent into its slot, so the ones not yet handled keep their index. */\n const agentsOf = (bodies: readonly BodyId[]): number[] => {\n if (isIndexStale) {\n indexOfBody.clear()\n for (let index = 0; index < agents.count; index++) {\n const body = agents.bodyOf(index)\n if (body !== undefined) indexOfBody.set(body, index)\n }\n isIndexStale = false\n }\n found.length = 0\n for (const body of bodies) {\n const index = indexOfBody.get(body)\n if (index !== undefined) found.push(index)\n }\n return found.sort(byIndexDescending)\n }\n\n /** What the body in the way does to the car and to itself; returns the momentum (N s) the car loses. */\n const strike = (index: number, outcome: RunOverOutcome, direction: readonly [number, number], hit: { readonly reduced: number; readonly closing: number; readonly common: number; readonly carMomentum: number }, h: number): number => {\n const { store } = crowd\n if (outcome === 'push') {\n store.x[index]! += -direction[1] * PUSH_ASIDE_SPEED * h\n store.z[index]! += direction[0] * PUSH_ASIDE_SPEED * h\n return hit.carMomentum * (1 - Math.exp(-rules.holdDrag * h))\n }\n dying = [direction[0] * hit.common, 0, direction[1] * hit.common]\n if (outcome === 'kill') crowd.kill(index)\n else if (!crowd.damage(index, { region: 1, amount: (hit.reduced / REFERENCE_MASS) * hit.closing * hit.closing * rules.knockDamage, distance: 0 }).died) {\n dying = undefined\n crowd.knockDown(index, { x: direction[0] * hit.common, z: direction[1] * hit.common })\n }\n const died = dying !== undefined\n dying = undefined\n diedLast = died\n return hit.reduced * hit.closing\n }\n\n const hitOne = (vehicle: RunOverVehicle, index: number, direction: readonly [number, number], car: { speed: number; readonly mass: number }, h: number): RunOverOutcome | undefined => {\n const { store } = crowd\n const mass = store.mass[index]! > 0 ? store.mass[index]! : REFERENCE_MASS\n const closing = car.speed - (store.vx[index]! * direction[0] + store.vz[index]! * direction[1])\n if (closing <= 0) return undefined\n const reduced = (mass * car.mass) / (mass + car.mass)\n const outcome = runOver(closing, rules)\n diedLast = false\n const lost = strike(index, outcome, direction, { reduced, closing, common: car.speed - (mass / (mass + car.mass)) * closing, carMomentum: car.mass * car.speed }, h)\n car.speed -= lost / car.mass\n impulse[0] = -direction[0] * lost\n impulse[2] = -direction[1] * lost\n world.addImpulse(vehicle.body, impulse, point)\n options.onHit?.({ vehicle: vehicle.body, agent: index, outcome, speed: closing, energy: 0.5 * reduced * closing * closing, vehicleDamage: diedLast ? rules.killVehicleDamage : 0 })\n return outcome\n }\n\n const sweep = (vehicle: RunOverVehicle, h: number): void => {\n world.readVelocity(vehicle.body, velocity, 0)\n const speed = Math.hypot(velocity[0]!, velocity[2]!)\n if (speed < MIN_SPEED) return\n world.readPose(vehicle.body, pose, 0)\n direction[0] = velocity[0]! / speed\n direction[1] = velocity[2]! / speed\n const reach = (speed * h) / 2\n box.half[0] = vehicle.half[0] + rules.margin\n box.half[1] = vehicle.half[1]\n box.half[2] = vehicle.half[2] + rules.margin + reach\n centre[0] = pose[0]! + direction[0] * reach\n centre[1] = pose[1]!\n centre[2] = pose[2]! + direction[1] * reach\n for (let k = 0; k < 4; k++) rotation[k] = pose[3 + k]!\n point[1] = pose[1]!\n if (world.overlapShape(box, centre, rotation as Quat, hits, { layers: ['agent'] }) === 0) {\n struck.delete(vehicle)\n return\n }\n car.speed = speed\n car.mass = world.massOf(vehicle.body)\n let before = struck.get(vehicle)\n if (!before) {\n before = new Set<number>()\n struck.set(vehicle, before)\n }\n for (const index of agentsOf(hits)) {\n const identity = crowd.store.identity[index]!\n if (before.has(identity)) {\n now.add(identity)\n continue\n }\n point[0] = crowd.store.x[index]!\n point[2] = crowd.store.z[index]!\n const outcome = hitOne(vehicle, index, direction, car, h)\n if (outcome === 'push') continue\n now.add(identity)\n if (outcome !== undefined) isIndexStale = true\n }\n before.clear()\n for (const identity of now) before.add(identity)\n now.clear()\n }\n\n const beforeStep = (h: number): void => {\n isIndexStale = true\n for (const vehicle of vehicles) sweep(vehicle, h)\n }\n\n const removePhase = loop.add({ beforeStep }, 'actors')\n return {\n track: (vehicle) => {\n vehicles.push(vehicle)\n return () => {\n const at = vehicles.indexOf(vehicle)\n if (at >= 0) vehicles.splice(at, 1)\n struck.delete(vehicle)\n }\n },\n get dyingVelocity() {\n return dying\n },\n dispose: () => {\n removePhase()\n vehicles.length = 0\n struck.clear()\n },\n }\n}\n"],"mappings":";AAoEO,IAAM,oBAAgC;AAAA,EAC3C,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,OAAO;AAAA,EACP,oBAAoB;AAAA,EACpB,cAAc;AAAA,EACd,MAAM;AAAA,EACN,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,UAAU;AAAA,EACV,eAAe;AAAA,EACf,WAAW;AAAA,EACX,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,wBAAwB;AAAA,EACxB,iBAAiB;AAAA,EACjB,OAAO,EAAE,UAAU,KAAK,aAAa,GAAG,QAAQ,GAAG,cAAc,IAAI,WAAW,GAAG,YAAY,KAAK,QAAQ,OAAO,aAAa,GAAG;AAAA,EACnI,SAAS,EAAE,YAAY,GAAG,WAAW,GAAG,aAAa,KAAK,aAAa,KAAK,aAAa,KAAK,UAAU,GAAG,WAAW,MAAM,mBAAmB,GAAG,UAAU,KAAK,QAAQ,IAAI;AAC/K;AAKO,SAAS,eAAe,MAA4C,GAAW,GAAW,KAAsC;AACrI,QAAM,IAAI,KAAK,IAAI,GAAG;AACtB,QAAM,IAAI,KAAK,IAAI,GAAG;AACtB,QAAM,KAAK,KAAK,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