@adatechnology/game-vehicles-proving 0.1.13 → 0.2.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/README.md +13 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.global.js +638 -11
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +14 -8
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/index.global.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/hands.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/index.ts","../../game-vehicles-driving/src/arcade.ts","../../game-vehicles-driving/src/run-over.ts","../../game-vehicles-driving/src/semi/fuel.ts","../../game-vehicles-driving/src/semi/surfaces.ts","../../game-vehicles-driving/src/semi/driver.ts","../../game-vehicles-driving/src/semi/impact.ts","../../game-vehicles-driving/src/semi/from-stats.ts","../../game-vehicles-driving/src/driving-aids.ts","../../game-vehicles-driving/src/controls.ts","../../game-vehicles-driving/src/semi/condition.ts","../../game-vehicles-driving/src/systems.ts","../../game-vehicles-driving/src/ejection.ts","../../game-vehicles-driving/src/parking-sensor.ts","../../game-vehicles-driving/src/storage.ts","../../game-vehicles-driving/src/windshield-fog.ts","../src/ranges.ts","../src/run.ts","../src/tests.ts","../src/certificate.ts","../src/fleet.ts"],"sourcesContent":["export { certify, gateVehicles, statusOf, withResult } from './certificate'\nexport type { CertifyOptions, GateOptions, SignOff } from './certificate'\nexport { DEFAULT_DENSITY, subjectFromCard } from './fleet'\nexport type { VehicleCardData } from './fleet'\nexport { accelerationRange, brakeRange, defaultRangeTable, dryBrakeRange, expectedAcceleration, inRange, topSpeedRange, turnCircleRange, wetBrakeRange } from './ranges'\nexport type { RangeTable } from './ranges'\nexport { runTest, startRun, subjectSpec } from './run'\nexport type { ProvingRun, RunOptions } from './run'\nexport { createProvingTests, defaultProvingTests } from './tests'\nexport type { ProvingTestOptions, ProvingTestRegistry } from './tests'\nexport type {\n ProvingCertificate,\n ProvingDomain,\n ProvingMemo,\n ProvingProcedure,\n ProvingRange,\n ProvingResult,\n ProvingSubject,\n ProvingTest,\n ProvingTestKind,\n ProvingVerdict,\n} from './types'\n","import type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n /**\n * Kilograms of TNT equivalent of the charge. With it a body is pushed by the blast wave itself (`blast-impulse`), and the shove of loose items keeps this module's rule; without it the body\n * takes the charge from `energy` by `BlastImpulseOptions.tntPerJoule`.\n */\n readonly tnt?: number\n /** Inside this radius (metres) the blast is lethal: a body there that the blast reaches (not behind cover) goes down, wounded, wherever the wave pushed it. */\n readonly lethalRadius?: number\n}\n\n/** What a blast does to one body: how fast it leaves (m/s), the unit direction it leaves in, and how far from the centre it was. */\nexport interface BlastShove {\n readonly speed: number\n readonly direction: Vec3\n readonly distance: number\n /** The falloff applied, 0..1. */\n readonly falloff: number\n}\n\nconst clampShare = (share: number): number => Math.min(1, Math.max(0, share))\n\n/**\n * The shove a blast gives to a body of `mass` kg whose centre is at `position`: away from the centre, lifted a little, with the speed\n * `sqrt(reach) * min(maxSpeed, sqrt(2 * energy * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n // cover takes its share off the push itself, past the cap too: a light thing behind a cupboard is not thrown as fast as one in the open\n const reach = clampShare(blast.reach ?? 1)\n const speed = Math.sqrt(reach) * Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * o.coupling) / mass)) * falloff\n if (!(speed >= o.minSpeed)) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const direction: Vec3 = distance > 1e-4 ? [dx / distance, dy / distance + o.lift, dz / distance] : [0, 1, 0]\n const length = Math.hypot(direction[0], direction[1], direction[2])\n return { speed, direction: [direction[0] / length, direction[1] / length, direction[2] / length], distance, falloff }\n}\n","/**\n * The push a blast gives a standing body, from the physics of the blast wave and not from a game coupling: the impulse of the wave per square metre at a distance from a charge of\n * `tnt` kg of TNT equivalent (Kinney and Graham's fit of the side-on impulse, scaled by the cube root of the charge), reflected on the body, over the area the body shows the wave,\n * divided by its mass. A hand grenade at 3 m gives a person a few tenths of a metre per second; what floors that person is the fragments, not the wave. A big charge close throws.\n */\n\n/** The numbers of the body a blast wave pushes. All have a default for a standing adult. */\nexport interface BlastImpulseOptions {\n /** Square metres of the body the wave meets: about 1.75 m tall by 0.4 m wide (default 0.7). */\n readonly bodyArea?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised (default 0.15: the wave runs along the ground). */\n readonly lift?: number\n /** Below this speed (m/s) the body does not move (default 0.3). */\n readonly minSpeed?: number\n /**\n * Kilograms of TNT per joule of the blast `energy`, for a blast that does not say its charge (`BlastSource.tnt`). Default 0.24 / 200000: the arsenal's energy scale, where the M67 (180 g\n * of Composition B, 0.24 kg of TNT) is 200 kJ. It is a game equivalence for blasts without a charge, not a physical constant.\n */\n readonly tntPerJoule?: number\n}\n\nexport const DEFAULT_BLAST_IMPULSE: Readonly<Required<BlastImpulseOptions>> = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 200000 }\n\n/** Closest distance (m) the fit is read at: inside it the charge is in contact and the body is torn apart anyway. */\nconst NEAREST = 0.3\n\n/**\n * Side-on (incident) specific impulse of the wave, in Pa·s, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `I/W^(1/3) = 0.067 sqrt(1 + (Z/0.23)^4) / (Z^2 (1 + (Z/1.55)^3)^(1/3))` bar·ms per kg^(1/3), with the scaled distance `Z = R / W^(1/3)`.\n */\nexport function sideOnImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, NEAREST) / w3\n const scaled = (0.067 * Math.sqrt(1 + (z / 0.23) ** 4)) / (z * z * Math.cbrt(1 + (z / 1.55) ** 3))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/** Sea-level atmospheric pressure, Pa. */\nconst ATMOSPHERE = 101325\n\n/**\n * Peak side-on (incident) overpressure of the wave, in Pa, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `Ps/Pa = 808 (1 + (Z/4.5)^2) / (sqrt(1 + (Z/0.048)^2) sqrt(1 + (Z/0.32)^2) sqrt(1 + (Z/1.35)^2))`, with the scaled distance `Z = R / W^(1/3)` (m/kg^(1/3)).\n * What a wall takes from a blast is read against it: about 7 kPa cracks plaster and breaks windows, 14 to 20 kPa knocks parts of a brick wall out, 35 kPa and over brings an\n * unreinforced brick wall down (Glasstone and Dolan, \"The Effects of Nuclear Weapons\", 1977, table 5.139; UFC 3-340-02).\n */\nexport function sideOnOverpressure(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n const ratio = (808 * (1 + (z / 4.5) ** 2)) / (Math.sqrt(1 + (z / 0.048) ** 2) * Math.sqrt(1 + (z / 0.32) ** 2) * Math.sqrt(1 + (z / 1.35) ** 2))\n return ratio * ATMOSPHERE\n}\n\n/**\n * The impulse per square metre a body facing the wave takes, Pa·s: the side-on impulse reflected. The reflection doubles a weak wave and grows up to about six times close to the charge,\n * where the wave is strong (the ratio of reflected to side-on impulse of the Kingery-Bulmash charts, fitted as `2 + 4 / (1 + Z^2)`).\n */\nexport function bodyImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n return sideOnImpulse(tnt, distance) * (2 + 4 / (1 + z * z))\n}\n\n/** The speed (m/s) a blast wave gives a free body of `mass` kg at `distance` metres from `tnt` kg of TNT, `reach` (0..1) of it getting through what stands in the way. */\nexport function blastBodySpeed(tnt: number, distance: number, mass: number, reach = 1, options: BlastImpulseOptions = {}): number {\n const area = options.bodyArea ?? DEFAULT_BLAST_IMPULSE.bodyArea\n return (bodyImpulse(tnt, distance) * area * Math.max(0, reach)) / Math.max(mass, 1)\n}\n","import { blastBodySpeed, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { BlastImpulseOptions } from './blast-impulse'\nimport type { BlastShoveOptions, BlastSource } from './blast-shove'\nimport type { Vec3 } from './destruction'\n\n/** From this speed (m/s) a blast takes a standing body off its feet. Below it the body is only pushed. */\nexport const KNOCK_DOWN_SPEED = 2.5\n/** The angle of a body lying where it fell (the same tilt a dead body takes). */\nexport const KNOCKED_DOWN_ANGLE = 1.35\n/** Seconds the body lies after it lands: this plus the landing speed times `STAND_UP_PER_SPEED`. */\nconst LIE_SECONDS = 1.6\n/** Seconds a body floored by its wounds (inside the lethal radius) lies before it gets up, when it is not dead. */\nconst WOUNDED_LIE_SECONDS = 6\n/** The share of the blast that has to get through for its fragments to reach a body: behind cover that stops half of it the fragments stop too. */\nexport const FRAGMENT_COVER = 0.5\n/** Seconds a body is stunned at the edge of the lethal radius (the ringing ears, the dizziness); it falls with the square of the way to the edge of the blast. */\nconst STUN_SECONDS = 4\nconst STAND_UP_PER_SPEED = 0.25\nconst FALL_SECONDS = 0.25\nconst RISE_SECONDS = 0.6\n/** m/s squared that slows a body sliding on the ground. */\nconst GROUND_FRICTION = 7\nconst GRAVITY = 9.81\n/** Height of the chest above the feet: where the blast takes the body. */\nexport const KNOCK_CHEST = 1.1\nconst CHEST = KNOCK_CHEST\n\n/** What a blast is doing to one body: its velocity (m/s), whether it is in the air, and how far down it is (0 on its feet, 1 lying). */\nexport interface Knock {\n velocity: [number, number, number]\n airborne: boolean\n /** 0..1 */\n lying: number\n /** Seconds left to lie on the ground after it stopped. */\n lieLeft: number\n /** Knocked off its feet by this blast. */\n down: boolean\n /** Floored by its wounds: inside the lethal radius and not behind cover. It lies longer and falls where it stood. */\n wounded?: boolean\n /** Seconds of stun the blast gave the body: dizziness and ringing ears. */\n stunSeconds?: number\n /** The horizontal unit direction away from the blast, even when the push is too weak to move the body: the way it falls. */\n away?: Vec3\n}\n\n/** The mass of a body in kg from its height (m) and its build (1 = average): 70 kg at 1.75 m. */\nexport const bodyMass = (height: number, build = 1): number => 70 * (height / 1.75) ** 2 * build\n\n/**\n * What a blast does to a body standing at `feet`, of `mass` kg. Undefined when the blast does not reach it or does nothing to it.\n *\n * The body is pushed by the blast wave (`blastBodySpeed`, from the charge `blast.tnt`, or from `energy` by `tntPerJoule`), taken at the chest and cut by `reach`, the share that got through\n * cover. It is floored when that push is `KNOCK_DOWN_SPEED` or more, or when it stands inside `lethalRadius` with the blast reaching it (the fragments and the overpressure fell it where it\n * stands). It is stunned for a while inside the radius. `options` are the shove numbers of the host's loose items; only their `minSpeed` applies to a body.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions, impulse: BlastImpulseOptions = {}): Knock | undefined {\n const o = { ...DEFAULT_BLAST_IMPULSE, ...impulse }\n const chest: Vec3 = [feet[0], feet[1] + CHEST, feet[2]]\n const dx = chest[0] - blast.point[0]\n const dy = chest[1] - blast.point[1]\n const dz = chest[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const reach = Math.max(0, Math.min(1, blast.reach ?? 1))\n const tnt = blast.tnt ?? blast.energy * o.tntPerJoule\n let speed = blastBodySpeed(tnt, distance, mass, reach, o)\n const minSpeed = impulse.minSpeed ?? options?.minSpeed ?? o.minSpeed\n if (speed < minSpeed) speed = 0\n const struck = reach >= FRAGMENT_COVER\n const wounded = struck && blast.lethalRadius !== undefined && distance <= blast.lethalRadius\n const edge = 1 - distance / blast.radius\n const stunSeconds = struck ? STUN_SECONDS * edge * edge * reach : 0\n if (speed === 0 && !wounded && stunSeconds < 0.25) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const horizontal = Math.hypot(dx, dz)\n const away: Vec3 = horizontal > 1e-4 ? [dx / horizontal, o.lift, dz / horizontal] : [0, 1, 0]\n const length = Math.hypot(away[0], away[1], away[2])\n const velocity: [number, number, number] = [(away[0] / length) * speed, (away[1] / length) * speed, (away[2] / length) * speed]\n return {\n velocity,\n airborne: velocity[1] > 0.5,\n lying: 0,\n lieLeft: wounded ? WOUNDED_LIE_SECONDS : 0,\n away: horizontal > 1e-4 ? [dx / horizontal, 0, dz / horizontal] : [0, 0, 0],\n down: speed >= KNOCK_DOWN_SPEED || wounded,\n ...(wounded ? { wounded } : {}),\n ...(stunSeconds >= 0.25 ? { stunSeconds } : {}),\n }\n}\n\n/**\n * Moves a body one step: it slides on the ground and slows, falls when it was knocked down, lies a while and gets up (a dead body stays down). Moves `position` in place; returns true when the\n * body is on its feet and still, and the knock can be dropped.\n */\nexport function stepKnock(knock: Knock, position: { x: number; y: number; z: number }, dt: number, groundAt: (x: number, z: number) => number, alive: boolean): boolean {\n const v = knock.velocity\n position.x += v[0] * dt\n position.z += v[2] * dt\n const ground = groundAt(position.x, position.z)\n if (knock.airborne || position.y > ground + 1e-4) {\n v[1] -= GRAVITY * dt\n position.y += v[1] * dt\n if (position.y <= ground) {\n position.y = ground\n v[1] = 0\n knock.airborne = false\n }\n } else position.y = ground\n const horizontal = Math.hypot(v[0], v[2])\n if (!knock.airborne && horizontal > 0) {\n const slowed = Math.max(0, horizontal - GROUND_FRICTION * dt)\n v[0] *= slowed / horizontal\n v[2] *= slowed / horizontal\n }\n const moving = horizontal > 0.05 || knock.airborne\n if (knock.down) {\n // a body floored where it stands (its wounds, not the push) still takes the time of a fall to reach the ground\n if (moving || knock.lying < 1) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else if (alive) {\n knock.lieLeft = knock.lieLeft > 0 ? knock.lieLeft : LIE_SECONDS + Math.hypot(v[0], v[2]) * STAND_UP_PER_SPEED\n knock.lieLeft -= dt\n if (knock.lieLeft <= 0) knock.down = false\n }\n } else if (knock.lying > 0) knock.lying = Math.max(0, knock.lying - dt / RISE_SECONDS)\n return !moving && !knock.down && knock.lying === 0\n}\n\n/** Where `launchBody` leaves the throw on the body's root until the module that animates it takes it. */\nconst LAUNCHED = 'launched'\n\n/**\n * Throws a body at `velocity` (m/s, world): an occupant leaving a car through the glass, a pedestrian run over. The module that animates the body\n * takes it on its next frame (`takeLaunch`) and moves it as it moves a body a blast knocked down: flying, landing, sliding, lying, getting up.\n */\nexport function launchBody(root: { userData: Record<string, unknown> }, velocity: Vec3): void {\n root.userData[LAUNCHED] = [velocity[0], velocity[1], velocity[2]]\n}\n\n/** The throw `launchBody` left on the root, as a knock (knocked down, in the air), once; undefined when nothing threw it. */\nexport function takeLaunch(root: { userData: Record<string, unknown> }): Knock | undefined {\n const velocity = root.userData[LAUNCHED] as Vec3 | undefined\n if (!velocity) return undefined\n delete root.userData[LAUNCHED]\n return { velocity: [velocity[0], velocity[1], velocity[2]], airborne: true, lying: 0, lieLeft: 0, down: true }\n}\n","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * Where a hand should be, in world space. `position` is the middle of the palm; the orientation follows one convention for every hand: the hand-local +x runs from the wrist to the\n * knuckles (the way the fingers point when open), +y is the back of the hand and +z completes the frame (for a right hand the little finger side; the thumb is at -z). A left hand is the\n * mirror image of a right one, so the same numbers describe the same grip: its thumb is at +z.\n */\nexport interface HandPose {\n position: Vec3\n /** Unit quaternion `[x, y, z, w]`, hand-local to world. */\n quaternion: [number, number, number, number]\n}\n\n/**\n * What a tool in the hands asks of the hands that hold it (a weapon asks for a grip on its grip and handguard, a carried item for a hand under it). A side left out or null is not held:\n * the hand stays in its rest stance. Nothing here knows what the tool is.\n */\nexport interface HandTargets {\n R?: HandPose | null\n L?: HandPose | null\n /** How closed the fingers are, 0 open to 1 closed on a grip. Default 1. */\n grip?: number\n /** The same for the left hand, when it differs from `grip` (a hand laid on a forend is looser than the one on the trigger). */\n gripL?: number\n /** The size of the hands against life size (a tool drawn smaller than real takes smaller hands). Default 1. */\n scale?: number\n /** Fingers of the right hand that curl by themselves, 0 extended to 1 fully curled (the index finger of a trigger hand); the others follow `grip`. */\n fingers?: { index?: number }\n /** The same for the left hand (its index on the trigger of a tool of its own, with a tool in each hand); absent, the left hand's fingers all follow `gripL`. */\n fingersL?: { index?: number }\n /**\n * Where the elbows go: `view` puts them on screen beside the hand, out to the side, as a tool held out in front (default); `body` lets them hang down and back by the body, as an item\n * carried close (a can, a bottle), where an elbow out to the side would lift it above the shoulder.\n */\n elbows?: 'view' | 'body'\n}\n\n/** Read every frame by whoever draws the arms; answers null while nothing is held. */\nexport type HandTargetSource = () => HandTargets | null\n\n/** The muzzle of the tool in the hands as it is drawn now (world space): where a shot's flash and tracer leave, and which way the barrel points. */\nexport interface MuzzlePose {\n readonly position: Vec3\n /** Unit vector along the barrel, out of the muzzle. */\n readonly direction: Vec3\n /** The module draws the muzzle flash itself: the host draws none of its own. */\n readonly drawsFlash: boolean\n}\n\n/** A hand of the body: `R` the right, `L` the left. A tool in one hand alone is in the right; the left holds one of its own only with a tool in each hand (`HostTool.offHand`). */\nexport type ToolHand = 'R' | 'L'\n\n/**\n * Read by the host at each shot; null while the tool in the hands has no muzzle (a knife, a bare hand). `hand` is the hand that fired (absent: the right one); a source that draws\n * one tool only answers the same for both.\n */\nexport type MuzzleSource = (hand?: ToolHand) => MuzzlePose | null\n\n/**\n * The layer of what the first-person view draws over the world (three.js `Object3D.layers`): the tool in the hands and the arms that hold it. A host with a first-person view draws\n * the world without this layer, then this layer alone over it with the depth cleared and its own field of view (`ModuleHost.setViewmodelFov`), as shooters draw the weapon in the hands:\n * it never goes into a wall, and the gun and the arms are framed by the lens chosen for them. Seen from outside (third person) nothing is on it.\n */\nexport const FIRST_PERSON_LAYER = 9\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present' },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A picture of the real thing the card is about, with its author and licence: the host shows it on the card, linked to `page`. */\n readonly image?: { readonly url: string; readonly alt: string; readonly credit?: string; readonly page?: string }\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n cobble: 'concrete',\n paver: 'concrete',\n plaster: 'concrete',\n asphalt: 'asphalt',\n wood_soft: 'wood',\n wood_hard: 'wood',\n green_wood: 'wood',\n plywood: 'wood',\n mdf: 'wood',\n ceramic: 'tile',\n plastic: 'tile',\n soil: 'dirt',\n mud: 'dirt',\n clay: 'dirt',\n wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n // no snow surface yet: packed snow crunches closest to sand underfoot\n snow: 'sand',\n steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n Dent,\n DestructibleSpec,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartAperture,\n PartShape,\n PartSpec,\n PartBreach,\n PartState,\n PartStatus,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n GroundLoss,\n PartSettlement,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { bodyMass, FRAGMENT_COVER, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, launchBody, stepKnock, takeLaunch } from './blast-knock'\nexport { blastBodySpeed, bodyImpulse, DEFAULT_BLAST_IMPULSE, sideOnImpulse, sideOnOverpressure } from './blast-impulse'\nexport type { BlastImpulseOptions } from './blast-impulse'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandTargetSource, HandTargets, MuzzlePose, MuzzleSource, ToolHand } from './hands'\nexport { FIRST_PERSON_LAYER } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectPose, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, leadClipEvents, sampleClip, scaleClip, toolAnimationStep } from './tool-animation'\nexport type { ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, checkDeferredQueue } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker } from './footprint'\nexport type { Footprint, FootprintObject } from './footprint'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\n","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\nconst 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 */\nconst RIM_RADIUS_SHARE = 0.7\nconst RIM_FRICTION = 0.4\nconst RIM_ROLLING = 0.25\nconst FLAT_SAG = 0.05\nconst FLAT_ROLLING = 6\nconst 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\nconst 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 { defaultSemiSpec } from './driver'\nimport type { SemiSimSpec } from './types'\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}\n\n/**\n * A semi-simulation spec for a two-axle vehicle from its design ratings: the grip follows the handling, the torque follows the acceleration,\n * the air drag is set so that the top gear tops out at the design top speed, and the brake force follows the mass.\n */\nexport function semiSpecFromStats(stats: DesignStats, body: BodyDimensions, base: Partial<SemiSimSpec> = {}): SemiSimSpec {\n const spec: SemiSimSpec = { ...defaultSemiSpec, ...base }\n const half = body.wheelbase / 2\n const side = body.track / 2\n const driveAll = !!body.fourWheelDrive\n const wheels = [\n { x: half, z: -side, steer: true, drive: driveAll },\n { x: half, z: side, steer: true, drive: driveAll },\n { x: -half, z: -side, drive: true, handbrake: true },\n { x: -half, z: side, drive: true, handbrake: true },\n ]\n const peakTorque = body.mass * (0.06 + 0.015 * stats.acceleration)\n const engine = { ...spec.engine, peakTorque }\n const top = stats.maxSpeedKmh / 3.6\n // the last gear puts the redline at the top speed\n const lastRatio = (engine.redlineRpm * 0.95 * 2 * Math.PI * spec.wheelRadius) / (60 * top * spec.finalDrive)\n const gears = [...spec.gears.slice(0, -1).map((g, i, all) => Math.max(g, lastRatio * (1.25 ** (all.length - i)))), lastRatio]\n const torqueAtTop = peakTorque * 0.76\n const thrust = (torqueAtTop * lastRatio * spec.finalDrive * spec.efficiency) / spec.wheelRadius\n const rollingForce = spec.rolling * body.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, (body.mass - 2000) / 8000))\n const brakeForce = base.brakeForce ?? body.mass * 9.81 * (carRatio + (0.6 - carRatio) * heavyShare)\n return { ...spec, mass: body.mass, wheels, fourWheelDrive: driveAll, engine, gears, drag, brakeForce, tyre: { ...spec.tyre, friction: 0.8 + 0.03 * stats.handling } }\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 { ProvingRange, ProvingSubject } from './types'\n\nconst lerpTable = (table: ReadonlyArray<readonly [number, number]>, x: number): number => {\n if (x <= table[0]![0]) return table[0]![1]\n for (let i = 1; i < table.length; i++) {\n const [x1, y1] = table[i]!\n const [x0, y0] = table[i - 1]!\n if (x <= x1) return y0 + ((y1 - y0) * (x - x0)) / (x1 - x0)\n }\n return table[table.length - 1]![1]\n}\n\n/**\n * The numbers the ranges come from. Real-world bands for road vehicles (a family car stops from 100 km/h in 35-45 m, turns in 10-11 m, a hatch reaches 100 km/h in about 10 s); every one can\n * be replaced per class through `createProvingTests({ ranges })`.\n */\nexport interface RangeTable {\n /** 0-100 km/h seconds by the card's acceleration rating (0-10). */\n accelerationSeconds: ReadonlyArray<readonly [number, number]>\n /** Accepted spread around the expected 0-100 time (0.35 = ±35 %). */\n accelerationSpread: number\n /** Accepted spread around the card's top speed. */\n topSpeedSpread: number\n /** Braking deceleration on dry asphalt, m/s², by class. */\n dryBrake: Readonly<Record<string, readonly [number, number]>>\n /** Braking deceleration on wet asphalt, m/s², by class. */\n wetBrake: Readonly<Record<string, readonly [number, number]>>\n /** Turning circle diameter, metres, by class. */\n turnCircle: Readonly<Record<string, readonly [number, number]>>\n /** Metres a four-wheel-drive vehicle has to cover in the mud test. */\n mudFourWheelDrive: number\n}\n\nexport const defaultRangeTable: RangeTable = {\n accelerationSeconds: [\n [1, 34],\n [3, 21],\n [5, 14],\n [7, 10],\n [9, 6],\n [10, 4.2],\n ],\n accelerationSpread: 0.35,\n topSpeedSpread: 0.1,\n dryBrake: { default: [6.5, 11], heavy: [4.5, 8.5], agricultural: [3.5, 7.5], military: [4.5, 9] },\n wetBrake: { default: [3.5, 8.5], heavy: [2.5, 7], agricultural: [2, 6], military: [2.5, 7] },\n turnCircle: { default: [7, 13.5], motorcycles: [3, 9], suvs: [9, 15], pickups: [9, 16], vans: [9, 15], heavy: [10, 26], military: [9, 24], agricultural: [6, 16] },\n mudFourWheelDrive: 10,\n}\n\nconst byClass = <T>(table: Readonly<Record<string, T>>, category: string): T => (table[category] ?? table.default) as T\n\n/** Expected 0-100 (or 0-`target`) seconds for a subject. Below 100 km/h the time scales linearly with the target speed. */\nexport const expectedAcceleration = (table: RangeTable, subject: ProvingSubject, target: number): number => {\n const base = lerpTable(table.accelerationSeconds, subject.stats.acceleration)\n return base * (target / 100)\n}\n\nexport const accelerationRange = (table: RangeTable, subject: ProvingSubject, target: number): ProvingRange => {\n const t = expectedAcceleration(table, subject, target)\n return { min: round(t * (1 - table.accelerationSpread)), max: round(t * (1 + table.accelerationSpread)) }\n}\n\nexport const topSpeedRange = (table: RangeTable, subject: ProvingSubject): ProvingRange => ({\n min: round(subject.stats.maxSpeedKmh * (1 - table.topSpeedSpread)),\n max: round(subject.stats.maxSpeedKmh * (1 + table.topSpeedSpread)),\n})\n\n/** Stopping distance band from `kmh` for the class's deceleration band. */\nexport const brakeRange = (decel: readonly [number, number], kmh: number): ProvingRange => {\n const v = kmh / 3.6\n return { min: round((v * v) / (2 * decel[1])), max: round((v * v) / (2 * decel[0])) }\n}\n\nexport const dryBrakeRange = (table: RangeTable, subject: ProvingSubject, kmh: number): ProvingRange => brakeRange(byClass(table.dryBrake, subject.category), kmh)\nexport const wetBrakeRange = (table: RangeTable, subject: ProvingSubject, kmh: number): ProvingRange => brakeRange(byClass(table.wetBrake, subject.category), kmh)\nexport const turnCircleRange = (table: RangeTable, subject: ProvingSubject): ProvingRange => {\n const [min, max] = byClass(table.turnCircle, subject.category)\n return { min, max }\n}\n\nexport const inRange = (value: number, range: ProvingRange): boolean => (range.min == null || value >= range.min) && (range.max == null || value <= range.max)\n\nexport const round = (x: number, digits = 1): number => {\n const k = 10 ** digits\n return Math.round(x * k) / k\n}\n","import { createSemiSimDriver, createSurfaces, semiSpecFromStats } from '@adatechnology/game-vehicles-driving'\nimport type { SemiDriver, SemiInput, SemiSimSpec, SurfaceRegistry } from '@adatechnology/game-vehicles-driving'\n\nimport { inRange } from './ranges'\nimport type { ProvingMemo, ProvingResult, ProvingSubject, ProvingTest } from './types'\n\n/** The semi-simulation spec the runner drives a subject with: from the card's ratings and the body, with the subject's own overrides. */\nexport const subjectSpec = (subject: ProvingSubject): SemiSimSpec => ({ ...semiSpecFromStats(subject.stats, subject.body), ...subject.spec })\n\n/** One measured test in progress. A host steps it with the frame's seconds and draws `driver.state`; `runTest` steps it to the end in one go. */\nexport interface ProvingRun {\n readonly test: ProvingTest\n readonly subject: ProvingSubject\n readonly driver: SemiDriver\n readonly surface: string\n readonly time: number\n readonly done: boolean\n /** [seconds, sample] of the run so far. */\n readonly trace: ReadonlyArray<[number, number]>\n readonly memo: ProvingMemo\n /** What the procedure asked of the controls on the last step (all zero before the first): a host plays the brakes and the engine from it. */\n readonly input: SemiInput\n step(dt: number): void\n /** The result so far; pending while the run has not ended. */\n result(): ProvingResult\n}\n\nexport interface RunOptions {\n surfaces?: SurfaceRegistry\n /** Seconds between two trace samples (default 0.1). */\n sampleEvery?: number\n /** Fixed step of the simulation (default 1/120 s); `step(dt)` splits the frame into steps this long. */\n fixedStep?: number\n}\n\nexport function startRun(test: ProvingTest, subject: ProvingSubject, options: RunOptions = {}): ProvingRun {\n const procedure = test.procedure\n if (test.kind !== 'measured' || !procedure) throw new Error(`startRun: ${test.id} is not a measured test`)\n const surfaces = options.surfaces ?? createSurfaces()\n const driver = createSemiSimDriver(subjectSpec(subject), { surfaces })\n driver.place(0, 0, 0)\n const surface = procedure.surface ?? 'dry_asphalt'\n const world = { ground: () => ({ surface }) }\n const memo: ProvingMemo = { target: procedure.target?.(subject) ?? 0, subject }\n const trace: Array<[number, number]> = []\n const sampleEvery = options.sampleEvery ?? 0.1\n const fixed = options.fixedStep ?? 1 / 120\n let time = 0\n let done = false\n let nextSample = 0\n let carry = 0\n let last: SemiInput = { throttle: 0, brake: 0, steer: 0, handbrake: false }\n const tick = (h: number): void => {\n const input = procedure.input(driver.state, time, memo)\n last = input\n driver.step(input, h, world)\n time += h\n if (time >= nextSample) {\n trace.push([Math.round(time * 1000) / 1000, procedure.sample(driver.state, time, memo)])\n nextSample += sampleEvery\n }\n if (procedure.finished(driver.state, time, memo) || time >= procedure.maxSeconds) done = true\n }\n return {\n test,\n subject,\n driver,\n surface,\n memo,\n get time() {\n return time\n },\n get done() {\n return done\n },\n get trace() {\n return trace\n },\n get input() {\n return last\n },\n step(dt) {\n carry += dt\n while (!done && carry >= fixed) {\n carry -= fixed\n tick(fixed)\n }\n },\n result() {\n const range = test.range?.(subject) ?? {}\n const base = { test: test.id, kind: test.kind, unit: test.unit, range, trace: [...trace] }\n if (!done) return { ...base, verdict: 'pending', value: null, note: 'running' }\n const value = procedure.value(driver.state, time, memo)\n const lowered = memo.target > 0 && /_100|_80/.test(test.id) && memo.target < (test.id.includes('80') ? 80 : 100)\n const note = lowered ? `target ${memo.target} km/h` : undefined\n if (value == null) return { ...base, verdict: 'fail', value: null, note: `did not finish in ${procedure.maxSeconds} s` }\n return { ...base, verdict: inRange(value, range) ? 'pass' : 'fail', value, ...(note ? { note } : {}) }\n },\n }\n}\n\n/** Runs a measured test to its end and returns the result. */\nexport function runTest(test: ProvingTest, subject: ProvingSubject, options: RunOptions = {}): ProvingResult {\n const run = startRun(test, subject, options)\n const fixed = options.fixedStep ?? 1 / 120\n while (!run.done) run.step(fixed * 60)\n return run.result()\n}\n","import { applyPatches, mergeById, removeIds } from '@adatechnology/game-contracts'\nimport type { SemiInput, SemiState } from '@adatechnology/game-vehicles-driving'\n\nimport { accelerationRange, defaultRangeTable, dryBrakeRange, round, topSpeedRange, turnCircleRange, wetBrakeRange } from './ranges'\nimport type { RangeTable } from './ranges'\nimport type { ProvingMemo, ProvingProcedure, ProvingSubject, ProvingTest } from './types'\n\nconst KMH = 3.6\nconst idle: SemiInput = { throttle: 0, brake: 0, steer: 0, handbrake: false }\nconst kmh = (s: SemiState): number => Math.abs(s.u) * KMH\nconst travelled = (s: SemiState, memo: ProvingMemo, key: string): number => Math.hypot(s.x - (memo[`${key}X`] as number), s.z - (memo[`${key}Z`] as number))\n\n/** Speed a run aims for: `wanted`, or 80 % of the vehicle's top speed when it cannot reach it (a tractor, a bicycle). */\nconst reachable = (subject: ProvingSubject, wanted: number): number => Math.min(wanted, Math.round(subject.stats.maxSpeedKmh * 0.8))\n\n/** Accelerates to the target, then brakes flat out in a straight line; the value is the distance from the first metre of braking to the stop. */\nconst brakeFrom = (wanted: number, surface?: string): ProvingProcedure => ({\n ...(surface ? { surface } : {}),\n maxSeconds: 90,\n target: (subject) => reachable(subject, wanted),\n input(state, _time, memo) {\n if (!memo.braking && kmh(state) >= memo.target) {\n memo.braking = true\n memo.brakeX = state.x\n memo.brakeZ = state.z\n }\n return memo.braking ? { ...idle, brake: 1 } : { ...idle, throttle: 1 }\n },\n sample: (state) => kmh(state),\n finished: (state, _t, memo) => !!memo.braking && kmh(state) < 0.3,\n value: (state, _t, memo) => (memo.braking ? round(travelled(state, memo, 'brake')) : null),\n})\n\n/** The tests of the kit. Every number comes from the range table; a game replaces the table, patches a test or adds its own. */\nexport function defaultProvingTests(ranges: RangeTable = defaultRangeTable): ProvingTest[] {\n return [\n {\n id: 'accel_0_100',\n kind: 'measured',\n domains: ['land'],\n unit: 's',\n procedure: {\n maxSeconds: 90,\n target: (subject) => reachable(subject, 100),\n input: () => ({ ...idle, throttle: 1 }),\n sample: (state) => kmh(state),\n finished: (state, _t, memo) => kmh(state) >= memo.target,\n value: (state, time, memo) => (kmh(state) >= memo.target ? round(time, 2) : null),\n },\n range: (subject) => accelerationRange(ranges, subject, reachable(subject, 100)),\n },\n {\n id: 'top_speed',\n kind: 'measured',\n domains: ['land'],\n unit: 'km/h',\n procedure: {\n maxSeconds: 150,\n input: () => ({ ...idle, throttle: 1 }),\n sample: (state) => kmh(state),\n // stops when the speed has grown less than 0.5 km/h in the last 4 seconds\n finished(state, time, memo) {\n const history = (memo.history ??= []) as Array<[number, number]>\n history.push([time, kmh(state)])\n while (history.length > 1 && time - history[0]![0] > 4) history.shift()\n memo.best = Math.max((memo.best as number | undefined) ?? 0, kmh(state))\n return time > 8 && history.length > 1 && kmh(state) - history[0]![1] < 0.5\n },\n value: (_state, _t, memo) => round((memo.best as number | undefined) ?? 0),\n },\n range: (subject) => topSpeedRange(ranges, subject),\n },\n {\n id: 'brake_100_0',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: brakeFrom(100),\n range: (subject) => dryBrakeRange(ranges, subject, reachable(subject, 100)),\n },\n {\n id: 'turn_circle',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: {\n maxSeconds: 30,\n target: () => 12,\n // full lock at a walking pace, the throttle holding 12 km/h; after the circle settles the diameter is twice the speed over the yaw rate\n input: (state, _t, memo) => ({ ...idle, steer: 1, throttle: kmh(state) < memo.target ? 0.5 : 0, brake: kmh(state) > memo.target + 3 ? 0.3 : 0 }),\n sample: (state) => (Math.abs(state.yawRate) > 1e-3 ? (2 * Math.abs(state.u)) / Math.abs(state.yawRate) : 0),\n finished(state, time, memo) {\n if (time < 6) return false\n const d = Math.abs(state.yawRate) > 1e-3 ? (2 * Math.abs(state.u)) / Math.abs(state.yawRate) : Infinity\n const samples = (memo.samples ??= []) as number[]\n samples.push(d)\n return samples.length > 240\n },\n value(_state, _t, memo) {\n const samples = (memo.samples as number[] | undefined) ?? []\n if (!samples.length) return null\n return round(samples.reduce((a, b) => a + b, 0) / samples.length)\n },\n },\n range: (subject) => turnCircleRange(ranges, subject),\n },\n {\n id: 'wet_brake_80_0',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: brakeFrom(80, 'wet_asphalt'),\n range: (subject) => wetBrakeRange(ranges, subject, reachable(subject, 80)),\n },\n {\n id: 'mud_traction',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: {\n surface: 'mud',\n maxSeconds: 10,\n input: () => ({ ...idle, throttle: 1 }),\n sample: (state) => kmh(state),\n finished: () => false,\n value: (state) => round(Math.hypot(state.x, state.z)),\n },\n // a four-wheel-drive vehicle has to get through; a two-wheel-drive one sinks, which is right, so it has no band\n range: (subject) => (subject.body.fourWheelDrive ? { min: ranges.mudFourWheelDrive } : {}),\n },\n // seen by a person in the test room and signed off with a print\n { id: 'cabin', kind: 'visual', domains: ['land', 'water', 'air'], unit: '' },\n { id: 'cameras', kind: 'visual', domains: ['land', 'water', 'air'], unit: '' },\n { id: 'mirrors', kind: 'visual', domains: ['land'], unit: '' },\n // rooms of the next phases: pending until each room reports\n { id: 'terrain', kind: 'room', domains: ['land'], unit: '', available: false },\n { id: 'wind_tunnel', kind: 'room', domains: ['land', 'air'], unit: '', available: false },\n { id: 'crash_test', kind: 'room', domains: ['land'], unit: '', available: false },\n { id: 'pedestrian', kind: 'room', domains: ['land'], unit: '', available: false },\n { id: 'performance', kind: 'room', domains: ['land', 'water', 'air'], unit: '', available: false },\n { id: 'buoyancy', kind: 'room', domains: ['water'], unit: '', available: false },\n { id: 'flight', kind: 'room', domains: ['air'], unit: '', available: false },\n ]\n}\n\nexport interface ProvingTestOptions {\n /** Replaces numbers of the range table (`{ turnCircle: { heavy: [12, 28] } }`). Nested tables are merged by class. */\n ranges?: Partial<RangeTable>\n /** Tests a game adds (or replaces by id). */\n packs?: ReadonlyArray<{ tests?: readonly ProvingTest[] }>\n patch?: Readonly<Record<string, Partial<ProvingTest>>>\n remove?: readonly string[]\n}\n\nexport interface ProvingTestRegistry {\n readonly tests: readonly ProvingTest[]\n get(id: string): ProvingTest | undefined\n /** The tests that apply to a domain, in order. */\n forDomain(domain: ProvingSubject['domain']): ProvingTest[]\n readonly ranges: RangeTable\n}\n\nexport function createProvingTests(options: ProvingTestOptions = {}): ProvingTestRegistry {\n const given = options.ranges ?? {}\n const ranges: RangeTable = {\n ...defaultRangeTable,\n ...given,\n dryBrake: { ...defaultRangeTable.dryBrake, ...given.dryBrake },\n wetBrake: { ...defaultRangeTable.wetBrake, ...given.wetBrake },\n turnCircle: { ...defaultRangeTable.turnCircle, ...given.turnCircle },\n }\n const entries = mergeById(defaultProvingTests(ranges), options.packs?.flatMap((pack) => pack.tests ?? []))\n applyPatches(entries, options.patch)\n removeIds(entries, options.remove)\n const list = (): ProvingTest[] => [...entries.values()]\n return {\n get tests() {\n return list()\n },\n get: (id) => entries.get(id),\n forDomain: (domain) => list().filter((t) => t.domains.includes(domain)),\n ranges,\n }\n}\n","import { runTest } from './run'\nimport type { RunOptions } from './run'\nimport { createProvingTests } from './tests'\nimport type { ProvingTestRegistry } from './tests'\nimport type { ProvingCertificate, ProvingResult, ProvingSubject } from './types'\n\n/** A person's verdict on a visual check (or on a room test run by hand), with the print that shows it. */\nexport interface SignOff {\n vehicle: string\n test: string\n ok: boolean\n by?: string\n evidence?: string\n note?: string\n}\n\nexport interface CertifyOptions extends RunOptions {\n tests?: ProvingTestRegistry\n /** Visual and room checks already signed off. */\n signOffs?: readonly SignOff[]\n /** Results reported by rooms of later phases (terrain, crash test), by test id. */\n reports?: readonly ProvingResult[]\n}\n\n/** approved when every result passed, rejected when any failed, pending otherwise. */\nexport const statusOf = (results: readonly ProvingResult[]): ProvingCertificate['status'] =>\n results.some((r) => r.verdict === 'fail') ? 'rejected' : results.every((r) => r.verdict === 'pass') ? 'approved' : 'pending'\n\n/** Runs every measured test of the subject's domain, takes the sign-offs and the room reports, and gives the certificate. */\nexport function certify(subject: ProvingSubject, options: CertifyOptions = {}): ProvingCertificate {\n const tests = options.tests ?? createProvingTests()\n const results: ProvingResult[] = tests.forDomain(subject.domain).map((test): ProvingResult => {\n const signed = options.signOffs?.find((s) => s.vehicle === subject.id && s.test === test.id)\n const reported = options.reports?.find((r) => r.test === test.id)\n if (reported) return reported\n if (test.kind === 'measured' && test.procedure && subject.domain === 'land') return runTest(test, subject, options)\n if (signed)\n return {\n test: test.id,\n kind: test.kind,\n unit: test.unit,\n range: {},\n value: null,\n verdict: signed.ok ? 'pass' : 'fail',\n ...(signed.by ? { signedBy: signed.by } : {}),\n ...(signed.evidence ? { evidence: signed.evidence } : {}),\n ...(signed.note ? { note: signed.note } : {}),\n }\n const note = test.kind === 'visual' ? 'awaiting sign-off in the test room' : test.kind === 'room' ? 'room not built yet' : 'no runner for this domain yet'\n return { test: test.id, kind: test.kind, unit: test.unit, range: {}, value: null, verdict: 'pending', note }\n })\n return { vehicle: subject.id, domain: subject.domain, category: subject.category, status: statusOf(results), results }\n}\n\n/** Replaces (or adds) one result of a certificate and recomputes its status. */\nexport function withResult(certificate: ProvingCertificate, result: ProvingResult): ProvingCertificate {\n const results = certificate.results.some((r) => r.test === result.test) ? certificate.results.map((r) => (r.test === result.test ? result : r)) : [...certificate.results, result]\n return { ...certificate, results, status: statusOf(results) }\n}\n\nexport interface GateOptions {\n /** Lets pending vehicles in too (a game in development). Rejected vehicles never get in unless listed in `allow`. */\n allowPending?: boolean\n /** Ids a game lets in whatever their certificate says. */\n allow?: readonly string[]\n /** Ids a game keeps out whatever their certificate says. */\n deny?: readonly string[]\n}\n\n/** The ids, of `ids`, that a game lets in: approved ones (and pending ones with `allowPending`), with the game's own allow and deny lists. An id without a certificate counts as pending. */\nexport function gateVehicles(ids: readonly string[], certificates: readonly ProvingCertificate[], options: GateOptions = {}): string[] {\n const byId = new Map(certificates.map((c) => [c.vehicle, c]))\n return ids.filter((id) => {\n if (options.deny?.includes(id)) return false\n if (options.allow?.includes(id)) return true\n const status = byId.get(id)?.status ?? 'pending'\n return status === 'approved' || (status === 'pending' && !!options.allowPending)\n })\n}\n","import type { DesignStats } from '@adatechnology/game-vehicles-driving'\n\nimport type { ProvingDomain, ProvingSubject } from './types'\n\n/** Kilograms per cubic metre of the bounding box, by group: only used when the card has no mass. */\nexport const DEFAULT_DENSITY: Readonly<Record<string, number>> = { motorcycles: 90, cars: 88, suvs: 90, pickups: 95, vans: 80, heavy: 120, agricultural: 150, military: 260, water: 60, air: 40 }\n\n/** What a catalogue knows of a vehicle: its design ratings, its measured size and its group (a content pack fills it; see `fleetProvingSubject` of game-vehicles-fleet). */\nexport interface VehicleCardData {\n stats: DesignStats\n dims: { length: number; width: number; height: number }\n /** Group of the catalogue (`cars`, `heavy`, `water`, `air`…): the class the ranges are read for, and the domain (water and air groups are not land). */\n group: string\n /** Kilograms. Estimated from the size and the group when absent. */\n mass?: number\n /** Metres between the axles and between the wheels, measured on the built vehicle. Estimated from the size when absent. */\n wheelbase?: number\n track?: number\n fourWheelDrive?: boolean\n /** Groups whose vehicles float or fly (default `water` and `air`). */\n domains?: Readonly<Record<string, ProvingDomain>>\n}\n\nconst DEFAULT_DOMAINS: Readonly<Record<string, ProvingDomain>> = { water: 'water', air: 'air' }\n\n/** A proving subject from what a catalogue knows of a vehicle. */\nexport function subjectFromCard(id: string, card: VehicleCardData): ProvingSubject {\n const { dims, group } = card\n const mass = card.mass ?? Math.round((DEFAULT_DENSITY[group] ?? 90) * dims.length * dims.width * dims.height)\n return {\n id,\n domain: (card.domains ?? DEFAULT_DOMAINS)[group] ?? 'land',\n category: group,\n stats: { acceleration: card.stats.acceleration, handling: card.stats.handling, maxSpeedKmh: card.stats.maxSpeedKmh },\n body: {\n mass,\n wheelbase: card.wheelbase ?? Math.round(dims.length * 0.6 * 100) / 100,\n track: card.track ?? Math.round(dims.width * 0.82 * 100) / 100,\n fourWheelDrive: !!card.fourWheelDrive,\n },\n }\n}\n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racts/src/blast-impulse.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/fireball.ts","../../game-contracts/src/blast-wave.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/body-measures.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/hands.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/workers.ts","../../game-contracts/src/index.ts","../../game-runtime/src/index.ts","../../game-runtime/src/budget.ts","../../game-runtime/src/budget-entry.ts","../../game-runtime/src/clock.ts","../../game-runtime/src/render-estimate.ts","../../game-runtime/src/commands.ts","../../game-runtime/src/loop.ts","../../game-runtime/src/scheduler.ts","../../game-runtime/src/frame-time.ts","../../game-runtime/src/phase-runner.ts","../../game-runtime/src/phases.ts","../../game-vehicles-driving/src/arcade.ts","../../game-vehicles-driving/src/run-over.ts","../../game-vehicles-driving/src/semi/fuel.ts","../../game-vehicles-driving/src/semi/surfaces.ts","../../game-vehicles-driving/src/semi/driver.ts","../../game-vehicles-driving/src/semi/impact.ts","../../game-vehicles-driving/src/semi/from-stats.ts","../../game-vehicles-driving/src/driving-aids.ts","../../game-vehicles-driving/src/controls.ts","../../game-vehicles-driving/src/semi/condition.ts","../../game-vehicles-driving/src/systems.ts","../../game-vehicles-driving/src/ejection.ts","../../game-vehicles-driving/src/parking-sensor.ts","../../game-vehicles-driving/src/storage.ts","../../game-vehicles-driving/src/windshield-fog.ts","../src/ranges.ts","../src/run.ts","../src/tests.ts","../src/certificate.ts","../src/fleet.ts"],"sourcesContent":["export { certify, gateVehicles, statusOf, withResult } from './certificate'\nexport type { CertifyOptions, GateOptions, SignOff } from './certificate'\nexport { DEFAULT_DENSITY, subjectFromCard } from './fleet'\nexport type { VehicleCardData } from './fleet'\nexport { accelerationRange, brakeRange, defaultRangeTable, dryBrakeRange, expectedAcceleration, inRange, topSpeedRange, turnCircleRange, wetBrakeRange } from './ranges'\nexport type { RangeTable } from './ranges'\nexport { runTest, startRun, STEPS_PER_TICK, subjectSpec } from './run'\nexport type { ProvingRun, RunOptions } from './run'\nexport { createProvingTests, defaultProvingTests } from './tests'\nexport type { ProvingTestOptions, ProvingTestRegistry } from './tests'\nexport type {\n ProvingCertificate,\n ProvingDomain,\n ProvingMemo,\n ProvingProcedure,\n ProvingRange,\n ProvingResult,\n ProvingSubject,\n ProvingTest,\n ProvingTestKind,\n ProvingVerdict,\n} from './types'\n","/**\n * The push a blast gives a standing body, from the physics of the blast wave and not from a game coupling: the impulse of the wave per square metre at a distance from a charge of\n * `tnt` kg of TNT equivalent (Kinney and Graham's fit of the side-on impulse, scaled by the cube root of the charge), reflected on the body, over the area the body shows the wave,\n * divided by its mass. A hand grenade at 3 m gives a person a few tenths of a metre per second; what floors that person is the fragments, not the wave. A big charge close throws.\n */\n\n/** The numbers of the body a blast wave pushes. All have a default for a standing adult. */\nexport interface BlastImpulseOptions {\n /** Square metres of the body the wave meets: about 1.75 m tall by 0.4 m wide (default 0.7). */\n readonly bodyArea?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised (default 0.15: the wave runs along the ground). */\n readonly lift?: number\n /** Below this speed (m/s) the body does not move (default 0.3). */\n readonly minSpeed?: number\n /**\n * Kilograms of TNT per joule of the blast `energy`, for a blast that does not say its charge (`BlastSource.tnt`). Default 0.24 / 200000: the arsenal's energy scale, where the M67 (180 g\n * of Composition B, 0.24 kg of TNT) is 200 kJ. It is a game equivalence for blasts without a charge, not a physical constant.\n */\n readonly tntPerJoule?: number\n}\n\nexport const DEFAULT_BLAST_IMPULSE: Readonly<Required<BlastImpulseOptions>> = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 200000 }\n\n/** Closest distance (m) the fit is read at by default: inside it the charge is in contact and the body is torn apart anyway (a caller that loads a part next to the charge passes a smaller `nearest`). */\nconst NEAREST = 0.3\n\n/**\n * Side-on (incident) specific impulse of the wave, in Pa·s, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `I/W^(1/3) = 0.067 sqrt(1 + (Z/0.23)^4) / (Z^2 (1 + (Z/1.55)^3)^(1/3))` bar·ms per kg^(1/3), with the scaled distance `Z = R / W^(1/3)`.\n */\nexport function sideOnImpulse(tnt: number, distance: number, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, nearest) / w3\n // products, not `**` past 2: V8 gives `x ** 3` a different last bit on Node 22 and 24, and the goldens must agree on both\n const near = (z / 0.23) * (z / 0.23)\n const far = z / 1.55\n const scaled = (0.067 * Math.sqrt(1 + near * near)) / (z * z * Math.cbrt(1 + far * far * far))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/** Sea-level atmospheric pressure, Pa. */\nconst ATMOSPHERE = 101325\n\n/**\n * Peak side-on (incident) overpressure of the wave, in Pa, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `Ps/Pa = 808 (1 + (Z/4.5)^2) / (sqrt(1 + (Z/0.048)^2) sqrt(1 + (Z/0.32)^2) sqrt(1 + (Z/1.35)^2))`, with the scaled distance `Z = R / W^(1/3)` (m/kg^(1/3)).\n * What a wall takes from a blast is read against it: about 7 kPa cracks plaster and breaks windows, 14 to 20 kPa knocks parts of a brick wall out, 35 kPa and over brings an\n * unreinforced brick wall down (Glasstone and Dolan, \"The Effects of Nuclear Weapons\", 1977, table 5.139; UFC 3-340-02).\n */\nexport function sideOnOverpressure(tnt: number, distance: number, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, nearest) / Math.cbrt(tnt)\n const ratio = (808 * (1 + (z / 4.5) ** 2)) / (Math.sqrt(1 + (z / 0.048) ** 2) * Math.sqrt(1 + (z / 0.32) ** 2) * Math.sqrt(1 + (z / 1.35) ** 2))\n return ratio * ATMOSPHERE\n}\n\n/**\n * The impulse per square metre a body facing the wave takes, Pa·s: the side-on impulse reflected. The reflection doubles a weak wave and grows up to about six times close to the charge,\n * where the wave is strong (the ratio of reflected to side-on impulse of the Kingery-Bulmash charts, fitted as `2 + 4 / (1 + Z^2)`).\n */\nexport function bodyImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n return sideOnImpulse(tnt, distance) * (2 + 4 / (1 + z * z))\n}\n\n/** The speed (m/s) a blast wave gives a free body of `mass` kg at `distance` metres from `tnt` kg of TNT, `reach` (0..1) of it getting through what stands in the way. */\nexport function blastBodySpeed(tnt: number, distance: number, mass: number, reach = 1, options: BlastImpulseOptions = {}): number {\n const area = options.bodyArea ?? DEFAULT_BLAST_IMPULSE.bodyArea\n return (bodyImpulse(tnt, distance) * area * Math.max(0, reach)) / Math.max(mass, 1)\n}\n","import { bodyImpulse, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n /**\n * Kilograms of TNT equivalent of the charge. With it a body is pushed by the blast wave itself (`blast-impulse`), and the shove of loose items keeps this module's rule; without it the body\n * takes the charge from `energy` by `BlastImpulseOptions.tntPerJoule`.\n */\n readonly tnt?: number\n /** Inside this radius (metres) the blast is lethal: a body there that the blast reaches (not behind cover) goes down, wounded, wherever the wave pushed it. */\n readonly lethalRadius?: number\n}\n\n/** What a blast does to one body: how fast it leaves (m/s), the unit direction it leaves in, and how far from the centre it was. */\nexport interface BlastShove {\n readonly speed: number\n readonly direction: Vec3\n readonly distance: number\n /** The falloff applied, 0..1. */\n readonly falloff: number\n}\n\nconst clampShare = (share: number): number => Math.min(1, Math.max(0, share))\n\n/**\n * The shove a blast gives to a body of `mass` kg whose centre is at `position`: away from the centre, lifted a little, with the speed\n * `sqrt(reach) * min(maxSpeed, sqrt(2 * energy * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * A target that says its `area` (m2 it shows the wave) is pushed by the blast wave itself instead (`bodyImpulse`: Kinney-Graham impulse of the charge `blast.tnt`, or of `energy` by\n * `tntPerJoule`, reflected on that area, divided by the mass): a 2 kg shovel 0.8 m from a hand grenade gets a few m/s, not the cap. `maxSpeed` still caps it (a light thing next to the charge would otherwise tunnel through what stands in its way); `coupling` and `falloffPower` do not apply.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number; readonly area?: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n // cover takes its share off the push itself, past the cap too: a light thing behind a cupboard is not thrown as fast as one in the open\n const reach = clampShare(blast.reach ?? 1)\n const speed =\n target.area !== undefined\n ? Math.min(o.maxSpeed, (bodyImpulse(blast.tnt ?? blast.energy * DEFAULT_BLAST_IMPULSE.tntPerJoule, distance) * target.area * reach) / mass)\n : Math.sqrt(reach) * Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * o.coupling) / mass)) * falloff\n if (!(speed >= o.minSpeed)) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const direction: Vec3 = distance > 1e-4 ? [dx / distance, dy / distance + o.lift, dz / distance] : [0, 1, 0]\n const length = Math.hypot(direction[0], direction[1], direction[2])\n return { speed, direction: [direction[0] / length, direction[1] / length, direction[2] / length], distance, falloff }\n}\n","/**\n * The heat of a blast, from the size and life of its fireball and not from the game radius of the blast. Pure functions in SI units (m, s, W/m2, J/m2).\n *\n * A condensed charge (TNT, Composition B, C4) makes a small fireball that lives milliseconds: its radius and its life both grow as the cube root of the charge\n * (Hopkinson-Cranz scaling, as the wave does). A burning fuel (the gas of a cylinder that bursts, petrol) makes a fireball metres wide that lives about a second:\n * the BLEVE correlations of the CCPS guidelines, `D = 5.8 M^(1/3)` m and `t = 0.45 M^(1/3)` s for `M` kg of fuel, with a surface emissive power of a few hundred kW/m2.\n * What a surface takes is the heat per square metre over the life of the fireball: the whole flux inside it, and outside it the share a sphere of radius `R` sends to a\n * surface that faces it at `d` from its centre (the view factor `(R / d)^2`). A surface catches fire when that dose passes what its material needs (`ignitionDose`).\n */\n\n/** The fireball of a blast: how wide, how long and how hot it burns on what it touches. */\nexport interface Fireball {\n /** Metres. */\n readonly radius: number\n /** Seconds the fireball lives. */\n readonly seconds: number\n /** W/m2 it puts on a surface inside it (radiation and the hot gases together). */\n readonly flux: number\n}\n\n/** m/kg^(1/3): radius of the luminous fireball of a condensed charge (an engineering estimate; the M67, 0.24 kg of TNT, is 0.8 m). */\nconst CHARGE_RADIUS = 1.3\n/** s/kg^(1/3): its life (the M67 burns 6 ms). */\nconst CHARGE_SECONDS = 0.01\n/** W/m2 on a surface inside the fireball of a condensed charge: detonation products at some 2500 K, radiation and convection. */\nconst CHARGE_FLUX = 1.5e6\n/** m/kg^(1/3): radius of a fuel fireball, half of the CCPS diameter 5.8 M^(1/3). */\nconst FUEL_RADIUS = 2.9\n/** s/kg^(1/3): life of a fuel fireball (CCPS, below 30 t of fuel). */\nconst FUEL_SECONDS = 0.45\n/** W/m2: surface emissive power of a hydrocarbon fireball (CCPS gives 200 to 350). */\nconst FUEL_FLUX = 250e3\n/** J/m2 per degree between the room and the ignition temperature: the dose a solid needs to light under a brief heat (paper at 230 °C takes 63 kJ/m2, hard wood at 330 °C 93). */\nconst DOSE_PER_DEGREE = 300\n\n/** The fireball of `tnt` kg of TNT equivalent of a condensed charge. */\nexport function chargeFireball(tnt: number): Fireball {\n const cube = Math.cbrt(Math.max(0, tnt))\n return { radius: CHARGE_RADIUS * cube, seconds: CHARGE_SECONDS * cube, flux: CHARGE_FLUX }\n}\n\n/** The fireball of `fuel` kg of a burning hydrocarbon (the gas of a cylinder, petrol). */\nexport function fuelFireball(fuel: number): Fireball {\n const cube = Math.cbrt(Math.max(0, fuel))\n return { radius: FUEL_RADIUS * cube, seconds: FUEL_SECONDS * cube, flux: FUEL_FLUX }\n}\n\n/** J/m2 a surface facing the fireball takes at `distance` metres from its centre: the whole flux inside it, the view factor `(R / d)^2` of the sphere outside. */\nexport function fireballDose(fireball: Fireball, distance: number): number {\n const share = distance <= fireball.radius ? 1 : (fireball.radius / distance) ** 2\n return fireball.flux * fireball.seconds * share\n}\n\n/** J/m2 a surface of a material that ignites at `ignitionC` needs to catch fire from a brief heat, starting at `ambientC`. */\nexport function ignitionDose(ignitionC: number, ambientC = 20): number {\n return DOSE_PER_DEGREE * Math.max(1, ignitionC - ambientC)\n}\n","import { sideOnImpulse, sideOnOverpressure } from './blast-impulse'\n\n/**\n * The blast wave on a part, from Hopkinson-Cranz scaling: the reflected load of a charge of TNT equivalent at a distance (Kinney and Graham's side-on fits, reflected by\n * Rankine-Hugoniot for the pressure and the Kingery-Bulmash ratio for the impulse), and the work it puts into a part of a given area, mass and thickness (the smaller\n * asymptote of its pressure-impulse diagram, Baker et al. 1983). Shared by the destruction world and every module that takes blasts on its own parts (vehicles).\n */\n\n/** Pa */\nconst ATMOSPHERE = 101325\n/** Scaled distance (m/kg^(1/3)) below which the far-field fits are held: closer is a charge in contact, where the fits stop being the wave. */\nconst NEAREST_SCALED = 0.2\n/** m: a charge's near field and the size of a charge add this much to the standoff when the area the wave loads evenly is taken. */\nconst LOADED_MARGIN = 0.15\n/** J/kg: the TNT equivalent's definition. */\nconst TNT_JOULES = 4.184e6\n/**\n * Share of the charge energy that a target crushes and spalls when the charge is in contact with it, at the scaled distance 0 (an engineering estimate of the cratering efficiency of\n * contact charges in concrete and masonry: a few percent of the energy goes into breaking the material, the rest into air and ground shock).\n */\nconst SHOCK_COUPLING = 0.04\n/** m/kg^(1/3): scaled distance at which the crushing and spalling of a surface is a quarter of that at contact (they fall off as `(1 + (Z / Z0)^2)^-2`; spalling of concrete stops near Z = 1.5). */\nconst SHOCK_SCALED = 0.6\n\n/** The wave on a face that looks at the charge: reflected peak overpressure (Pa) and reflected positive impulse (Pa s). */\nexport interface WaveLoad {\n readonly pressure: number\n readonly impulse: number\n}\n\n/** The reflected load at `distance` m from `tnt` kg of TNT. */\nexport function reflectedLoad(tnt: number, distance: number): WaveLoad {\n if (!(tnt > 0)) return { pressure: 0, impulse: 0 }\n const cube = Math.cbrt(tnt)\n const nearest = NEAREST_SCALED * cube\n const side = sideOnOverpressure(tnt, distance, nearest)\n const z = Math.max(distance, nearest) / cube\n // ideal gas, normal reflection: Pr = 2 Ps (7 Pa + 4 Ps) / (7 Pa + Ps), 2 for a weak wave, up to 8 for a strong one\n const pressure = (2 * side * (7 * ATMOSPHERE + 4 * side)) / (7 * ATMOSPHERE + side)\n const impulse = sideOnImpulse(tnt, distance, nearest) * (2 + 4 / (1 + z * z))\n return { pressure, impulse }\n}\n\n\nexport interface WaveWorkInput {\n /** Kilograms of TNT. */\n readonly tnt: number\n /** Metres from the charge to the nearest point of the part. */\n readonly distance: number\n /** 0..1: the share of the wave that gets through what stands in between. */\n readonly reach: number\n /** m2 the part shows the charge. */\n readonly area: number\n readonly mass: number\n /** m: how far the part moves under the wave before it fails (its own thickness). */\n readonly thickness: number\n}\n\nexport interface WaveWork {\n /** m2 the wave loads evenly. */\n readonly loaded: number\n /** Joules the wave puts into the part as a whole (it moves and bends, the P-I work). */\n readonly energy: number\n /** Joules that crush and spall the face next to the charge (`shockWork`), on top of `energy`. */\n readonly shock: number\n /** Reflected peak overpressure on the part (Pa), after cover. */\n readonly pressure: number\n}\n\n/**\n * What a blast puts into a part: `min(J^2 / 2 m, P A d)` with the load `P`, `J / A` of `reflectedLoad` cut by `reach`, over the area the wave loads evenly (a disc as wide as the\n * standoff, so a wall 10 m wide is not loaded as one block by a charge 1 m from it) and the mass of the piece of the part under that area. A 2 mm steel blade 0.8 m from an M67 gets\n * about 75 J (a dent); a 2 tonne wall 1.5 m away gets about 120 J (a scuff), so the damage depends on how much the part weighs for the area it shows.\n */\nexport function waveWork(input: WaveWorkInput): WaveWork {\n const load = reflectedLoad(input.tnt, input.distance)\n const reach = Math.min(1, Math.max(0, input.reach))\n const pressure = load.pressure * reach\n if (!(input.area > 0) || !(input.mass > 0) || pressure <= 0) return { energy: 0, shock: 0, pressure, loaded: 0 }\n const loaded = Math.min(input.area, Math.PI * (input.distance + LOADED_MARGIN) ** 2)\n const mass = input.mass * (loaded / input.area)\n const impulse = load.impulse * reach * loaded\n const impulsive = (impulse * impulse) / (2 * mass)\n const quasiStatic = pressure * loaded * Math.max(input.thickness, 1e-4)\n return { energy: Math.min(impulsive, quasiStatic), shock: shockWork(input), pressure, loaded }\n}\n\n/**\n * Crushing and spalling of the face next to a charge, which the far-field fits do not see: the charge energy `W * 4.184 MJ`, times the share that crushes material at that scaled\n * distance (`SHOCK_COUPLING (1 + (Z / 0.6)^2)^-2`), times the share of the sphere around the charge that the part intercepts (`A / 4 pi (R + r_c)^2`, at most a half: a face on the charge).\n * A grenade 0.8 m from a blade gives it about 1 J of this; a block of C4 against a wall gives it tens of kilojoules.\n */\nfunction shockWork(input: WaveWorkInput): number {\n const cube = Math.cbrt(input.tnt)\n if (!(cube > 0) || !(input.area > 0)) return 0\n const z = Math.max(input.distance, 0) / cube\n const radius = Math.cbrt((3 * input.tnt) / (4 * Math.PI * 1600))\n const share = Math.min(0.5, input.area / (4 * Math.PI * (input.distance + radius) ** 2))\n // products, not `**` past 2: V8 gives `x ** -2` a different last bit on Node 22 and 24, and the goldens must agree on both\n const falloff = 1 + (z / SHOCK_SCALED) * (z / SHOCK_SCALED)\n const reach = Math.min(1, Math.max(0, input.reach))\n return (SHOCK_COUPLING * input.tnt * TNT_JOULES * share * reach * reach) / (falloff * falloff)\n}\n","import { blastBodySpeed, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { BlastImpulseOptions } from './blast-impulse'\nimport type { BlastShoveOptions, BlastSource } from './blast-shove'\nimport type { Vec3 } from './destruction'\n\n/** From this speed (m/s) a blast takes a standing body off its feet. Below it the body is only pushed. */\nexport const KNOCK_DOWN_SPEED = 2.5\n/** The angle of a body lying where it fell (the same tilt a dead body takes). */\nexport const KNOCKED_DOWN_ANGLE = 1.35\n/** Seconds the body lies after it lands: this plus the landing speed times `STAND_UP_PER_SPEED`. */\nconst LIE_SECONDS = 1.6\n/** Seconds a body floored by its wounds (inside the lethal radius) lies before it gets up, when it is not dead. */\nconst WOUNDED_LIE_SECONDS = 6\n/** The share of the blast that has to get through for its fragments to reach a body: behind cover that stops half of it the fragments stop too. */\nexport const FRAGMENT_COVER = 0.5\n/** Seconds a body is stunned at the edge of the lethal radius (the ringing ears, the dizziness); it falls with the square of the way to the edge of the blast. */\nconst STUN_SECONDS = 4\nconst STAND_UP_PER_SPEED = 0.25\nconst FALL_SECONDS = 0.25\nconst RISE_SECONDS = 0.6\n/** m/s squared that slows a body sliding on the ground. */\nconst GROUND_FRICTION = 7\nconst GRAVITY = 9.81\n/** Height of the chest above the feet: where the blast takes the body. */\nexport const KNOCK_CHEST = 1.1\nconst CHEST = KNOCK_CHEST\n\n/** What a blast is doing to one body: its velocity (m/s), whether it is in the air, and how far down it is (0 on its feet, 1 lying). */\nexport interface Knock {\n velocity: [number, number, number]\n airborne: boolean\n /** 0..1 */\n lying: number\n /** Seconds left to lie on the ground after it stopped. */\n lieLeft: number\n /** Knocked off its feet by this blast. */\n down: boolean\n /** Floored by its wounds: inside the lethal radius and not behind cover. It lies longer and falls where it stood. */\n wounded?: boolean\n /** Seconds of stun the blast gave the body: dizziness and ringing ears. */\n stunSeconds?: number\n /** The horizontal unit direction away from the blast, even when the push is too weak to move the body: the way it falls. */\n away?: Vec3\n}\n\n/** The mass of a body in kg from its height (m) and its build (1 = average): 70 kg at 1.75 m. */\nexport const bodyMass = (height: number, build = 1): number => 70 * (height / 1.75) ** 2 * build\n\n/**\n * What a blast does to a body standing at `feet`, of `mass` kg. Undefined when the blast does not reach it or does nothing to it.\n *\n * The body is pushed by the blast wave (`blastBodySpeed`, from the charge `blast.tnt`, or from `energy` by `tntPerJoule`), taken at the chest and cut by `reach`, the share that got through\n * cover. It is floored when that push is `KNOCK_DOWN_SPEED` or more, or when it stands inside `lethalRadius` with the blast reaching it (the fragments and the overpressure fell it where it\n * stands). It is stunned for a while inside the radius. `options` are the shove numbers of the host's loose items; only their `minSpeed` applies to a body.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions, impulse: BlastImpulseOptions = {}): Knock | undefined {\n const o = { ...DEFAULT_BLAST_IMPULSE, ...impulse }\n const chest: Vec3 = [feet[0], feet[1] + CHEST, feet[2]]\n const dx = chest[0] - blast.point[0]\n const dy = chest[1] - blast.point[1]\n const dz = chest[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const reach = Math.max(0, Math.min(1, blast.reach ?? 1))\n const tnt = blast.tnt ?? blast.energy * o.tntPerJoule\n let speed = blastBodySpeed(tnt, distance, mass, reach, o)\n const minSpeed = impulse.minSpeed ?? options?.minSpeed ?? o.minSpeed\n if (speed < minSpeed) speed = 0\n const struck = reach >= FRAGMENT_COVER\n const wounded = struck && blast.lethalRadius !== undefined && distance <= blast.lethalRadius\n const edge = 1 - distance / blast.radius\n const stunSeconds = struck ? STUN_SECONDS * edge * edge * reach : 0\n if (speed === 0 && !wounded && stunSeconds < 0.25) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const horizontal = Math.hypot(dx, dz)\n const away: Vec3 = horizontal > 1e-4 ? [dx / horizontal, o.lift, dz / horizontal] : [0, 1, 0]\n const length = Math.hypot(away[0], away[1], away[2])\n const velocity: [number, number, number] = [(away[0] / length) * speed, (away[1] / length) * speed, (away[2] / length) * speed]\n return {\n velocity,\n airborne: velocity[1] > 0.5,\n lying: 0,\n lieLeft: wounded ? WOUNDED_LIE_SECONDS : 0,\n away: horizontal > 1e-4 ? [dx / horizontal, 0, dz / horizontal] : [0, 0, 0],\n down: speed >= KNOCK_DOWN_SPEED || wounded,\n ...(wounded ? { wounded } : {}),\n ...(stunSeconds >= 0.25 ? { stunSeconds } : {}),\n }\n}\n\n/**\n * Moves a body one step: it slides on the ground and slows, falls when it was knocked down, lies a while and gets up (a dead body stays down). Moves `position` in place; returns true when the\n * body is on its feet and still, and the knock can be dropped.\n */\nexport function stepKnock(knock: Knock, position: { x: number; y: number; z: number }, dt: number, groundAt: (x: number, z: number) => number, alive: boolean): boolean {\n const v = knock.velocity\n position.x += v[0] * dt\n position.z += v[2] * dt\n const ground = groundAt(position.x, position.z)\n if (knock.airborne || position.y > ground + 1e-4) {\n v[1] -= GRAVITY * dt\n position.y += v[1] * dt\n if (position.y <= ground) {\n position.y = ground\n v[1] = 0\n knock.airborne = false\n }\n } else position.y = ground\n const horizontal = Math.hypot(v[0], v[2])\n if (!knock.airborne && horizontal > 0) {\n const slowed = Math.max(0, horizontal - GROUND_FRICTION * dt)\n v[0] *= slowed / horizontal\n v[2] *= slowed / horizontal\n }\n const moving = horizontal > 0.05 || knock.airborne\n if (knock.down) {\n // a body floored where it stands (its wounds, not the push) still takes the time of a fall to reach the ground\n if (moving || knock.lying < 1) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else if (alive) {\n knock.lieLeft = knock.lieLeft > 0 ? knock.lieLeft : LIE_SECONDS + Math.hypot(v[0], v[2]) * STAND_UP_PER_SPEED\n knock.lieLeft -= dt\n if (knock.lieLeft <= 0) knock.down = false\n }\n } else if (knock.lying > 0) knock.lying = Math.max(0, knock.lying - dt / RISE_SECONDS)\n return !moving && !knock.down && knock.lying === 0\n}\n\n/** Where `launchBody` leaves the throw on the body's root until the module that animates it takes it. */\nconst LAUNCHED = 'launched'\n\n/**\n * Throws a body at `velocity` (m/s, world): an occupant leaving a car through the glass, a pedestrian run over. The module that animates the body\n * takes it on its next frame (`takeLaunch`) and moves it as it moves a body a blast knocked down: flying, landing, sliding, lying, getting up.\n */\nexport function launchBody(root: { userData: Record<string, unknown> }, velocity: Vec3): void {\n root.userData[LAUNCHED] = [velocity[0], velocity[1], velocity[2]]\n}\n\n/** The throw `launchBody` left on the root, as a knock (knocked down, in the air), once; undefined when nothing threw it. */\nexport function takeLaunch(root: { userData: Record<string, unknown> }): Knock | undefined {\n const velocity = root.userData[LAUNCHED] as Vec3 | undefined\n if (!velocity) return undefined\n delete root.userData[LAUNCHED]\n return { velocity: [velocity[0], velocity[1], velocity[2]], airborne: true, lying: 0, lieLeft: 0, down: true }\n}\n","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\n/**\n * One drawn piece of a hosted body as a solid for a physics engine, in the impl's frame (`DestructibleImpl.colliders`): a box turned as drawn where a box fits the piece\n * (every corner within 1 cm of a vertex), else the piece's triangles (`mesh`, with the box around them). `id` is the part of `describe()` the piece is.\n * A piece handed back is never changed in place: a piece that changed is a new object (the world reuses what it made of an object it has seen, `hostedSolids`).\n */\nexport interface DrawnCollider {\n readonly id: string\n /** Names the piece across lists (a piece measured again is the same piece): without it, the place in the list. */\n readonly key?: string\n readonly center: Vec3\n readonly half: Vec3\n readonly rotation: [number, number, number, number]\n readonly mesh?: { readonly vertices: Float32Array; readonly indices: Uint32Array }\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /**\n * The pieces the impl draws, as what an engine collides with in their place (in the frame `describe()` answers in): one per drawn piece, none for a part that broke or\n * came off. Without it the engine takes the boxes of `describe()`. Same cost contract as `describe()`: the world asks again only when state, place or a pose changes.\n */\n colliders?(): readonly DrawnCollider[]\n /** True while `colliders()` still has pieces to make (a vehicle that just spawned fills in over several updates): the world asks again at the next update. */\n collidersPending?(): boolean\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source', 'pieces'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n if (hit.pieces !== undefined && !(Number.isFinite(hit.pieces) && hit.pieces >= 1)) out.push(`${hit.type} hit \"pieces\" must be a finite number of at least 1`)\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { Vec3 } from './destruction'\n\n/** Anthropometric measures of a standing/seated body derived from stature and lateral build (metres). */\nexport type BodyMeasures = {\n /** Standing stature from sole to top of skull (excluding hair/hat), in metres. */\n readonly heightMetres: number\n /** Lateral build multiplier (1.0 = reference adult). */\n readonly build: number\n /** Vertical distance from seat surface (H-point) to top of skull, in metres. */\n readonly seatedHeightMetres: number\n /** Vertical distance from seat surface (H-point) to eye level, in metres. */\n readonly seatedEyeHeightMetres: number\n /** Bideltoid shoulder width, in metres. */\n readonly shoulderWidthMetres: number\n /** Horizontal buttock-to-knee length (hip to front of knee), in metres. */\n readonly thighLengthMetres: number\n /** Vertical knee-to-sole length (popliteal/knee height), in metres. */\n readonly shinLengthMetres: number\n}\n\n/** Functional roles a vehicle seat can play. */\nexport const SEAT_ROLES = ['driver', 'front_passenger', 'rear', 'cargo', 'rider', 'pilot', 'crew'] as const\n\n/** Functional role of a vehicle seat. */\nexport type SeatRole = (typeof SEAT_ROLES)[number]\n\n/** Usable interior clearance of one seat in vehicle local coordinates (+x front, +y up, +z right), in metres. */\nexport type SeatSpace = {\n /** Stable seat identifier within the vehicle (e.g. 'driver', 'front_right', 'rear_left', 'rider'). */\n readonly id: string\n /** Functional role of the seat. */\n readonly role: SeatRole\n /** Seat hip point (H-point, cushion top centre) in vehicle local coordinates, in metres. */\n readonly hipPoint: Vec3\n /** Clear vertical height from hipPoint to headliner/roof (minimum of 5 rays). `Infinity` for open vehicles/bikes/boats. */\n readonly headroomMetres: number\n /** Clear longitudinal knee/leg space from hipPoint along seat facing direction to first obstruction. `Infinity` if open. */\n readonly legroomMetres: number\n /** Available lateral width at shoulder height for this seat, in metres. `Infinity` for open-sided seats. */\n readonly widthMetres: number\n /** Id of the door opening that serves this seat (matches `DoorOpening.id`); `undefined` for open entry. */\n readonly doorId?: string\n}\n\n/** Clear opening of a vehicle door or hatch, in metres. */\nexport type DoorOpening = {\n /** Matches the vehicle door zone id (e.g. 'door_front_left', 'hatch_commander'). */\n readonly id: string\n /** Clear horizontal opening width, in metres. `Infinity` if open entry. */\n readonly widthMetres: number\n /** Clear vertical opening height, in metres. `Infinity` if open entry. */\n readonly heightMetres: number\n}\n\n/** Canonical reasons a body cannot fit a seat/door pair (Spec 012 D2). */\nexport const FIT_REJECT_REASONS = ['head', 'legs', 'shoulders', 'door'] as const\n\n/** Why a body does not fit a seat/door pair (binary with reason). */\nexport type FitRejectReason = (typeof FIT_REJECT_REASONS)[number]\n\n/** Result of checking whether a body fits a seat (and optionally its access door). */\nexport type FitResult =\n | { readonly fits: true }\n | { readonly fits: false; readonly reason: FitRejectReason }\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * Where a hand should be, in world space. `position` is the middle of the palm; the orientation follows one convention for every hand: the hand-local +x runs from the wrist to the\n * knuckles (the way the fingers point when open), +y is the back of the hand and +z completes the frame (for a right hand the little finger side; the thumb is at -z). A left hand is the\n * mirror image of a right one, so the same numbers describe the same grip: its thumb is at +z.\n */\nexport interface HandPose {\n position: Vec3\n /** Unit quaternion `[x, y, z, w]`, hand-local to world. */\n quaternion: [number, number, number, number]\n}\n\n/**\n * What a tool in the hands asks of the hands that hold it (a weapon asks for a grip on its grip and handguard, a carried item for a hand under it). A side left out or null is not held:\n * the hand stays in its rest stance. Nothing here knows what the tool is.\n */\nexport interface HandTargets {\n R?: HandPose | null\n L?: HandPose | null\n /**\n * The shaft of a two-handed tool (a shovel, an axe, a sledgehammer) the left hand may slide along, world space: a left grip out of the arm's reach is taken at the nearest point of\n * this segment the hand reaches, the hand still closed on the shaft, as one shortens the grip on a handle. Absent, the left hand goes to `L` or stops short of it.\n */\n slideL?: { readonly from: Vec3; readonly to: Vec3 } | null\n /** How closed the fingers are, 0 open to 1 closed on a grip. Default 1. */\n grip?: number\n /** The same for the left hand, when it differs from `grip` (a hand laid on a forend is looser than the one on the trigger). */\n gripL?: number\n /** The size of the hands against life size (a tool drawn smaller than real takes smaller hands). Default 1. */\n scale?: number\n /** Fingers of the right hand that curl by themselves, 0 extended to 1 fully curled (the index finger of a trigger hand); the others follow `grip`. */\n fingers?: { index?: number }\n /** The same for the left hand (its index on the trigger of a tool of its own, with a tool in each hand); absent, the left hand's fingers all follow `gripL`. */\n fingersL?: { index?: number }\n /**\n * Where the elbows go: `view` puts them on screen beside the hand, out to the side, as a tool held out in front (default); `body` lets them hang down and back by the body, as an item\n * carried close (a can, a bottle), where an elbow out to the side would lift it above the shoulder.\n */\n elbows?: 'view' | 'body'\n}\n\n/** Read every frame by whoever draws the arms; answers null while nothing is held. */\nexport type HandTargetSource = () => HandTargets | null\n\n/** The muzzle of the tool in the hands as it is drawn now (world space): where a shot's flash and tracer leave, and which way the barrel points. */\nexport interface MuzzlePose {\n readonly position: Vec3\n /** Unit vector along the barrel, out of the muzzle. */\n readonly direction: Vec3\n /** The module draws the muzzle flash itself: the host draws none of its own. */\n readonly drawsFlash: boolean\n}\n\n/** A hand of the body: `R` the right, `L` the left. A tool in one hand alone is in the right; the left holds one of its own only with a tool in each hand (`HostTool.offHand`). */\nexport type ToolHand = 'R' | 'L'\n\n/**\n * Read by the host at each shot; null while the tool in the hands has no muzzle (a knife, a bare hand). `hand` is the hand that fired (absent: the right one); a source that draws\n * one tool only answers the same for both.\n */\nexport type MuzzleSource = (hand?: ToolHand) => MuzzlePose | null\n\n/**\n * The layer of what the first-person view draws over the world (three.js `Object3D.layers`): the tool in the hands and the arms that hold it. A host with a first-person view draws\n * the world without this layer, then this layer alone over it with the depth cleared and its own field of view (`ModuleHost.setViewmodelFov`), as shooters draw the weapon in the hands:\n * it never goes into a wall, and the gun and the arms are framed by the lens chosen for them. Seen from outside (third person) nothing is on it.\n */\nexport const FIRST_PERSON_LAYER = 9\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n /** The queue runs to empty in the drain of its phase, outside the frame deadline and the budget (the blow's visible effect). Counted apart. Default false. */\n readonly mustDrain?: boolean\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n BREACH_CUT: 'floorplan.breach-cut',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n AUDIO_OCCLUSION: 'audio.occlusion',\n FLUID_FILM: 'fluids.film',\n VEHICLE_LOD_BATCH: 'vehicles.lod-batch',\n SETTLED_BATCH: 'destruction.settled-batch',\n STATIC_BATCH: 'render.static-batch',\n ANIMALS_STATIC_BATCH: 'animals.static-batch',\n CHARACTERS_STATIC_BATCH: 'characters.static-batch',\n HOUSE_SHADOW_BATCH: 'floorplan.shadow-batch',\n DESTRUCTION_PREFIT: 'destruction.prefit',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n // every frame: the walls cut since the last frame are painted once each, and a hole must show in the frame of the blast\n [DEFERRED_QUEUE_ID.BREACH_CUT]: { priority: 260, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_OCCLUSION]: { priority: 190, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.FLUID_FILM]: { priority: 120, phase: 'idle', minEveryFrames: 2 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n [DEFERRED_QUEUE_ID.VEHICLE_LOD_BATCH]: { priority: 90, phase: 'idle', minEveryFrames: 4 },\n [DEFERRED_QUEUE_ID.SETTLED_BATCH]: { priority: 70, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.ANIMALS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.CHARACTERS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.HOUSE_SHADOW_BATCH]: { priority: 50, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.DESTRUCTION_PREFIT]: { priority: 40, phase: 'idle', minEveryFrames: 30 },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\n/** The queues that may register with `mustDrain: true`: a new one needs the owner's decision (CLAUDE.md §15), and `budget.register` throws for any other. */\nexport const MUST_DRAIN_QUEUE_IDS: ReadonlySet<string> = new Set([DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS, DEFERRED_QUEUE_ID.BREACH_CUT])\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n\n/** Drains a queue no budget registered (D2): runs it until `budgetMs` from now. The one place outside game-runtime that times deferred work. */\nexport function drainDetached(queue: DeferredQueue, budgetMs: number, clock: () => number = () => performance.now()): number {\n return queue.run(clock() + budgetMs, clock)\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A picture of the real thing the card is about, with its author and licence: the host shows it on the card, linked to `page`. */\n readonly image?: { readonly url: string; readonly alt: string; readonly credit?: string; readonly page?: string }\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n cobble: 'concrete',\n paver: 'concrete',\n plaster: 'concrete',\n asphalt: 'asphalt',\n wood_soft: 'wood',\n wood_hard: 'wood',\n green_wood: 'wood',\n plywood: 'wood',\n mdf: 'wood',\n ceramic: 'tile',\n plastic: 'tile',\n soil: 'dirt',\n mud: 'dirt',\n clay: 'dirt',\n laterite: 'gravel',\n wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n // no snow surface yet: packed snow crunches closest to sand underfoot\n snow: 'sand',\n steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * The worker coordinator as the packages see it: a package declares its heavy work as a task kind (a pure function of plain data) or a\n * resident kind (an instance pinned to one worker), and takes a `WorkerCoordinator` through its options. The implementation is\n * `@adatechnology/game-workers`; nothing in a package makes a `Worker` of its own (CLAUDE.md §14).\n */\n\n/**\n * The pools a kind runs in. `sim`: physics and anything the next frames read; the result is applied in a fixed frame and computed on the\n * main thread when the worker is late, so it is the same whichever thread made it. `build`: generation at load (shapes, colliders,\n * normals), no frame deadline. `background`: the living world far from the player, the lowest priority, never takes a `sim` worker.\n */\nexport const WORKER_LANES = ['sim', 'build', 'background'] as const\nexport type WorkerLane = (typeof WORKER_LANES)[number]\n\n/**\n * What happens when no worker answers in time (or there is none). `sync`: the main thread runs the same kernel and the late answer is\n * thrown away (the only rule of the `sim` lane). `drop`: the job is given up and its promise rejects with `WorkerTaskDropped`.\n * `keep-waiting`: it waits for a worker (a fresh one after a crash); with no worker at all it runs on the main thread.\n */\nexport const WORKER_LATE_RULES = ['sync', 'drop', 'keep-waiting'] as const\nexport type WorkerLateRule = (typeof WORKER_LATE_RULES)[number]\n\n/** How a kind is scheduled: the defaults the kind declares, any of which a game may override by id (`CoordinatorOptions.kinds`). */\nexport interface WorkerKindSchedule {\n readonly lane: WorkerLane\n /** Higher runs first, as `DEFERRED_PRIORITY`. */\n readonly priority: number\n /** Frames between the frame a job is submitted in and the frame its result is applied in (`sim` lane; default 1). */\n readonly latencyFrames?: number\n readonly late: WorkerLateRule\n}\n\n/**\n * A job with no state: plain data in, plain data out, through `run`, the same function in the worker and on the main thread. `run` reads\n * nothing but its input (a seed travels inside it), so the bytes out are the same whichever thread ran it.\n */\nexport interface TaskKind<In, Out> extends WorkerKindSchedule {\n /** `package.thing`, unique in a coordinator: `destruction.ground-tiles`. */\n readonly id: string\n readonly kind: 'task'\n run(input: In): Out\n /** The buffers of the output to transfer back (zero copy). The input is copied, never transferred, when `late` is `sync` (unless `transferAwaitedInput`): the main thread may still need it. */\n transferOutput?(value: Out): readonly ArrayBuffer[]\n /** The buffers of the input to transfer when `late` is not `sync` (and on awaited jobs of a `sync` kind with `transferAwaitedInput`). */\n transferInput?(value: In): readonly ArrayBuffer[]\n /**\n * With `late: 'sync'`, transfer the input (`transferInput`) on awaited jobs (`run`) too, instead of copying it: for a caller that keeps its own copy of the input for its\n * own fallback (the ground tiles). Once sent, such a job is never run on the main thread (its input is gone): a worker that dies holding it rejects its promise with an\n * error named `WORKER_INPUT_LOST` (`isWorkerInputLost`: the caller makes it from its own copy), one that answers with an error rejects with that error. Jobs read through\n * `submit`/`collect` still copy their input.\n * Needs `transferInput`.\n */\n readonly transferAwaitedInput?: boolean\n /** One input each worker runs once at `warm` (the JIT compiles the kernel before the first real job). */\n readonly warmup?: In\n}\n\n/** One instance of a resident kind: built from `init` once per worker, then stepped. */\nexport interface ResidentInstance<Step, Result> {\n step(input: Step): Result\n dispose?(): void\n}\n\n/**\n * A kind with an instance pinned to one worker (the crowd physics, a region of the world). With `late: 'sync'` the step must be a pure\n * function of `init` and the step's input (the state lives on the main thread and travels each step), so a main-thread instance gives the\n * same result; a resident that keeps its own state in the worker uses `drop` or `keep-waiting`.\n */\nexport interface ResidentKind<Init, Step, Result> extends WorkerKindSchedule {\n readonly id: string\n readonly kind: 'resident'\n create(init: Init): ResidentInstance<Step, Result>\n transferOutput?(value: Result): readonly ArrayBuffer[]\n transferInput?(value: Step): readonly ArrayBuffer[]\n}\n\n/** A kind of any input and output, for registries (the methods are bivariant, so every `TaskKind<In, Out>` is one). */\nexport type AnyTaskKind = TaskKind<unknown, unknown>\nexport type AnyResidentKind = ResidentKind<unknown, unknown, unknown>\nexport type AnyWorkerKind = AnyTaskKind | AnyResidentKind\n\n/** Where a result came from. `worker`: on time. `main`: the main thread ran it (late worker, crash, or no worker). */\nexport type WorkerResultSource = 'worker' | 'main'\n\n/** A job of the `sim` lane: its result is read in `dueFrame`, never before, whichever thread made it. */\nexport interface TaskHandle<Out> {\n readonly dueFrame: number\n /**\n * The result in `frame` (>= `dueFrame`, an error before it): the worker's when it is back, otherwise the kernel run here now and the\n * late answer thrown away. The same value on every later call.\n */\n collect(frame: number): Out\n /** Resolves when the result exists (worker or main thread); for the `build` and `background` lanes. */\n readonly promise: Promise<Out>\n /** Where the collected result came from; `null` before `collect` or the promise settles. */\n readonly source: WorkerResultSource | null\n /** Drops a job not yet collected: it leaves the queue, or its answer is thrown away. */\n cancel(): void\n}\n\nexport interface ResidentHandle<Step, Result> {\n readonly id: string\n /** Steps the instance with `input` in `frame`; read the result with `collect(dueFrame)`. The input is the coordinator's from here on. */\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result>\n dispose(): void\n}\n\nexport interface WorkerKindStats {\n readonly id: string\n readonly lane: WorkerLane\n readonly submitted: number\n /** Answers that came back from a worker, on time or late. */\n readonly answered: number\n /** Results that came from a worker before they were needed. */\n readonly onTime: number\n /** Results the main thread computed (late worker, crash, no worker). */\n readonly fallback: number\n readonly dropped: number\n readonly cancelled: number\n readonly failed: number\n /** Milliseconds inside the worker, summed over `answered`. */\n readonly workerMs: number\n /** Milliseconds on the main thread, summed (fallbacks). */\n readonly mainMs: number\n /** Milliseconds waiting in the queue before a worker took the job, summed. */\n readonly queueMs: number\n}\n\nexport interface WorkerCoordinatorStats {\n readonly workers: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n readonly queued: number\n readonly running: number\n readonly respawned: number\n readonly kinds: readonly WorkerKindStats[]\n}\n\nexport interface WorkerCoordinator {\n /** A `sim` job submitted in `at.frame` (default: the last `tick`), due `latencyFrames` later. The input is the coordinator's from here on: do not change it. */\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out>\n /**\n * A job awaited instead of collected: a `build` or `background` job, or a `sim` job in the simulation thread (which may wait; with no worker\n * it runs on this thread). A promise, cancelled through `signal`.\n */\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out>\n /** An instance of a resident kind on one worker (or on the main thread when there is none). */\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result>\n /** The frame now; the runtime calls it at the start of each fixed step. Jobs are ordered by priority, then by the nearest due frame. */\n tick(frame: number): void\n /** Starts the workers and runs each kind's `warmup` in every worker; rejects when a worker does not know one of the kinds. */\n warm(kinds: readonly AnyWorkerKind[]): Promise<void>\n /** The schedule a kind runs with here (its own, with the game's overrides). */\n scheduleOf(kind: AnyWorkerKind): WorkerKindSchedule\n stats(): WorkerCoordinatorStats\n dispose(): void\n}\n\n/** The ids of the kit's kinds (`TaskKind.id` / `ResidentKind.id`), what `WORKER_KIND_DEFAULTS` is keyed by. */\nexport const WORKER_KIND_ID = {\n GROUND_TILES: 'destruction.ground-tiles',\n CROWD_PHYSICS: 'crowd.physics',\n PIECE_BOXES: 'destruction.piece-boxes',\n STATIC_COLLIDERS: 'destruction.static-colliders',\n SHAPES_GENERATE: 'shapes.generate',\n WORLD_REGION: 'world.region',\n} as const\n\n/** Default schedule of the kit's kinds; each kind carries its own copy, a game overrides any of them by id. */\nexport const WORKER_KIND_DEFAULTS = {\n [WORKER_KIND_ID.GROUND_TILES]: { lane: 'sim', priority: 300, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.CROWD_PHYSICS]: { lane: 'sim', priority: 250, latencyFrames: 1, late: 'sync' },\n [WORKER_KIND_ID.PIECE_BOXES]: { lane: 'sim', priority: 200, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: 'build', priority: 150, late: 'sync' },\n [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: 'build', priority: 100, late: 'sync' },\n [WORKER_KIND_ID.WORLD_REGION]: { lane: 'background', priority: 10, latencyFrames: 10, late: 'drop' },\n} as const satisfies Readonly<Record<string, WorkerKindSchedule>>\n\n/** The name of the error an awaited job with a transferred input (`transferAwaitedInput`) rejects with when its worker died holding it. */\nexport const WORKER_INPUT_LOST = 'WorkerTaskInputLost'\n\n/** Whether a rejection is that of a job whose transferred input was lost with its worker (`WORKER_INPUT_LOST`): the caller's own fallback makes it, nothing else is wrong. */\nexport const isWorkerInputLost = (error: unknown): boolean => error instanceof Error && error.name === WORKER_INPUT_LOST\n\n/*\n * The simulation thread (spec 009, T22): a game's whole fixed step in one worker that may wait. A package declares its simulation as a\n * `SimModule`; `@adatechnology/game-workers` runs it (`installSimThread`, `startSimThread`, `runSimInline`).\n */\n\n/** One running simulation, built in the simulation thread from the start message's `init`. */\nexport interface SimInstance {\n /**\n * One fixed step. It may return a promise: the loop waits for it (jobs handed to the coordinator are awaited, not raced against a frame),\n * so the result never depends on how fast the other workers were.\n */\n step(frame: number, dt: number, commands: readonly Float64Array[]): void | Promise<void>\n /** Writes the state the page draws into `out` (the snapshot's bytes, `snapshotBytes` long). */\n write(out: Uint8Array, frame: number): void\n dispose?(): void\n}\n\n/** What the simulation thread can build, by id (the worker's file registers every module the game starts). */\nexport interface SimModule<Init> {\n /** `package.thing`: `crowd.horde`. */\n readonly id: string\n create(init: Init): SimInstance | Promise<SimInstance>\n}\nexport type AnySimModule = SimModule<unknown>\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n BendHinge,\n Dent,\n DestructibleSpec,\n BlastCasing,\n BlastCharge,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartAperture,\n PartShape,\n PartSpec,\n CarryHands,\n PartBreach,\n PartState,\n PartStatus,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n GroundLoss,\n PartSettlement,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { chargeFireball, fireballDose, fuelFireball, ignitionDose } from './fireball'\nexport { reflectedLoad, waveWork } from './blast-wave'\nexport type { WaveLoad, WaveWork, WaveWorkInput } from './blast-wave'\nexport type { Fireball } from './fireball'\nexport { bodyMass, FRAGMENT_COVER, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, launchBody, stepKnock, takeLaunch } from './blast-knock'\nexport { blastBodySpeed, bodyImpulse, DEFAULT_BLAST_IMPULSE, sideOnImpulse, sideOnOverpressure } from './blast-impulse'\nexport type { BlastImpulseOptions } from './blast-impulse'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, DrawnCollider, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport type { ToolCondition } from './tool-condition'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { FIT_REJECT_REASONS, SEAT_ROLES } from './body-measures'\nexport type { BodyMeasures, DoorOpening, FitRejectReason, FitResult, SeatRole, SeatSpace } from './body-measures'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandTargetSource, HandTargets, MuzzlePose, MuzzleSource, ToolHand } from './hands'\nexport { FIRST_PERSON_LAYER } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectPose, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, leadClipEvents, sampleClip, scaleClip, toolAnimationStep } from './tool-animation'\nexport type { ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, MUST_DRAIN_QUEUE_IDS, checkDeferredQueue, drainDetached } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker } from './footprint'\nexport type { UtilityConnection, UtilityNetwork } from './utility'\nexport type { Footprint, FootprintObject } from './footprint'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\nexport { WORKER_INPUT_LOST, WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES, WORKER_LATE_RULES, isWorkerInputLost } from './workers'\nexport type { AnyResidentKind, AnySimModule, AnyTaskKind, AnyWorkerKind, ResidentHandle, ResidentInstance, ResidentKind, SimInstance, SimModule, TaskHandle, TaskKind, WorkerCoordinator, WorkerCoordinatorStats, WorkerKindSchedule, WorkerKindStats, WorkerLane, WorkerLateRule, WorkerResultSource } from './workers'\n","/**\n * @adatechnology/game-runtime: the owner of the frame. A phased scheduler with a fixed simulation step and one time budget shared by every deferred\n * queue of the kit. L1: no three.js, and no DOM unless `startLoop` runs on a page.\n */\nexport { DEFERRED_PRIORITY, FRAME_PHASES } from '@adatechnology/game-contracts'\nexport type { DeferredQueue, DeferredQueueOptions, FramePhase } from '@adatechnology/game-contracts'\nexport { createFrameBudget } from './budget'\nexport type { FrameBudgetOptions } from './budget'\nexport { COMMAND_SYSTEM_ORDER, createCommandBuffer } from './commands'\nexport { startLoop } from './loop'\nexport { createScheduler } from './scheduler'\nexport type {\n BudgetStats,\n Command,\n CommandBuffer,\n FrameBudget,\n FrameContext,\n FrameRunOptions,\n LoopOptions,\n QueueStats,\n Scheduler,\n SchedulerOptions,\n SchedulerStats,\n SystemFn,\n SystemOptions,\n SystemProbe,\n} from './types'\n","import { MUST_DRAIN_QUEUE_IDS, type DeferredQueueOptions } from '@adatechnology/game-contracts'\nimport { createQueueEntry, insertByPriority, queueStats, type QueueEntry } from './budget-entry'\nimport { defaultClock } from './clock'\nimport { createRenderEstimate } from './render-estimate'\nimport type { BudgetStats, FrameBudget } from './types'\n\nconst DEFAULT_MS = 4\nconst DEFAULT_MIN_MS = 1\nconst MAX_RESERVE_SHARE = 0.5\n\nexport interface FrameBudgetOptions {\n /** Quota per frame; with `targetMs`, the ceiling of a frame that has a deadline. Default 4. */\n readonly ms?: number\n /** Frame deadline, ms: with it, a frame that carries `frameStartMs` runs in the deadline mode. Absent: quota. */\n readonly targetMs?: number | undefined\n /** Floor of the deadline mode, ms. Default 1. */\n readonly minMs?: number | undefined\n readonly clock?: () => number\n /** The queue ids that may register with `mustDrain: true`; replaces `MUST_DRAIN_QUEUE_IDS` (game-contracts) for a host that has another queue the owner decided on. */\n readonly mustDrainIds?: ReadonlySet<string> | undefined\n /** A queue that throws in `run`: default logs once per queue id. The frame goes on and the queue counts 0 units. */\n readonly onError?: (error: unknown, queue: { readonly id: string; readonly phase: 'present' | 'idle' }) => void\n}\n\nexport function createFrameBudget(options: FrameBudgetOptions = {}): FrameBudget {\n const clock = options.clock ?? defaultClock()\n const entries: QueueEntry[] = []\n const reportedQueues = new Set<string>()\n let frame = 0\n let frameOpen = false\n let debt = 0\n let common = 0\n let spentThisFrame = 0\n let mustDrainSpent = 0\n let unbounded = false\n let mode: 'quota' | 'deadline' = 'quota'\n let allowance = 0\n let isAllowanceReady = false\n let frameStart = 0\n let frameTarget = 0\n let isRenderSkipped = false\n const forcedMs: number[] = []\n const minMs = options.minMs ?? DEFAULT_MIN_MS\n const mustDrainIds = options.mustDrainIds ?? MUST_DRAIN_QUEUE_IDS\n const renderEstimate = createRenderEstimate()\n\n const reservedTotal = (): number => entries.reduce((sum, entry) => sum + entry.reserveMs, 0)\n\n /** Takes each reserve (of a queue with work) out of `pool`; returns what is left for the shared part. */\n const carveReserves = (pool: number): number => {\n for (const entry of entries) {\n entry.reserveLeft = 0\n if (entry.reserveMs <= 0 || entry.mustDrain || entry.queue.pending(frame) <= 0) continue\n entry.reserveLeft = Math.min(entry.reserveMs, pool)\n pool -= entry.reserveLeft\n }\n return pool\n }\n\n const beginFrame = (frameStartMs?: number): void => {\n frame++\n frameOpen = true\n spentThisFrame = 0\n mustDrainSpent = 0\n forcedMs.length = 0\n isRenderSkipped = false\n for (const entry of entries) entry.lastSpentMs = 0\n const target = budget.targetMs\n if (target !== undefined && frameStartMs !== undefined && !unbounded) {\n const now = clock()\n const lag = now - frameStartMs\n mode = 'deadline'\n frameTarget = target\n frameStart = lag >= 0 && lag <= target ? frameStartMs : now\n isAllowanceReady = false\n allowance = 0\n common = 0\n debt = 0\n return\n }\n mode = 'quota'\n allowance = Math.max(0, budget.ms - debt)\n common = Math.max(0, carveReserves(budget.ms) - debt)\n debt = 0\n }\n\n /** Deadline mode: what the queues may spend, computed once per frame after the `mustDrain` queues ran and the simulation and physics are in the clock. */\n const ensureAllowance = (): void => {\n if (isAllowanceReady) return\n isAllowanceReady = true\n const left = frameStart + frameTarget - renderEstimate.value - clock()\n allowance = Math.max(minMs, Math.min(budget.ms, left))\n common = carveReserves(allowance)\n }\n\n /** Deadline mode, start of the idle drain: the render that really ran replaces the estimate, and the floor holds for the whole frame. */\n const refreshForIdle = (): void => {\n for (const entry of entries) if (entry.phase === 'present') entry.reserveLeft = 0\n const realLeft = frameStart + frameTarget - clock()\n const total = Math.max(Math.min(allowance - spentThisFrame, realLeft), minMs - spentThisFrame)\n common = Math.max(0, total - entries.reduce((sum, entry) => sum + entry.reserveLeft, 0))\n }\n\n const reportError = (error: unknown, entry: QueueEntry): void => {\n if (options.onError) return options.onError(error, { id: entry.queue.id, phase: entry.phase })\n if (reportedQueues.has(entry.queue.id)) return\n reportedQueues.add(entry.queue.id)\n console.error(`game-runtime: queue ${entry.queue.id} threw`, error)\n }\n\n const runQueue = (entry: QueueEntry, deadline: number): number => {\n try {\n return entry.queue.run(deadline, clock)\n } catch (error) {\n reportError(error, entry)\n return 0\n }\n }\n\n const runEntry = (entry: QueueEntry, deadline: number): number => {\n const started = clock()\n const ran = runQueue(entry, deadline)\n const spent = Math.max(0, clock() - started)\n entry.ranUnits += ran\n entry.spentMs += spent\n entry.lastSpentMs += spent\n entry.waitingFrames = 0\n if (entry.mustDrain) {\n mustDrainSpent += spent\n return spent\n }\n spentThisFrame += spent\n if (unbounded) return spent\n const fromReserve = Math.min(entry.reserveLeft, spent)\n entry.reserveLeft -= fromReserve\n common -= spent - fromReserve\n if (common < 0) {\n if (mode === 'quota') debt = Math.min(budget.ms, debt - common)\n common = 0\n }\n return spent\n }\n\n const drainMustDrain = (entry: QueueEntry): void => {\n entry.lastPending = entry.queue.pending(frame)\n if (entry.lastPending <= 0) {\n entry.waitingFrames = 0\n return\n }\n runEntry(entry, Infinity)\n }\n\n const drainEntry = (entry: QueueEntry): void => {\n entry.lastPending = entry.queue.pending(frame)\n if (entry.lastPending <= 0) {\n entry.waitingFrames = 0\n return\n }\n if (unbounded) {\n runEntry(entry, Infinity)\n return\n }\n const share = entry.reserveLeft + common\n if (share > 0) {\n runEntry(entry, clock() + share)\n return\n }\n entry.waitingFrames++\n entry.maxWaitingFrames = Math.max(entry.maxWaitingFrames, entry.waitingFrames)\n if (entry.waitingFrames < entry.minEveryFrames) return\n entry.forced++\n forcedMs.push(runEntry(entry, clock()))\n }\n\n const budget: FrameBudget = {\n ms: options.ms ?? DEFAULT_MS,\n register(queue, queueOptions: DeferredQueueOptions) {\n if (entries.some((candidate) => candidate.queue === queue)) throw new Error(`budget.register(${queue.id}): this queue is already registered`)\n if (queueOptions.mustDrain === true && !mustDrainIds.has(queue.id)) {\n throw new Error(`budget.register(${queue.id}): mustDrain is only for ${[...mustDrainIds].join(', ')} (CLAUDE.md §15: a new queue does not enter the mustDrain class without the owner's decision; a host passes its own list as the budget's mustDrainIds)`)\n }\n const reserveMs = queueOptions.reserveMs ?? 0\n if (reservedTotal() + reserveMs > budget.ms * MAX_RESERVE_SHARE) {\n throw new Error(`budget.register(${queue.id}): the reserves would pass half of the ${budget.ms} ms budget`)\n }\n if (budget.targetMs !== undefined && reservedTotal() + reserveMs > minMs) {\n throw new Error(`budget.register(${queue.id}): with a deadline the reserves come out of the ${minMs} ms floor and would pass it`)\n }\n const entry = createQueueEntry(queue, queueOptions)\n insertByPriority(entries, entry)\n queue.attach?.()\n return () => {\n const at = entries.indexOf(entry)\n if (at < 0) return\n entries.splice(at, 1)\n queue.detach?.()\n }\n },\n targetMs: options.targetMs,\n get mode() {\n return mode\n },\n beginFrame,\n recordRender(ms) {\n if (budget.targetMs === undefined || isRenderSkipped || !Number.isFinite(ms)) return\n renderEstimate.add(Math.min(Math.max(ms, 0), budget.targetMs))\n },\n skipRenderSample() {\n isRenderSkipped = true\n },\n drain(phase) {\n if (phase === 'present' && !frameOpen) beginFrame()\n for (const entry of [...entries]) if (entry.mustDrain && entry.phase === phase) drainMustDrain(entry)\n if (mode === 'deadline' && !unbounded) {\n ensureAllowance()\n if (phase === 'idle') refreshForIdle()\n }\n for (const entry of [...entries]) if (!entry.mustDrain && entry.phase === phase) drainEntry(entry)\n if (phase === 'idle') frameOpen = false\n },\n flushAll() {\n for (const entry of entries) entry.queue.flush()\n },\n get unbounded() {\n return unbounded\n },\n set unbounded(value: boolean) {\n unbounded = value\n },\n stats(): BudgetStats {\n return {\n mode,\n ms: budget.ms,\n targetMs: mode === 'deadline' ? frameTarget : undefined,\n allowanceMs: allowance,\n renderEstimateMs: renderEstimate.value,\n spentMs: spentThisFrame,\n mustDrainSpentMs: mustDrainSpent,\n overMs: Math.max(0, spentThisFrame - Math.max(allowance, minMs)),\n forcedThisFrame: forcedMs.length,\n forcedMs: [...forcedMs],\n debtMs: debt,\n queues: entries.map(queueStats),\n }\n },\n dispose() {\n for (const entry of entries.splice(0)) entry.queue.detach?.()\n },\n }\n return budget\n}\n","import type { DeferredQueue, DeferredQueueOptions } from '@adatechnology/game-contracts'\nimport type { QueueStats } from './types'\n\nconst DEFAULT_MIN_EVERY_FRAMES = 4\n\nexport interface QueueEntry {\n readonly queue: DeferredQueue\n readonly phase: 'present' | 'idle'\n readonly priority: number\n readonly minEveryFrames: number\n readonly reserveMs: number\n readonly mustDrain: boolean\n reserveLeft: number\n waitingFrames: number\n maxWaitingFrames: number\n ranUnits: number\n spentMs: number\n lastSpentMs: number\n forced: number\n lastPending: number\n}\n\nexport function createQueueEntry(queue: DeferredQueue, options: DeferredQueueOptions): QueueEntry {\n return {\n queue,\n phase: options.phase ?? 'idle',\n priority: options.priority,\n minEveryFrames: options.minEveryFrames ?? DEFAULT_MIN_EVERY_FRAMES,\n reserveMs: options.reserveMs ?? 0,\n mustDrain: options.mustDrain === true,\n reserveLeft: 0,\n waitingFrames: 0,\n maxWaitingFrames: 0,\n ranUnits: 0,\n spentMs: 0,\n lastSpentMs: 0,\n forced: 0,\n lastPending: 0,\n }\n}\n\n/** Puts the entry before the first one of lower priority, so equal priorities keep the order of registration. */\nexport function insertByPriority(entries: QueueEntry[], entry: QueueEntry): void {\n let index = entries.length\n while (index > 0 && (entries[index - 1] as QueueEntry).priority < entry.priority) index--\n entries.splice(index, 0, entry)\n}\n\nexport function queueStats(entry: QueueEntry): QueueStats {\n return {\n id: entry.queue.id,\n pending: entry.lastPending,\n ranUnits: entry.ranUnits,\n spentMs: entry.spentMs,\n lastSpentMs: entry.lastSpentMs,\n mustDrain: entry.mustDrain,\n framesWaiting: entry.waitingFrames,\n maxFramesWaiting: entry.maxWaitingFrames,\n forced: entry.forced,\n }\n}\n","export const MICROS_PER_SECOND = 1_000_000\n\nexport const toMicros = (seconds: number): number => Math.round(seconds * MICROS_PER_SECOND)\n\nexport function defaultClock(): () => number {\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') return () => performance.now()\n return () => Date.now()\n}\n","const RENDER_ESTIMATE_WEIGHT = 0.125\n\n/** Exponential moving average of the render phase; the first sample seeds it, before it the estimate is 0. */\nexport function createRenderEstimate(): { readonly value: number; add(sample: number): void } {\n let value = 0\n let seeded = false\n return {\n get value() {\n return value\n },\n add(sample) {\n value = seeded ? value + (sample - value) * RENDER_ESTIMATE_WEIGHT : sample\n seeded = true\n },\n }\n}\n","import type { Command, CommandBuffer } from './types'\n\n/** `order` of the fixedSimulate system that takes the tick's commands: it runs before every other fixed system. */\nexport const COMMAND_SYSTEM_ORDER = -10000\n\nconst NONE: readonly Command[] = []\n\n/** `nextTick` answers which fixed tick runs next: that is the tick a command pushed from `input` becomes valid at. */\nexport function createCommandBuffer(nextTick: () => number): CommandBuffer {\n let pending: Command[] = []\n return {\n push(kind, payload, tick) {\n pending.push({ kind, payload, tick: tick ?? nextTick() })\n },\n take(tick) {\n if (pending.length === 0) return NONE\n const due: Command[] = []\n const later: Command[] = []\n for (const command of pending) (command.tick <= tick ? due : later).push(command)\n pending = later\n return due\n },\n clear() {\n pending = []\n },\n }\n}\n","import type { LoopOptions, Scheduler } from './types'\n\n/** Drives `scheduler.frame` from the display's frames; listens to `visibilitychange` when there is a document. Returns the stop function. */\nexport function startLoop(scheduler: Scheduler, options: LoopOptions = {}): () => void {\n const requestFrame = options.requestFrame ?? globalThis.requestAnimationFrame?.bind(globalThis)\n const cancelFrame = options.cancelFrame ?? globalThis.cancelAnimationFrame?.bind(globalThis)\n if (!requestFrame) throw new Error('startLoop: no requestAnimationFrame here, pass requestFrame')\n let last: number = options.startMs ?? (typeof performance !== 'undefined' ? performance.now() : 0)\n let handle = 0\n let stopped = false\n\n const onFrame = (nowMs: number): void => {\n if (stopped) return\n handle = requestFrame(onFrame)\n const gap = options.minFrameMs?.() ?? 0\n if (gap > 0 && nowMs - last < gap) return\n const realSeconds = (nowMs - last) / 1000\n last = nowMs\n options.onFrame?.(realSeconds)\n scheduler.frame(realSeconds, options.skipSimulation?.() ? { simulate: false, frameStartMs: nowMs } : { frameStartMs: nowMs })\n }\n\n const onVisibility = (): void => {\n if (document.visibilityState !== 'visible') return\n // the first frame back measures from now, not from before the tab went away\n if (typeof performance !== 'undefined') last = performance.now()\n scheduler.resetClock()\n }\n const hasDocument = typeof document !== 'undefined' && typeof document.addEventListener === 'function'\n if (hasDocument) document.addEventListener('visibilitychange', onVisibility)\n handle = requestFrame(onFrame)\n\n return () => {\n stopped = true\n cancelFrame?.(handle)\n if (hasDocument) document.removeEventListener('visibilitychange', onVisibility)\n }\n}\n","import { FRAME_PHASES, type FramePhase } from '@adatechnology/game-contracts'\nimport { createFrameBudget } from './budget'\nimport { MICROS_PER_SECOND, defaultClock, toMicros } from './clock'\nimport { createCommandBuffer } from './commands'\nimport { resolveFrameTime, sanitizeSeconds, sanitizeTimeScale } from './frame-time'\nimport { createPhaseRunner, type MutableContext } from './phase-runner'\nimport { createSystemList, type SystemEntry, type SystemList } from './phases'\nimport type { FrameRunOptions, Scheduler, SchedulerOptions, SchedulerStats, SystemFn, SystemOptions, SystemProbe } from './types'\n\nexport function createScheduler(options: SchedulerOptions = {}): Scheduler {\n const fixedDt = options.fixedDt ?? 1 / 60\n const fixedMicros = toMicros(fixedDt)\n const maxSubsteps = options.maxSubsteps ?? 4\n const timeConfig = { fixedMicros, fixedDt, maxFrameSeconds: options.maxFrameSeconds ?? 0.25, snapMicros: Math.round((options.snapMs ?? 0.25) * 1000) }\n const clock = options.clock ?? defaultClock()\n let accumulator = 0\n let residual = 0\n let droppedMicros = 0\n let heldMicros = 0\n let substepsLastFrame = 0\n let running = false\n let disposed = false\n let paused = false\n let scripted = false\n let timeScale = 1\n let systemProbe: SystemProbe | undefined\n let nextSystem = 0\n const reportedErrors = new Set<string>()\n const lists = Object.fromEntries(FRAME_PHASES.map((phase) => [phase, createSystemList(() => running)])) as Record<FramePhase, SystemList>\n const ctx: MutableContext = { dt: 0, realDt: 0, fixedDt, alpha: 0, frame: 0, tick: 0, substep: 0, simTime: 0, paused: false, scripted: false, simulated: true, fixedFrozen: false }\n\n const reportError =\n options.onError ??\n ((error: unknown, system: { id: string; phase: FramePhase }): void => {\n if (reportedErrors.has(system.id)) return\n reportedErrors.add(system.id)\n console.error(`game-runtime: system ${system.id} (${system.phase}) threw`, error)\n })\n const budget = createFrameBudget({ ms: options.budgetMs ?? 4, targetMs: options.targetMs, minMs: options.minBudgetMs, mustDrainIds: options.mustDrainIds, clock, onError: (error, queue) => reportError(error, { id: `queue:${queue.id}`, phase: queue.phase }) })\n const runner = createPhaseRunner({ clock, ctx, lists, reportError, fixedDt, probe: () => systemProbe })\n const { runPhase, runFixed } = runner\n\n const settleAll = (): void => {\n for (const phase of FRAME_PHASES) lists[phase].settle()\n }\n\n const begin = (frameStartMs?: number): void => {\n running = true\n budget.beginFrame(frameStartMs)\n ctx.frame++\n ctx.paused = paused\n ctx.scripted = scripted\n ctx.tick = runner.tick\n }\n\n const end = (): void => {\n running = false\n settleAll()\n }\n\n /** The input phase and, unless paused, the fixed steps (none when frozen) and the late phase; `micros` is the real time to feed the accumulator. */\n const simulate = (seconds: number, micros: number, exact: boolean): void => {\n runPhase('input', seconds)\n if (paused) return\n if (ctx.fixedFrozen) {\n heldMicros += Math.round(micros * timeScale)\n ctx.simTime += seconds * timeScale\n runPhase('lateSimulate', seconds * timeScale)\n return\n }\n accumulator += Math.round(micros * timeScale)\n let steps = Math.floor(accumulator / fixedMicros)\n if (!exact && steps > maxSubsteps) {\n droppedMicros += accumulator - maxSubsteps * fixedMicros\n steps = maxSubsteps\n accumulator = maxSubsteps * fixedMicros\n }\n accumulator -= steps * fixedMicros\n substepsLastFrame = runFixed(steps, options.holdFixed)\n // held inside the frame: what is left of it is frozen (its steps are dropped above with the rest of the accumulator they took)\n if (substepsLastFrame < steps) {\n heldMicros += (steps - substepsLastFrame) * fixedMicros\n ctx.fixedFrozen = true\n }\n ctx.alpha = accumulator / fixedMicros\n ctx.simTime += seconds * timeScale\n runPhase('lateSimulate', seconds * timeScale)\n }\n\n const frame = (realSeconds: number, run: FrameRunOptions = {}): void => {\n if (running) throw new Error('scheduler.frame: re-entrant call')\n if (disposed) throw new Error('scheduler.frame: the scheduler was disposed')\n const time = resolveFrameTime(realSeconds, run.exact === true, residual, timeConfig)\n residual = time.residual\n const seconds = time.seconds\n begin(run.frameStartMs)\n try {\n ctx.simulated = run.simulate !== false\n ctx.fixedFrozen = ctx.simulated && (run.freezeFixed === true || options.holdFixed?.() === true)\n ctx.realDt = seconds\n ctx.alpha = accumulator / fixedMicros\n substepsLastFrame = 0\n if (ctx.simulated) simulate(seconds, time.micros, run.exact === true)\n ctx.alpha = accumulator / fixedMicros\n runPhase('present', paused ? 0 : seconds * timeScale)\n budget.drain('present')\n if (run.render !== false) {\n runPhase('render', seconds)\n budget.recordRender(runner.phaseMs.render)\n }\n runPhase('idle', seconds)\n budget.drain('idle')\n } finally {\n ctx.simulated = true\n ctx.fixedFrozen = false\n end()\n }\n }\n\n const advanceStep = (dt: number, steps: number): void => {\n begin()\n try {\n ctx.simulated = true\n ctx.realDt = dt\n ctx.alpha = 0\n runPhase('input', dt)\n if (!paused) {\n runFixed(steps)\n ctx.simTime += dt\n runPhase('lateSimulate', dt)\n }\n runPhase('present', paused ? 0 : dt)\n budget.drain('present')\n runPhase('idle', dt)\n budget.drain('idle')\n } finally {\n end()\n }\n }\n\n const advance = (seconds: number, advanceOptions: { readonly dt?: number } = {}): void => {\n if (running) throw new Error('scheduler.advance: re-entrant call')\n if (disposed) throw new Error('scheduler.advance: the scheduler was disposed')\n const dt = sanitizeSeconds(advanceOptions.dt ?? fixedDt) || fixedDt\n const iterations = Math.max(1, Math.round(sanitizeSeconds(seconds) / dt))\n const steps = Math.max(1, Math.round(dt / fixedDt))\n const wasUnbounded = budget.unbounded\n budget.unbounded = true\n scripted = true\n accumulator = 0\n residual = 0\n scheduler.commands.clear()\n try {\n for (let i = 0; i < iterations; i++) advanceStep(dt, steps)\n } finally {\n scripted = false\n ctx.scripted = false\n budget.unbounded = wasUnbounded\n accumulator = 0\n ctx.alpha = 0\n }\n }\n\n const scheduler: Scheduler = {\n add(system: SystemFn, systemOptions: SystemOptions) {\n if (disposed) return () => undefined\n const entry: SystemEntry = {\n id: systemOptions.id ?? `${systemOptions.phase}#${nextSystem++}`,\n phase: systemOptions.phase,\n fn: system,\n order: systemOptions.order ?? 0,\n dead: false,\n }\n lists[entry.phase].add(entry)\n return () => lists[entry.phase].remove(entry)\n },\n frame,\n advance,\n pause() {\n paused = true\n },\n resume() {\n paused = false\n },\n get paused() {\n return paused\n },\n get timeScale() {\n return timeScale\n },\n set timeScale(value: number) {\n timeScale = sanitizeTimeScale(value)\n },\n resetClock() {\n accumulator = 0\n residual = 0\n },\n get systemProbe() {\n return systemProbe\n },\n set systemProbe(value: SystemProbe | undefined) {\n systemProbe = value\n },\n budget,\n commands: createCommandBuffer(() => runner.tick),\n stats(): SchedulerStats {\n return { frame: ctx.frame, tick: runner.tick, substepsLastFrame, droppedSeconds: droppedMicros / MICROS_PER_SECOND, heldSeconds: heldMicros / MICROS_PER_SECOND, phaseMs: { ...runner.phaseMs }, budget: budget.stats() }\n },\n dispose() {\n disposed = true\n budget.dispose()\n for (const phase of FRAME_PHASES) lists[phase].clear()\n settleAll()\n },\n }\n return scheduler\n}\n","import { toMicros } from './clock'\n\nexport interface FrameTimeConfig {\n readonly fixedMicros: number\n readonly fixedDt: number\n readonly maxFrameSeconds: number\n readonly snapMicros: number\n}\n\nexport interface FrameTime {\n readonly seconds: number\n readonly micros: number\n /** What the snap left over, carried to the next frame. */\n readonly residual: number\n}\n\n/** A time that is not a finite positive number (NaN, a negative delta from a clock that went back) counts as no time. */\nexport const sanitizeSeconds = (seconds: number): number => (Number.isFinite(seconds) && seconds > 0 ? seconds : 0)\n\n/** The scale is never negative; a NaN scale is read as real time. */\nexport const sanitizeTimeScale = (scale: number): number => (Number.isFinite(scale) ? Math.max(0, scale) : 1)\n\n/** Clamps a real frame, adds the residue of the last snap and snaps a frame within a hair of whole fixed steps to exactly those steps. */\nexport function resolveFrameTime(realSeconds: number, exact: boolean, residual: number, config: FrameTimeConfig): FrameTime {\n const given = sanitizeSeconds(realSeconds)\n if (exact) return { seconds: given, micros: toMicros(given), residual }\n const clamped = Math.min(given, config.maxFrameSeconds)\n const micros = toMicros(clamped) + residual\n const wholeSteps = Math.round(micros / config.fixedMicros)\n const drift = micros - wholeSteps * config.fixedMicros\n if (config.snapMicros > 0 && wholeSteps >= 1 && Math.abs(drift) <= config.snapMicros) {\n return { seconds: wholeSteps * config.fixedDt, micros: wholeSteps * config.fixedMicros, residual: drift }\n }\n return { seconds: clamped, micros, residual: 0 }\n}\n","import { FRAME_PHASES, type FramePhase } from '@adatechnology/game-contracts'\nimport type { SystemList } from './phases'\nimport type { FrameContext, SystemProbe } from './types'\n\nexport type MutableContext = { -readonly [Key in keyof FrameContext]: FrameContext[Key] }\n\nexport interface PhaseRunnerDeps {\n readonly clock: () => number\n readonly ctx: MutableContext\n readonly lists: Readonly<Record<FramePhase, SystemList>>\n readonly fixedDt: number\n readonly probe: () => SystemProbe | undefined\n readonly reportError: (error: unknown, system: { id: string; phase: FramePhase }) => void\n}\n\nexport interface PhaseRunner {\n runPhase(phase: FramePhase, dt: number): void\n /** Runs up to `steps` fixed steps of the `fixedSimulate` phase, stopping before one when `isHeld` says so; returns the steps run. */\n runFixed(steps: number, isHeld?: () => boolean): number\n /** Fixed steps run since start. */\n readonly tick: number\n readonly phaseMs: Readonly<Record<FramePhase, number>>\n}\n\n/** Runs the systems of a phase, one at a time: a system that throws is reported and the rest of the phase goes on. */\nexport function createPhaseRunner(deps: PhaseRunnerDeps): PhaseRunner {\n const { clock, ctx, lists, reportError, fixedDt, probe } = deps\n const phaseMs = Object.fromEntries(FRAME_PHASES.map((phase) => [phase, 0])) as Record<FramePhase, number>\n let tick = 0\n\n const runEntries = (phase: FramePhase): void => {\n for (const entry of lists[phase].entries) {\n if (entry.dead) continue\n const watcher = probe()\n watcher?.enter(entry.id)\n try {\n entry.fn(ctx)\n } catch (error) {\n reportError(error, { id: entry.id, phase })\n } finally {\n watcher?.leave(entry.id)\n }\n }\n }\n\n return {\n runPhase(phase, dt) {\n const started = clock()\n ctx.dt = dt\n runEntries(phase)\n phaseMs[phase] = clock() - started\n },\n runFixed(steps, isHeld) {\n const started = clock()\n ctx.dt = fixedDt\n let ran = 0\n for (let substep = 0; substep < steps; substep++) {\n if (isHeld?.()) break\n ran++\n ctx.substep = substep\n ctx.tick = tick\n runEntries('fixedSimulate')\n tick++\n }\n ctx.substep = 0\n ctx.tick = tick\n phaseMs.fixedSimulate = clock() - started\n return ran\n },\n get tick() {\n return tick\n },\n phaseMs,\n }\n}\n","import type { FramePhase } from '@adatechnology/game-contracts'\nimport type { SystemFn } from './types'\n\nexport interface SystemEntry {\n readonly id: string\n readonly phase: FramePhase\n readonly fn: SystemFn\n readonly order: number\n dead: boolean\n}\n\n/** Systems of one phase sorted by `order` and then by registration, kept sorted by insertion. A system added while a frame runs waits for the next one. */\nexport interface SystemList {\n add(entry: SystemEntry): void\n remove(entry: SystemEntry): void\n /** The live entries; the array is never replaced while the phase runs. */\n readonly entries: readonly SystemEntry[]\n /** Called at the end of a phase: takes in the pending additions and drops the removed. */\n settle(): void\n /** Marks every entry dead and forgets the ones waiting to come in (the scheduler was disposed). */\n clear(): void\n}\n\nexport function createSystemList(isRunning: () => boolean): SystemList {\n let entries: SystemEntry[] = []\n const waiting: SystemEntry[] = []\n const insert = (entry: SystemEntry): void => {\n let index = entries.length\n while (index > 0 && (entries[index - 1] as SystemEntry).order > entry.order) index--\n entries.splice(index, 0, entry)\n }\n return {\n add(entry) {\n if (isRunning()) waiting.push(entry)\n else insert(entry)\n },\n remove(entry) {\n entry.dead = true\n if (!isRunning()) entries = entries.filter((candidate) => candidate !== entry)\n },\n get entries() {\n return entries\n },\n settle() {\n if (entries.some((entry) => entry.dead)) entries = entries.filter((entry) => !entry.dead)\n for (const entry of waiting.splice(0)) if (!entry.dead) insert(entry)\n },\n clear() {\n for (const entry of entries) entry.dead = true\n for (const entry of waiting.splice(0)) entry.dead = true\n entries = isRunning() ? entries : []\n },\n }\n}\n","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\nconst 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 */\nconst RIM_RADIUS_SHARE = 0.7\nconst RIM_FRICTION = 0.4\nconst RIM_ROLLING = 0.25\nconst FLAT_SAG = 0.05\nconst FLAT_ROLLING = 6\nconst 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\nconst 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 { defaultSemiSpec } from './driver'\nimport type { SemiSimSpec } from './types'\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}\n\n/**\n * A semi-simulation spec for a two-axle vehicle from its design ratings: the grip follows the handling, the torque follows the acceleration,\n * the air drag is set so that the top gear tops out at the design top speed, and the brake force follows the mass.\n */\nexport function semiSpecFromStats(stats: DesignStats, body: BodyDimensions, base: Partial<SemiSimSpec> = {}): SemiSimSpec {\n const spec: SemiSimSpec = { ...defaultSemiSpec, ...base }\n const half = body.wheelbase / 2\n const side = body.track / 2\n const driveAll = !!body.fourWheelDrive\n const wheels = [\n { x: half, z: -side, steer: true, drive: driveAll },\n { x: half, z: side, steer: true, drive: driveAll },\n { x: -half, z: -side, drive: true, handbrake: true },\n { x: -half, z: side, drive: true, handbrake: true },\n ]\n const peakTorque = body.mass * (0.06 + 0.015 * stats.acceleration)\n const engine = { ...spec.engine, peakTorque }\n const top = stats.maxSpeedKmh / 3.6\n // the last gear puts the redline at the top speed\n const lastRatio = (engine.redlineRpm * 0.95 * 2 * Math.PI * spec.wheelRadius) / (60 * top * spec.finalDrive)\n const gears = [...spec.gears.slice(0, -1).map((g, i, all) => Math.max(g, lastRatio * (1.25 ** (all.length - i)))), lastRatio]\n const torqueAtTop = peakTorque * 0.76\n const thrust = (torqueAtTop * lastRatio * spec.finalDrive * spec.efficiency) / spec.wheelRadius\n const rollingForce = spec.rolling * body.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, (body.mass - 2000) / 8000))\n const brakeForce = base.brakeForce ?? body.mass * 9.81 * (carRatio + (0.6 - carRatio) * heavyShare)\n return { ...spec, mass: body.mass, wheels, fourWheelDrive: driveAll, engine, gears, drag, brakeForce, tyre: { ...spec.tyre, friction: 0.8 + 0.03 * stats.handling } }\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 { ProvingRange, ProvingSubject } from './types'\n\nconst lerpTable = (table: ReadonlyArray<readonly [number, number]>, x: number): number => {\n if (x <= table[0]![0]) return table[0]![1]\n for (let i = 1; i < table.length; i++) {\n const [x1, y1] = table[i]!\n const [x0, y0] = table[i - 1]!\n if (x <= x1) return y0 + ((y1 - y0) * (x - x0)) / (x1 - x0)\n }\n return table[table.length - 1]![1]\n}\n\n/**\n * The numbers the ranges come from. Real-world bands for road vehicles (a family car stops from 100 km/h in 35-45 m, turns in 10-11 m, a hatch reaches 100 km/h in about 10 s); every one can\n * be replaced per class through `createProvingTests({ ranges })`.\n */\nexport interface RangeTable {\n /** 0-100 km/h seconds by the card's acceleration rating (0-10). */\n accelerationSeconds: ReadonlyArray<readonly [number, number]>\n /** Accepted spread around the expected 0-100 time (0.35 = ±35 %). */\n accelerationSpread: number\n /** Accepted spread around the card's top speed. */\n topSpeedSpread: number\n /** Braking deceleration on dry asphalt, m/s², by class. */\n dryBrake: Readonly<Record<string, readonly [number, number]>>\n /** Braking deceleration on wet asphalt, m/s², by class. */\n wetBrake: Readonly<Record<string, readonly [number, number]>>\n /** Turning circle diameter, metres, by class. */\n turnCircle: Readonly<Record<string, readonly [number, number]>>\n /** Metres a four-wheel-drive vehicle has to cover in the mud test. */\n mudFourWheelDrive: number\n}\n\nexport const defaultRangeTable: RangeTable = {\n accelerationSeconds: [\n [1, 34],\n [3, 21],\n [5, 14],\n [7, 10],\n [9, 6],\n [10, 4.2],\n ],\n accelerationSpread: 0.35,\n topSpeedSpread: 0.1,\n dryBrake: { default: [6.5, 11], heavy: [4.5, 8.5], agricultural: [3.5, 7.5], military: [4.5, 9] },\n wetBrake: { default: [3.5, 8.5], heavy: [2.5, 7], agricultural: [2, 6], military: [2.5, 7] },\n turnCircle: { default: [7, 13.5], motorcycles: [3, 9], suvs: [9, 15], pickups: [9, 16], vans: [9, 15], heavy: [10, 26], military: [9, 24], agricultural: [6, 16] },\n mudFourWheelDrive: 10,\n}\n\nconst byClass = <T>(table: Readonly<Record<string, T>>, category: string): T => (table[category] ?? table.default) as T\n\n/** Expected 0-100 (or 0-`target`) seconds for a subject. Below 100 km/h the time scales linearly with the target speed. */\nexport const expectedAcceleration = (table: RangeTable, subject: ProvingSubject, target: number): number => {\n const base = lerpTable(table.accelerationSeconds, subject.stats.acceleration)\n return base * (target / 100)\n}\n\nexport const accelerationRange = (table: RangeTable, subject: ProvingSubject, target: number): ProvingRange => {\n const t = expectedAcceleration(table, subject, target)\n return { min: round(t * (1 - table.accelerationSpread)), max: round(t * (1 + table.accelerationSpread)) }\n}\n\nexport const topSpeedRange = (table: RangeTable, subject: ProvingSubject): ProvingRange => ({\n min: round(subject.stats.maxSpeedKmh * (1 - table.topSpeedSpread)),\n max: round(subject.stats.maxSpeedKmh * (1 + table.topSpeedSpread)),\n})\n\n/** Stopping distance band from `kmh` for the class's deceleration band. */\nexport const brakeRange = (decel: readonly [number, number], kmh: number): ProvingRange => {\n const v = kmh / 3.6\n return { min: round((v * v) / (2 * decel[1])), max: round((v * v) / (2 * decel[0])) }\n}\n\nexport const dryBrakeRange = (table: RangeTable, subject: ProvingSubject, kmh: number): ProvingRange => brakeRange(byClass(table.dryBrake, subject.category), kmh)\nexport const wetBrakeRange = (table: RangeTable, subject: ProvingSubject, kmh: number): ProvingRange => brakeRange(byClass(table.wetBrake, subject.category), kmh)\nexport const turnCircleRange = (table: RangeTable, subject: ProvingSubject): ProvingRange => {\n const [min, max] = byClass(table.turnCircle, subject.category)\n return { min, max }\n}\n\nexport const inRange = (value: number, range: ProvingRange): boolean => (range.min == null || value >= range.min) && (range.max == null || value <= range.max)\n\nexport const round = (x: number, digits = 1): number => {\n const k = 10 ** digits\n return Math.round(x * k) / k\n}\n","import { createScheduler } from '@adatechnology/game-runtime'\nimport type { Scheduler } from '@adatechnology/game-runtime'\nimport { createSemiSimDriver, createSurfaces, semiSpecFromStats } from '@adatechnology/game-vehicles-driving'\nimport type { SemiDriver, SemiInput, SemiSimSpec, SurfaceRegistry } from '@adatechnology/game-vehicles-driving'\n\nimport { inRange } from './ranges'\nimport type { ProvingMemo, ProvingResult, ProvingSubject, ProvingTest } from './types'\n\n/** The semi-simulation spec the runner drives a subject with: from the card's ratings and the body, with the subject's own overrides. */\nexport const subjectSpec = (subject: ProvingSubject): SemiSimSpec => ({ ...semiSpecFromStats(subject.stats, subject.body), ...subject.spec })\n\n/** Physics steps of one scheduler tick (1/60 s): the proving run steps its driver at twice the tick, as the room's physics loop does. */\nexport const STEPS_PER_TICK = 2\n\n/**\n * One measured test in progress. It owns no clock: a host registers `stepFixed(STEPS_PER_TICK)` in its scheduler's `fixedSimulate` and draws `driver.state`;\n * standalone (tests, CLI) the caller drives `stepFixed` or the thin `advance(seconds)`. `runTest` steps it to the end in one go.\n */\nexport interface ProvingRun {\n readonly test: ProvingTest\n readonly subject: ProvingSubject\n readonly driver: SemiDriver\n readonly surface: string\n readonly time: number\n readonly done: boolean\n /** [seconds, sample] of the run so far. */\n readonly trace: ReadonlyArray<[number, number]>\n readonly memo: ProvingMemo\n /** What the procedure asked of the controls on the last step (all zero before the first): a host plays the brakes and the engine from it. */\n readonly input: SemiInput\n /** Seconds of one physics step (`RunOptions.fixedStep`, default 1/120). */\n readonly fixedStep: number\n /** Runs `steps` physics steps now (stops at the end of the run); no accumulator, no time scale: the caller's scheduler decides how many. */\n stepFixed(steps: number): void\n /** Standalone helper: feeds `seconds` to a private `game-runtime` scheduler (exact, no render) whose fixed tick runs `STEPS_PER_TICK` steps; the remainder waits for the next call. */\n advance(seconds: number): void\n /** The result so far; pending while the run has not ended. */\n result(): ProvingResult\n}\n\nexport interface RunOptions {\n surfaces?: SurfaceRegistry\n /** Seconds between two trace samples (default 0.1). */\n sampleEvery?: number\n /** Fixed step of the simulation (default 1/120 s): the seconds one `stepFixed` step integrates. */\n fixedStep?: number\n}\n\nexport function startRun(test: ProvingTest, subject: ProvingSubject, options: RunOptions = {}): ProvingRun {\n const procedure = test.procedure\n if (test.kind !== 'measured' || !procedure) throw new Error(`startRun: ${test.id} is not a measured test`)\n const surfaces = options.surfaces ?? createSurfaces()\n const driver = createSemiSimDriver(subjectSpec(subject), { surfaces })\n driver.place(0, 0, 0)\n const surface = procedure.surface ?? 'dry_asphalt'\n const world = { ground: () => ({ surface }) }\n const memo: ProvingMemo = { target: procedure.target?.(subject) ?? 0, subject }\n const trace: Array<[number, number]> = []\n const sampleEvery = options.sampleEvery ?? 0.1\n const fixed = options.fixedStep ?? 1 / 120\n let time = 0\n let done = false\n let nextSample = 0\n let scheduler: Scheduler | undefined\n let last: SemiInput = { throttle: 0, brake: 0, steer: 0, handbrake: false }\n const tick = (h: number): void => {\n const input = procedure.input(driver.state, time, memo)\n last = input\n driver.step(input, h, world)\n time += h\n if (time >= nextSample) {\n trace.push([Math.round(time * 1000) / 1000, procedure.sample(driver.state, time, memo)])\n nextSample += sampleEvery\n }\n if (procedure.finished(driver.state, time, memo) || time >= procedure.maxSeconds) done = true\n }\n return {\n test,\n subject,\n driver,\n surface,\n memo,\n get time() {\n return time\n },\n get done() {\n return done\n },\n get trace() {\n return trace\n },\n get input() {\n return last\n },\n fixedStep: fixed,\n stepFixed(steps) {\n for (let i = 0; i < steps && !done; i++) tick(fixed)\n },\n advance(seconds) {\n if (!scheduler) {\n scheduler = createScheduler({ fixedDt: fixed * STEPS_PER_TICK })\n scheduler.add(() => this.stepFixed(STEPS_PER_TICK), { phase: 'fixedSimulate', id: 'proving.run' })\n }\n scheduler.frame(seconds, { exact: true, render: false })\n },\n result() {\n const range = test.range?.(subject) ?? {}\n const base = { test: test.id, kind: test.kind, unit: test.unit, range, trace: [...trace] }\n if (!done) return { ...base, verdict: 'pending', value: null, note: 'running' }\n const value = procedure.value(driver.state, time, memo)\n const lowered = memo.target > 0 && /_100|_80/.test(test.id) && memo.target < (test.id.includes('80') ? 80 : 100)\n const note = lowered ? `target ${memo.target} km/h` : undefined\n if (value == null) return { ...base, verdict: 'fail', value: null, note: `did not finish in ${procedure.maxSeconds} s` }\n return { ...base, verdict: inRange(value, range) ? 'pass' : 'fail', value, ...(note ? { note } : {}) }\n },\n }\n}\n\n/** Runs a measured test to its end and returns the result. */\nexport function runTest(test: ProvingTest, subject: ProvingSubject, options: RunOptions = {}): ProvingResult {\n const run = startRun(test, subject, options)\n while (!run.done) run.stepFixed(STEPS_PER_TICK)\n return run.result()\n}\n","import { applyPatches, mergeById, removeIds } from '@adatechnology/game-contracts'\nimport type { SemiInput, SemiState } from '@adatechnology/game-vehicles-driving'\n\nimport { accelerationRange, defaultRangeTable, dryBrakeRange, round, topSpeedRange, turnCircleRange, wetBrakeRange } from './ranges'\nimport type { RangeTable } from './ranges'\nimport type { ProvingMemo, ProvingProcedure, ProvingSubject, ProvingTest } from './types'\n\nconst KMH = 3.6\nconst idle: SemiInput = { throttle: 0, brake: 0, steer: 0, handbrake: false }\nconst kmh = (s: SemiState): number => Math.abs(s.u) * KMH\nconst travelled = (s: SemiState, memo: ProvingMemo, key: string): number => Math.hypot(s.x - (memo[`${key}X`] as number), s.z - (memo[`${key}Z`] as number))\n\n/** Speed a run aims for: `wanted`, or 80 % of the vehicle's top speed when it cannot reach it (a tractor, a bicycle). */\nconst reachable = (subject: ProvingSubject, wanted: number): number => Math.min(wanted, Math.round(subject.stats.maxSpeedKmh * 0.8))\n\n/** Accelerates to the target, then brakes flat out in a straight line; the value is the distance from the first metre of braking to the stop. */\nconst brakeFrom = (wanted: number, surface?: string): ProvingProcedure => ({\n ...(surface ? { surface } : {}),\n maxSeconds: 90,\n target: (subject) => reachable(subject, wanted),\n input(state, _time, memo) {\n if (!memo.braking && kmh(state) >= memo.target) {\n memo.braking = true\n memo.brakeX = state.x\n memo.brakeZ = state.z\n }\n return memo.braking ? { ...idle, brake: 1 } : { ...idle, throttle: 1 }\n },\n sample: (state) => kmh(state),\n finished: (state, _t, memo) => !!memo.braking && kmh(state) < 0.3,\n value: (state, _t, memo) => (memo.braking ? round(travelled(state, memo, 'brake')) : null),\n})\n\n/** The tests of the kit. Every number comes from the range table; a game replaces the table, patches a test or adds its own. */\nexport function defaultProvingTests(ranges: RangeTable = defaultRangeTable): ProvingTest[] {\n return [\n {\n id: 'accel_0_100',\n kind: 'measured',\n domains: ['land'],\n unit: 's',\n procedure: {\n maxSeconds: 90,\n target: (subject) => reachable(subject, 100),\n input: () => ({ ...idle, throttle: 1 }),\n sample: (state) => kmh(state),\n finished: (state, _t, memo) => kmh(state) >= memo.target,\n value: (state, time, memo) => (kmh(state) >= memo.target ? round(time, 2) : null),\n },\n range: (subject) => accelerationRange(ranges, subject, reachable(subject, 100)),\n },\n {\n id: 'top_speed',\n kind: 'measured',\n domains: ['land'],\n unit: 'km/h',\n procedure: {\n maxSeconds: 150,\n input: () => ({ ...idle, throttle: 1 }),\n sample: (state) => kmh(state),\n // stops when the speed has grown less than 0.5 km/h in the last 4 seconds\n finished(state, time, memo) {\n const history = (memo.history ??= []) as Array<[number, number]>\n history.push([time, kmh(state)])\n while (history.length > 1 && time - history[0]![0] > 4) history.shift()\n memo.best = Math.max((memo.best as number | undefined) ?? 0, kmh(state))\n return time > 8 && history.length > 1 && kmh(state) - history[0]![1] < 0.5\n },\n value: (_state, _t, memo) => round((memo.best as number | undefined) ?? 0),\n },\n range: (subject) => topSpeedRange(ranges, subject),\n },\n {\n id: 'brake_100_0',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: brakeFrom(100),\n range: (subject) => dryBrakeRange(ranges, subject, reachable(subject, 100)),\n },\n {\n id: 'turn_circle',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: {\n maxSeconds: 30,\n target: () => 12,\n // full lock at a walking pace, the throttle holding 12 km/h; after the circle settles the diameter is twice the speed over the yaw rate\n input: (state, _t, memo) => ({ ...idle, steer: 1, throttle: kmh(state) < memo.target ? 0.5 : 0, brake: kmh(state) > memo.target + 3 ? 0.3 : 0 }),\n sample: (state) => (Math.abs(state.yawRate) > 1e-3 ? (2 * Math.abs(state.u)) / Math.abs(state.yawRate) : 0),\n finished(state, time, memo) {\n if (time < 6) return false\n const d = Math.abs(state.yawRate) > 1e-3 ? (2 * Math.abs(state.u)) / Math.abs(state.yawRate) : Infinity\n const samples = (memo.samples ??= []) as number[]\n samples.push(d)\n return samples.length > 240\n },\n value(_state, _t, memo) {\n const samples = (memo.samples as number[] | undefined) ?? []\n if (!samples.length) return null\n return round(samples.reduce((a, b) => a + b, 0) / samples.length)\n },\n },\n range: (subject) => turnCircleRange(ranges, subject),\n },\n {\n id: 'wet_brake_80_0',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: brakeFrom(80, 'wet_asphalt'),\n range: (subject) => wetBrakeRange(ranges, subject, reachable(subject, 80)),\n },\n {\n id: 'mud_traction',\n kind: 'measured',\n domains: ['land'],\n unit: 'm',\n procedure: {\n surface: 'mud',\n maxSeconds: 10,\n input: () => ({ ...idle, throttle: 1 }),\n sample: (state) => kmh(state),\n finished: () => false,\n value: (state) => round(Math.hypot(state.x, state.z)),\n },\n // a four-wheel-drive vehicle has to get through; a two-wheel-drive one sinks, which is right, so it has no band\n range: (subject) => (subject.body.fourWheelDrive ? { min: ranges.mudFourWheelDrive } : {}),\n },\n // seen by a person in the test room and signed off with a print\n { id: 'cabin', kind: 'visual', domains: ['land', 'water', 'air'], unit: '' },\n { id: 'cameras', kind: 'visual', domains: ['land', 'water', 'air'], unit: '' },\n { id: 'mirrors', kind: 'visual', domains: ['land'], unit: '' },\n // rooms of the next phases: pending until each room reports\n { id: 'terrain', kind: 'room', domains: ['land'], unit: '', available: false },\n { id: 'wind_tunnel', kind: 'room', domains: ['land', 'air'], unit: '', available: false },\n { id: 'crash_test', kind: 'room', domains: ['land'], unit: '', available: false },\n { id: 'pedestrian', kind: 'room', domains: ['land'], unit: '', available: false },\n { id: 'performance', kind: 'room', domains: ['land', 'water', 'air'], unit: '', available: false },\n { id: 'buoyancy', kind: 'room', domains: ['water'], unit: '', available: false },\n { id: 'flight', kind: 'room', domains: ['air'], unit: '', available: false },\n ]\n}\n\nexport interface ProvingTestOptions {\n /** Replaces numbers of the range table (`{ turnCircle: { heavy: [12, 28] } }`). Nested tables are merged by class. */\n ranges?: Partial<RangeTable>\n /** Tests a game adds (or replaces by id). */\n packs?: ReadonlyArray<{ tests?: readonly ProvingTest[] }>\n patch?: Readonly<Record<string, Partial<ProvingTest>>>\n remove?: readonly string[]\n}\n\nexport interface ProvingTestRegistry {\n readonly tests: readonly ProvingTest[]\n get(id: string): ProvingTest | undefined\n /** The tests that apply to a domain, in order. */\n forDomain(domain: ProvingSubject['domain']): ProvingTest[]\n readonly ranges: RangeTable\n}\n\nexport function createProvingTests(options: ProvingTestOptions = {}): ProvingTestRegistry {\n const given = options.ranges ?? {}\n const ranges: RangeTable = {\n ...defaultRangeTable,\n ...given,\n dryBrake: { ...defaultRangeTable.dryBrake, ...given.dryBrake },\n wetBrake: { ...defaultRangeTable.wetBrake, ...given.wetBrake },\n turnCircle: { ...defaultRangeTable.turnCircle, ...given.turnCircle },\n }\n const entries = mergeById(defaultProvingTests(ranges), options.packs?.flatMap((pack) => pack.tests ?? []))\n applyPatches(entries, options.patch)\n removeIds(entries, options.remove)\n const list = (): ProvingTest[] => [...entries.values()]\n return {\n get tests() {\n return list()\n },\n get: (id) => entries.get(id),\n forDomain: (domain) => list().filter((t) => t.domains.includes(domain)),\n ranges,\n }\n}\n","import { runTest } from './run'\nimport type { RunOptions } from './run'\nimport { createProvingTests } from './tests'\nimport type { ProvingTestRegistry } from './tests'\nimport type { ProvingCertificate, ProvingResult, ProvingSubject } from './types'\n\n/** A person's verdict on a visual check (or on a room test run by hand), with the print that shows it. */\nexport interface SignOff {\n vehicle: string\n test: string\n ok: boolean\n by?: string\n evidence?: string\n note?: string\n}\n\nexport interface CertifyOptions extends RunOptions {\n tests?: ProvingTestRegistry\n /** Visual and room checks already signed off. */\n signOffs?: readonly SignOff[]\n /** Results reported by rooms of later phases (terrain, crash test), by test id. */\n reports?: readonly ProvingResult[]\n}\n\n/** approved when every result passed, rejected when any failed, pending otherwise. */\nexport const statusOf = (results: readonly ProvingResult[]): ProvingCertificate['status'] =>\n results.some((r) => r.verdict === 'fail') ? 'rejected' : results.every((r) => r.verdict === 'pass') ? 'approved' : 'pending'\n\n/** Runs every measured test of the subject's domain, takes the sign-offs and the room reports, and gives the certificate. */\nexport function certify(subject: ProvingSubject, options: CertifyOptions = {}): ProvingCertificate {\n const tests = options.tests ?? createProvingTests()\n const results: ProvingResult[] = tests.forDomain(subject.domain).map((test): ProvingResult => {\n const signed = options.signOffs?.find((s) => s.vehicle === subject.id && s.test === test.id)\n const reported = options.reports?.find((r) => r.test === test.id)\n if (reported) return reported\n if (test.kind === 'measured' && test.procedure && subject.domain === 'land') return runTest(test, subject, options)\n if (signed)\n return {\n test: test.id,\n kind: test.kind,\n unit: test.unit,\n range: {},\n value: null,\n verdict: signed.ok ? 'pass' : 'fail',\n ...(signed.by ? { signedBy: signed.by } : {}),\n ...(signed.evidence ? { evidence: signed.evidence } : {}),\n ...(signed.note ? { note: signed.note } : {}),\n }\n const note = test.kind === 'visual' ? 'awaiting sign-off in the test room' : test.kind === 'room' ? 'room not built yet' : 'no runner for this domain yet'\n return { test: test.id, kind: test.kind, unit: test.unit, range: {}, value: null, verdict: 'pending', note }\n })\n return { vehicle: subject.id, domain: subject.domain, category: subject.category, status: statusOf(results), results }\n}\n\n/** Replaces (or adds) one result of a certificate and recomputes its status. */\nexport function withResult(certificate: ProvingCertificate, result: ProvingResult): ProvingCertificate {\n const results = certificate.results.some((r) => r.test === result.test) ? certificate.results.map((r) => (r.test === result.test ? result : r)) : [...certificate.results, result]\n return { ...certificate, results, status: statusOf(results) }\n}\n\nexport interface GateOptions {\n /** Lets pending vehicles in too (a game in development). Rejected vehicles never get in unless listed in `allow`. */\n allowPending?: boolean\n /** Ids a game lets in whatever their certificate says. */\n allow?: readonly string[]\n /** Ids a game keeps out whatever their certificate says. */\n deny?: readonly string[]\n}\n\n/** The ids, of `ids`, that a game lets in: approved ones (and pending ones with `allowPending`), with the game's own allow and deny lists. An id without a certificate counts as pending. */\nexport function gateVehicles(ids: readonly string[], certificates: readonly ProvingCertificate[], options: GateOptions = {}): string[] {\n const byId = new Map(certificates.map((c) => [c.vehicle, c]))\n return ids.filter((id) => {\n if (options.deny?.includes(id)) return false\n if (options.allow?.includes(id)) return true\n const status = byId.get(id)?.status ?? 'pending'\n return status === 'approved' || (status === 'pending' && !!options.allowPending)\n })\n}\n","import type { DesignStats } from '@adatechnology/game-vehicles-driving'\n\nimport type { ProvingDomain, ProvingSubject } from './types'\n\n/** Kilograms per cubic metre of the bounding box, by group: only used when the card has no mass. */\nexport const DEFAULT_DENSITY: Readonly<Record<string, number>> = { motorcycles: 90, cars: 88, suvs: 90, pickups: 95, vans: 80, heavy: 120, agricultural: 150, military: 260, water: 60, air: 40 }\n\n/** What a catalogue knows of a vehicle: its design ratings, its measured size and its group (a content pack fills it; see `fleetProvingSubject` of game-vehicles-fleet). */\nexport interface VehicleCardData {\n stats: DesignStats\n dims: { length: number; width: number; height: number }\n /** Group of the catalogue (`cars`, `heavy`, `water`, `air`…): the class the ranges are read for, and the domain (water and air groups are not land). */\n group: string\n /** Kilograms. Estimated from the size and the group when absent. */\n mass?: number\n /** Metres between the axles and between the wheels, measured on the built vehicle. Estimated from the size when absent. */\n wheelbase?: number\n track?: number\n fourWheelDrive?: boolean\n /** Groups whose vehicles float or fly (default `water` and `air`). */\n domains?: Readonly<Record<string, ProvingDomain>>\n}\n\nconst DEFAULT_DOMAINS: Readonly<Record<string, ProvingDomain>> = { water: 'water', air: 'air' }\n\n/** A proving subject from what a catalogue knows of a vehicle. */\nexport function subjectFromCard(id: string, card: VehicleCardData): ProvingSubject {\n const { dims, group } = card\n const mass = card.mass ?? Math.round((DEFAULT_DENSITY[group] ?? 90) * dims.length * dims.width * dims.height)\n return {\n id,\n domain: (card.domains ?? DEFAULT_DOMAINS)[group] ?? 'land',\n category: group,\n stats: { acceleration: card.stats.acceleration, handling: card.stats.handling, maxSpeedKmh: card.stats.maxSpeedKmh },\n body: {\n mass,\n wheelbase: card.wheelbase ?? Math.round(dims.length * 0.6 * 100) / 100,\n track: card.track ?? Math.round(dims.width * 0.82 * 100) / 100,\n fourWheelDrive: !!card.fourWheelDrive,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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