@adatechnology/game-workers 0.1.12 → 0.1.14

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../game-contracts/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/rain-cover.ts","../../game-contracts/src/nav-obstacles.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/workers.ts","../../game-contracts/src/index.ts","../src/define.ts","../src/plan.ts","../src/protocol.ts","../src/coordinator.ts","../src/host.ts","../src/in-thread.ts","../src/check.ts","../src/spawn.ts","../src/shared.ts","../src/sim-thread.ts"],"sourcesContent":["export { checkTaskKind, firstDifference } from './check'\nexport type { KindReport } from './check'\nexport { createWorkerCoordinator, IN_FLIGHT_PER_WORKER, WorkerTaskCancelled, WorkerTaskDropped, WorkerTaskInputLost } from './coordinator'\nexport type { CoordinatorOptions } from './coordinator'\nexport { checkSchedule, defineResidentKind, defineTaskKind, kitScheduleOf } from './define'\nexport { installWorkerHost } from './host'\nexport { inThreadSpawn } from './in-thread'\nexport type { InThreadOptions } from './in-thread'\nexport { DEFAULT_MAX_WORKERS, hardwareCores, planWorkers } from './plan'\nexport type { LaneOptions, WorkerPlan, WorkerPlanOptions } from './plan'\nexport type { FromWorker, Spawn, ToWorker, WorkerLike, WorkerScopeLike } from './protocol'\nexport { browserSpawn, canSpawnBrowserWorkers, sourceSpawn } from './spawn'\nexport { CommandRing, SnapshotReader, SnapshotWriter, canShareMemory, createCommandBuffer, createSnapshotBuffer } from './shared'\nexport type { Snapshot } from './shared'\nexport { canRunSimThread, installSimThread, runSimInline, startSimThread } from './sim-thread'\nexport type { SimLoopOptions, SimThread, SimThreadOptions, SimThreadStats } from './sim-thread'\nexport type {\n AnyResidentKind,\n AnySimModule,\n AnyTaskKind,\n AnyWorkerKind,\n ResidentHandle,\n ResidentInstance,\n ResidentKind,\n SimInstance,\n SimModule,\n TaskHandle,\n TaskKind,\n WorkerCoordinator,\n WorkerCoordinatorStats,\n WorkerKindSchedule,\n WorkerKindStats,\n WorkerLane,\n WorkerLateRule,\n WorkerResultSource,\n} from '@adatechnology/game-contracts'\nexport { WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES } from '@adatechnology/game-contracts'\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. */\nexport const 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', '+', '-', 'all']\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/** A rotation as a unit quaternion [x, y, z, w]. */\nexport type ClipQuat = [number, number, number, number]\n\n/** Euler XYZ (three.js' default order, as in `AnimationPose.rotation`) to a quaternion. */\nexport const quatFromEuler = (e: readonly number[]): ClipQuat => {\n const c1 = Math.cos((e[0] ?? 0) / 2), c2 = Math.cos((e[1] ?? 0) / 2), c3 = Math.cos((e[2] ?? 0) / 2)\n const s1 = Math.sin((e[0] ?? 0) / 2), s2 = Math.sin((e[1] ?? 0) / 2), s3 = Math.sin((e[2] ?? 0) / 2)\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n}\n\n/** A quaternion to Euler XYZ (three.js' default order). */\nexport const eulerFromQuat = (q: readonly number[]): [number, number, number] => {\n const [x = 0, y = 0, z = 0, w = 1] = q\n const m13 = 2 * (x * z + w * y)\n const ey = Math.asin(Math.max(-1, Math.min(1, m13)))\n if (Math.abs(m13) < 0.9999999) return [Math.atan2(-2 * (y * z - w * x), 1 - 2 * (x * x + y * y)), ey, Math.atan2(-2 * (x * y - w * z), 1 - 2 * (y * y + z * z))]\n return [Math.atan2(2 * (y * z + w * x), 1 - 2 * (x * x + z * z)), ey, 0]\n}\n\n/** Spherical interpolation, the short way round. */\nexport const slerpQuat = (a: readonly number[], b: readonly number[], f: number): ClipQuat => {\n const [ax = 0, ay = 0, az = 0, aw = 1] = a\n let [bx = 0, by = 0, bz = 0, bw = 1] = b\n let cos = ax * bx + ay * by + az * bz + aw * bw\n if (cos < 0) {\n cos = -cos\n bx = -bx; by = -by; bz = -bz; bw = -bw\n }\n let ka = 1 - f\n let kb = f\n if (cos < 0.9999) {\n const angle = Math.acos(cos)\n const sin = Math.sin(angle)\n ka = Math.sin((1 - f) * angle) / sin\n kb = Math.sin(f * angle) / sin\n }\n const out: ClipQuat = [ax * ka + bx * kb, ay * ka + by * kb, az * ka + bz * kb, aw * ka + bw * kb]\n const size = Math.hypot(out[0], out[1], out[2], out[3]) || 1\n return [out[0] / size, out[1] / size, out[2] / size, out[3] / size]\n}\n\n/**\n * The turn between two keys. Euler angles cannot be mixed one by one: a door that opens past 90 degrees about y is the key (180, 82, 180)\n * degrees, and mixing those three numbers from (0, 0, 0) tips the door out of its plane on the way. So a turn about one axis (only one\n * angle changes: it may be more than a full turn, a fan or a knob) is mixed as that angle, and any other turn goes the short way round.\n */\nconst mixTurn = (from: readonly number[], to: readonly number[], fraction: number): { euler: [number, number, number]; quat: ClipQuat } => {\n let changed = 0\n for (let i = 0; i < 3; i++) if (Math.abs((to[i] ?? 0) - (from[i] ?? 0)) > 1e-9) changed++\n if (changed <= 1) {\n const euler = mix(from, to, fraction)\n return { euler, quat: quatFromEuler(euler) }\n }\n const quat = slerpQuat(quatFromEuler(from), quatFromEuler(to), fraction)\n return { euler: eulerFromQuat(quat), quat }\n}\n\n/** A pose sampled from a clip: `rotation` is Euler XYZ and `quaternion` the same turn; apply the quaternion on top of the rest rotation (rest × turn). */\nexport interface ClipSample {\n readonly position: [number, number, number]\n readonly rotation: [number, number, number]\n readonly quaternion: ClipQuat\n}\n\nconst IDENTITY: ClipQuat = [0, 0, 0, 1]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys (the turn as in `mixTurn`); a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): ClipSample => {\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: [0, 0, 0], rotation: [0, 0, 0], quaternion: [...IDENTITY] }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0), quaternion: quatFromEuler(last.rotation) }\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: [0, 0, 0], rotation: [0, 0, 0], quaternion: [...IDENTITY] }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n const turn = mixTurn(from.rotation, to.rotation, fraction)\n return { position: mix(from.position, to.position, fraction), rotation: turn.euler, quaternion: turn.quat }\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/** A fixed box a module gives the host as the body of an obstacle (`ModuleHost.addBlocker`): centre and half sizes in the world, the turn as a quaternion (default none). */\nexport interface HostSolid {\n readonly center: readonly [number, number, number]\n readonly half: readonly [number, number, number]\n readonly rotation?: readonly [number, number, number, number]\n /** Names the box across calls (a box measured again is the same box): without it, the place in the list. */\n readonly key?: string\n}\n\n/**\n * The fixed box of `footprint` on `object`, `height` metres tall from the floor: the body of what `footprintBlocker` stops the player at. An object out of the scene (no parent) has no box.\n * The turn is read from the object's x and z columns (a turn about the vertical axis, as the blocker reads it).\n */\nexport function footprintSolid(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined), height: number): HostSolid[] {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return []\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n const sx = Math.hypot(e[0] as number, e[2] as number) || 1\n const sz = Math.hypot(e[8] as number, e[10] as number) || 1\n const angle = Math.atan2(-(e[2] as number), e[0] as number)\n const cx = (fp.minX + fp.maxX) / 2\n const cz = (fp.minZ + fp.maxZ) / 2\n const centreX = (e[12] as number) + cx * (e[0] as number) + cz * (e[8] as number)\n const centreZ = (e[14] as number) + cx * (e[2] as number) + cz * (e[10] as number)\n return [{ center: [centreX, height / 2, centreZ], half: [((fp.maxX - fp.minX) / 2) * sx, height / 2, ((fp.maxZ - fp.minZ) / 2) * sz], rotation: [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)] }]\n}\n","/** A world rectangle `[x0, z0, x1, z1]`, metres. */\nexport type RainCoverBounds = readonly [x0: number, z0: number, x1: number, z1: number]\n\n/**\n * Something with a roof or a slab over it (a house, a shed, a bus stop, a car): it says, for a point on the ground plan, how high the cover over it is.\n * The rain asks before it falls, splashes or wets the ground: under a cover there is none.\n */\nexport interface RainCoverSource {\n /** Where the source may cover anything; a point outside is never asked. */\n bounds(): RainCoverBounds\n /** Top (world y, metres) of the highest intact roof or slab over (x, z); `undefined` for open sky, or for a hole a blast or a collapse opened. */\n coverTopAt(x: number, z: number): number | undefined\n /** Grows whenever the covers change (a roof panel broke, a hole opened): whoever caches reads it. */\n version(): number\n}\n\n/** What the rain reads (`ModuleHost.rainCover`): every source of the host together. */\nexport interface RainCover {\n /** The highest cover over (x, z) among the sources, or `undefined` for open sky. */\n coverTopAt(x: number, z: number): number | undefined\n /** Changes whenever a source is added or removed or one of them changes. */\n version(): number\n /** True while there is no source: the rain skips the test. */\n isEmpty(): boolean\n /** Adds a source; returns the function that takes it away. */\n add(source: RainCoverSource): () => void\n}\n\nexport function createRainCover(): RainCover {\n const sources = new Set<RainCoverSource>()\n let list: RainCoverSource[] = []\n let membership = 0\n return {\n coverTopAt(x, z) {\n let top: number | undefined\n for (const source of list) {\n const [x0, z0, x1, z1] = source.bounds()\n if (x < x0 || x > x1 || z < z0 || z > z1) continue\n const value = source.coverTopAt(x, z)\n if (value !== undefined && (top === undefined || value > top)) top = value\n }\n return top\n },\n version() {\n let sum = membership\n for (const source of list) sum += source.version()\n return sum\n },\n isEmpty: () => list.length === 0,\n add(source) {\n sources.add(source)\n list = [...sources]\n membership++\n return () => {\n if (!sources.delete(source)) return\n list = [...sources]\n membership++\n }\n },\n }\n}\n\nexport type GridRainCoverOptions = {\n readonly bounds: RainCoverBounds\n /** Side of a cell, metres (default 0.25: a blast hole is bigger). */\n readonly cellSize?: number\n /** The exact answer at a cell centre; called again for every cell only after `invalidate`. */\n readonly coverTopAt: (x: number, z: number) => number | undefined\n}\n\nexport type GridRainCoverSource = RainCoverSource & {\n /** The covers changed (a roof panel broke): the grid is cut again on the next question, and `version` grows. */\n invalidate(): void\n}\n\nconst NO_COVER = -Infinity\n\n/** A source answered from a grid cut once from `coverTopAt`: a question is two array reads, however many panels the roof has. */\nexport function createGridRainCover(options: GridRainCoverOptions): GridRainCoverSource {\n const [x0, z0, x1, z1] = options.bounds\n const cell = options.cellSize ?? 0.25\n const columns = Math.max(1, Math.ceil((x1 - x0) / cell))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cell))\n const cells = new Float32Array(columns * rows)\n let revision = 0\n let isCut = false\n const cut = (): void => {\n for (let row = 0; row < rows; row++) {\n for (let column = 0; column < columns; column++) {\n const top = options.coverTopAt(x0 + (column + 0.5) * cell, z0 + (row + 0.5) * cell)\n cells[row * columns + column] = top === undefined ? NO_COVER : top\n }\n }\n isCut = true\n }\n return {\n bounds: () => options.bounds,\n coverTopAt(x, z) {\n if (!isCut) cut()\n const column = Math.floor((x - x0) / cell)\n const row = Math.floor((z - z0) / cell)\n if (column < 0 || row < 0 || column >= columns || row >= rows) return undefined\n const top = cells[row * columns + column]!\n return top === NO_COVER ? undefined : top\n },\n version: () => revision,\n invalidate() {\n isCut = false\n revision++\n },\n }\n}\n\n/** A roof or slab seen from above: the rectangle it covers and the height of its top. */\nexport type RainCoverRect = { readonly bounds: RainCoverBounds; readonly top: number }\n\n/** A round opening in a cover (a blast hole), centre and radius in the ground plan. */\nexport type RainCoverHole = { readonly x: number; readonly z: number; readonly radius: number }\n\n/** The exact answer for a list of rectangles with holes: the highest rectangle over the point whose hole does not take the point. */\nexport function rainCoverTopOf(rects: readonly RainCoverRect[], holes: readonly RainCoverHole[], x: number, z: number): number | undefined {\n let top: number | undefined\n for (const rect of rects) {\n if (x < rect.bounds[0] || x > rect.bounds[2] || z < rect.bounds[1] || z > rect.bounds[3]) continue\n if (top !== undefined && rect.top <= top) continue\n if (holes.some((hole) => (x - hole.x) ** 2 + (z - hole.z) ** 2 <= hole.radius ** 2)) continue\n top = rect.top\n }\n return top\n}\n\n/** A roof seen from above as a turned rectangle: its centre on the ground plan, half sides along its own axes, the turn about y and the height of its top. */\nexport type RainCoverFootprint = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly yaw: number; readonly top: number }\n\nexport type FootprintRainCoverSource = RainCoverSource & {\n /**\n * Puts the roofs and the openings where they are now (a car moved, a window broke). The answer follows at once; the version grows only with `bumpVersion`,\n * which a mover asks once it has gone far enough for whoever caches (the far curtain) to cut again.\n */\n set(footprints: readonly RainCoverFootprint[], openings: readonly RainCoverFootprint[], bumpVersion: boolean): void\n}\n\ntype Prepared = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly cos: number; readonly sin: number; readonly top: number }\n\nconst prepare = (f: RainCoverFootprint): Prepared => ({ x: f.x, z: f.z, halfX: f.halfX, halfZ: f.halfZ, cos: Math.cos(f.yaw), sin: Math.sin(f.yaw), top: f.top })\n\nconst insideTurned = (f: Prepared, x: number, z: number): boolean => {\n const dx = x - f.x\n const dz = z - f.z\n return Math.abs(dx * f.cos + dz * f.sin) <= f.halfX && Math.abs(-dx * f.sin + dz * f.cos) <= f.halfZ\n}\n\n/**\n * A source of turned rectangles with openings (a car's cabin, a tent, a kiosk): a question is a few multiplications per rectangle, no allocation, so the near rain\n * asks it for every drop. `set` moves the rectangles whenever the thing moves; nothing else is cut or cached.\n */\nexport function createFootprintRainCover(): FootprintRainCoverSource {\n let roofs: Prepared[] = []\n let openings: Prepared[] = []\n let bounds: RainCoverBounds = [0, 0, 0, 0]\n let revision = 0\n return {\n bounds: () => bounds,\n version: () => revision,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) {\n if ((top !== undefined && roof.top <= top) || !insideTurned(roof, x, z)) continue\n top = roof.top\n }\n if (top === undefined) return undefined\n for (const opening of openings) if (insideTurned(opening, x, z)) return undefined\n return top\n },\n set(footprints, cutouts, bumpVersion) {\n roofs = footprints.map(prepare)\n openings = cutouts.map(prepare)\n let x0 = Infinity\n let z0 = Infinity\n let x1 = -Infinity\n let z1 = -Infinity\n for (const roof of roofs) {\n const reach = Math.abs(roof.halfX * roof.cos) + Math.abs(roof.halfZ * roof.sin)\n const reachZ = Math.abs(roof.halfX * roof.sin) + Math.abs(roof.halfZ * roof.cos)\n x0 = Math.min(x0, roof.x - reach)\n x1 = Math.max(x1, roof.x + reach)\n z0 = Math.min(z0, roof.z - reachZ)\n z1 = Math.max(z1, roof.z + reachZ)\n }\n bounds = roofs.length === 0 ? [0, 0, 0, 0] : [x0, z0, x1, z1]\n if (bumpVersion) revision++\n },\n }\n}\n\n/** The most cells a fixed footprint cover cuts: a wide district gets a coarser cell instead of a bigger grid. */\nconst FIXED_COVER_MAX_CELLS = 1_000_000\n\n/** A source of turned rectangles that never move (the buildings of a district, a tent, a kiosk): answered from a grid cut once, two array reads a question however many roofs there are. */\nexport function createFixedFootprintRainCover(footprints: readonly RainCoverFootprint[], cellSize = 0.5): RainCoverSource {\n const roofs = footprints.map(prepare)\n if (roofs.length === 0) return { bounds: () => [0, 0, 0, 0], coverTopAt: () => undefined, version: () => 0 }\n const x0 = Math.min(...roofs.map((r) => r.x - Math.abs(r.halfX * r.cos) - Math.abs(r.halfZ * r.sin)))\n const x1 = Math.max(...roofs.map((r) => r.x + Math.abs(r.halfX * r.cos) + Math.abs(r.halfZ * r.sin)))\n const z0 = Math.min(...roofs.map((r) => r.z - Math.abs(r.halfX * r.sin) - Math.abs(r.halfZ * r.cos)))\n const z1 = Math.max(...roofs.map((r) => r.z + Math.abs(r.halfX * r.sin) + Math.abs(r.halfZ * r.cos)))\n const cell = Math.max(cellSize, Math.sqrt(((x1 - x0) * (z1 - z0)) / FIXED_COVER_MAX_CELLS))\n return createGridRainCover({\n bounds: [x0, z0, x1, z1],\n cellSize: cell,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) if ((top === undefined || roof.top > top) && insideTurned(roof, x, z)) top = roof.top\n return top\n },\n })\n}\n","/** What an obstacle on the ground is to a walker: a solid (a wall, a lot wall, a fence, a board) or a door (a door or a gate, which opens and can be broken). */\nexport const NAV_OBSTACLE_KIND = { SOLID: 'solid', DOOR: 'door' } as const\nexport type NavObstacleKind = (typeof NAV_OBSTACLE_KIND)[keyof typeof NAV_OBSTACLE_KIND]\n\n/** A box of an obstacle on the ground: world metres `[x0, z0, x1, z1]` and how high it stands over the ground (a low remnant of a wall can be climbed). */\nexport type NavObstacleBox = {\n readonly rect: readonly [number, number, number, number]\n readonly height: number\n}\n\n/**\n * One thing that stops a walker on the ground, as the SDK that builds it publishes it for a navigation grid (the crowd's): a whole wall is one box, a wall a blast\n * cut stands in the boxes of what is left of it, a wall that is gone has none. A door is one box, passable while `open`.\n */\nexport type NavObstacle = {\n /** Stable for the life of the source: a change names the same obstacle again. */\n readonly id: string\n readonly kind: NavObstacleKind\n readonly boxes: readonly NavObstacleBox[]\n /** A door or a gate that lets walkers through now (always false for a solid). */\n readonly open: boolean\n /** A door the barricade's boards cover, each making it harder to break (0 for none). */\n readonly boards: number\n}\n\n/**\n * The obstacles one or more SDKs put on the ground (the houses' walls, doors, lot walls and gates), for whoever keeps a navigation grid. Pulled once per fixed step, so a\n * grid that follows it changes at the same step on every run.\n */\nexport type NavObstacleSource = {\n /** Every obstacle as it stands now. */\n obstacles(): readonly NavObstacle[]\n /** The obstacles that changed since the last call (a door opened or closed, a wall cut or gone); empty when none did. */\n changes(): readonly NavObstacle[]\n /** A walker broke the door `id` open (the horde hit it until it gave way): the owner shows it open. */\n breakDoor(id: string): void\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 spring_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 VEHICLE_HULL_PLAN: 'vehicles.hull-plan',\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 [WORKER_KIND_ID.VEHICLE_HULL_PLAN]: { lane: 'build', priority: 120, late: 'keep-waiting' },\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 PartSolid,\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 { TNT_JOULES, 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, eulerFromQuat, leadClipEvents, quatFromEuler, sampleClip, scaleClip, slerpQuat, toolAnimationStep } from './tool-animation'\nexport type { ClipQuat, ClipSample, 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 { ControlledHand, ItemControl, ItemControlResult, ItemControls, ItemControlsHost, ItemDose, ReachedItem } from './item-controls'\nexport type { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleItemUse, ModuleScenario, PlayerState, ItemSeat, HostSeatHolder, HostSeatState, HostSeating, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach, HostTakenItem, HostTap } 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, footprintSolid } from './footprint'\nexport { createFixedFootprintRainCover, createFootprintRainCover, createGridRainCover, createRainCover, rainCoverTopOf } from './rain-cover'\nexport type { FootprintRainCoverSource, GridRainCoverOptions, GridRainCoverSource, RainCover, RainCoverBounds, RainCoverFootprint, RainCoverHole, RainCoverRect, RainCoverSource } from './rain-cover'\nexport type { UtilityConnection, UtilityNetwork } from './utility'\nexport type { Footprint, FootprintObject, HostSolid } from './footprint'\nexport { NAV_OBSTACLE_KIND } from './nav-obstacles'\nexport type { NavObstacle, NavObstacleBox, NavObstacleKind, NavObstacleSource } from './nav-obstacles'\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","import { WORKER_KIND_DEFAULTS, WORKER_LANES, WORKER_LATE_RULES } from '@adatechnology/game-contracts'\nimport type { ResidentKind, TaskKind, WorkerKindSchedule } from '@adatechnology/game-contracts'\n\nconst ID = /^[a-z0-9-]+(\\.[a-z0-9-]+)+$/\n\n/** Checks a schedule: a known lane and rule, `sync` on the `sim` lane (its result is read in a fixed frame), a whole latency >= 1. */\nexport function checkSchedule(id: string, schedule: WorkerKindSchedule): void {\n if (!WORKER_LANES.includes(schedule.lane)) throw new Error(`worker kind ${id}: unknown lane \"${schedule.lane}\"`)\n if (!WORKER_LATE_RULES.includes(schedule.late)) throw new Error(`worker kind ${id}: unknown late rule \"${schedule.late}\"`)\n if (schedule.lane === 'sim' && schedule.late !== 'sync') throw new Error(`worker kind ${id}: the sim lane needs late \"sync\" (its result is applied in a fixed frame)`)\n if (!Number.isFinite(schedule.priority)) throw new Error(`worker kind ${id}: priority must be a number`)\n const latency = schedule.latencyFrames ?? 1\n if (!Number.isInteger(latency) || latency < 1) throw new Error(`worker kind ${id}: latencyFrames must be a whole number >= 1`)\n}\n\nconst checkId = (id: string): void => {\n if (!ID.test(id)) throw new Error(`worker kind \"${id}\": the id is \"package.thing\" in lowercase (destruction.ground-tiles)`)\n}\n\n/** The schedule a kit kind declares by default, by id (`WORKER_KIND_DEFAULTS`); `undefined` for a game's own kind. */\nexport const kitScheduleOf = (id: string): WorkerKindSchedule | undefined => (WORKER_KIND_DEFAULTS as Readonly<Record<string, WorkerKindSchedule>>)[id]\n\n/**\n * A task kind, checked: the id, the lane and the late rule. The kit's kinds take their schedule from `WORKER_KIND_DEFAULTS`.\n *\n * ```ts\n * export const pathfinding = defineTaskKind<PathInput, PathOutput>({ id: 'mygame.pathfinding', lane: 'sim', priority: 180, latencyFrames: 2, late: 'sync', run: aStar })\n * ```\n */\nexport function defineTaskKind<In, Out>(kind: Omit<TaskKind<In, Out>, 'kind'>): TaskKind<In, Out> {\n checkId(kind.id)\n checkSchedule(kind.id, kind)\n if (kind.transferAwaitedInput && !kind.transferInput) throw new Error(`worker kind ${kind.id}: transferAwaitedInput needs transferInput (the buffers to transfer)`)\n return Object.freeze({ ...kind, kind: 'task' as const })\n}\n\n/** A resident kind, checked as `defineTaskKind`. */\nexport function defineResidentKind<Init, Step, Result>(kind: Omit<ResidentKind<Init, Step, Result>, 'kind'>): ResidentKind<Init, Step, Result> {\n checkId(kind.id)\n checkSchedule(kind.id, kind)\n return Object.freeze({ ...kind, kind: 'resident' as const })\n}\n","import type { WorkerLane } from '@adatechnology/game-contracts'\n\nexport interface LaneOptions {\n /** Workers of this lane (default: the automatic split). */\n readonly workers?: number\n /** `build` only: its idle workers take `sim` jobs (default true). */\n readonly borrow?: boolean\n}\n\nexport interface WorkerPlanOptions {\n /** `'auto'` (default): `cores - 1 - reserveCores`, at most `maxWorkers`. A number: exactly that many. 0: everything on the main thread. */\n readonly workers?: 'auto' | number\n /** Ceiling of the automatic count (default 8). */\n readonly maxWorkers?: number\n /** Cores others use (Jolt's job threads, an audio worklet): the automatic count leaves them free. */\n readonly reserveCores?: number\n readonly lanes?: Partial<Readonly<Record<WorkerLane, LaneOptions>>>\n}\n\nexport interface WorkerPlan {\n readonly total: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n /** For each worker, by index, the lane it belongs to. */\n readonly homes: readonly WorkerLane[]\n /** For each worker, by index, the lanes it takes jobs from, in order (a `build` worker takes `sim` jobs first: they have a deadline). */\n readonly serves: readonly (readonly WorkerLane[])[]\n}\n\nexport const DEFAULT_MAX_WORKERS = 8\n\n/** The cores of this machine, or 1 where the runtime does not say. */\nexport function hardwareCores(): number {\n const n = (globalThis as { navigator?: { hardwareConcurrency?: number } }).navigator?.hardwareConcurrency\n return typeof n === 'number' && n > 0 ? n : 1\n}\n\nconst whole = (n: number): number => Math.max(0, Math.floor(n))\n\n/**\n * How many workers and which lanes each one serves. Automatic: `cores - 1 - reserveCores` workers (the main thread keeps a core), at most\n * `maxWorkers`; the `sim` lane takes a third rounded up (1 to 3), `background` gets its own worker from 6 on, `build` the rest. One worker\n * serves every lane. A `build` worker takes `sim` jobs first (they have a deadline), then its own, then `background` when that lane has\n * none of its own; a `background` worker never takes `sim` jobs, so the far world never delays a frame.\n */\nexport function planWorkers(options: WorkerPlanOptions = {}, cores = hardwareCores()): WorkerPlan {\n const max = whole(options.maxWorkers ?? DEFAULT_MAX_WORKERS)\n const asked = options.workers ?? 'auto'\n const total = asked === 'auto' ? Math.min(max, whole(cores - 1 - (options.reserveCores ?? 0))) : whole(asked)\n const fixed = options.lanes ?? {}\n let sim: number\n let background: number\n if (total <= 1) {\n sim = total\n background = 0\n } else {\n sim = Math.min(3, Math.max(1, Math.ceil(total / 3)))\n background = total >= 6 ? 1 : 0\n }\n if (fixed.sim?.workers !== undefined) sim = whole(fixed.sim.workers)\n if (fixed.background?.workers !== undefined) background = whole(fixed.background.workers)\n let build = fixed.build?.workers !== undefined ? whole(fixed.build.workers) : Math.max(0, total - sim - background)\n // lanes given by hand win over the total; the automatic split never goes over it\n if (fixed.sim?.workers === undefined && fixed.build?.workers === undefined && fixed.background?.workers === undefined) build = total - sim - background\n const count = sim + build + background\n const borrow = fixed.build?.borrow !== false\n const serves: WorkerLane[][] = []\n for (let i = 0; i < sim; i++) serves.push(['sim', ...(build === 0 ? (['build'] as const) : []), ...(build === 0 && background === 0 ? (['background'] as const) : [])])\n for (let i = 0; i < build; i++) serves.push([...(borrow ? (['sim'] as const) : []), 'build', ...(background === 0 ? (['background'] as const) : [])])\n for (let i = 0; i < background; i++) serves.push(['background'])\n const homes: WorkerLane[] = [...Array<WorkerLane>(sim).fill('sim'), ...Array<WorkerLane>(build).fill('build'), ...Array<WorkerLane>(background).fill('background')]\n return { total: count, lanes: { sim, build, background }, homes, serves }\n}\n","/** Messages between the coordinator and a worker host. One protocol for browser workers, `worker_threads` and the in-thread host. */\n\nexport type ToWorker =\n | { readonly t: 'hello'; readonly id: number }\n | { readonly t: 'task'; readonly id: number; readonly kind: string; readonly input: unknown }\n | { readonly t: 'create'; readonly rid: number; readonly kind: string; readonly init: unknown }\n | { readonly t: 'step'; readonly id: number; readonly rid: number; readonly input: unknown }\n | { readonly t: 'dispose'; readonly rid: number }\n\nexport type FromWorker =\n | { readonly t: 'hello'; readonly id: number; readonly kinds: readonly string[] }\n | { readonly t: 'done'; readonly id: number; readonly ok: true; readonly output: unknown; readonly ms: number }\n | { readonly t: 'done'; readonly id: number; readonly ok: false; readonly error: string; readonly ms: number }\n\n/** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, the in-thread host. */\nexport interface WorkerLike {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void\n terminate(): void\n}\n\n/** The worker side: `self` in a browser worker, `parentPort` in Node (through `nodeWorkerScope`), or the in-thread host. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null\n postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void\n}\n\n/** Makes one worker that runs `installWorkerHost` with the kinds the coordinator is asked for. */\nexport type Spawn = () => WorkerLike\n\nexport const isFromWorker = (data: unknown): data is FromWorker => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\nexport const isToWorker = (data: unknown): data is ToWorker => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\n","import { WORKER_INPUT_LOST, WORKER_LANES } from '@adatechnology/game-contracts'\nimport type {\n AnyWorkerKind,\n ResidentHandle,\n ResidentInstance,\n ResidentKind,\n TaskHandle,\n TaskKind,\n WorkerCoordinator,\n WorkerCoordinatorStats,\n WorkerKindSchedule,\n WorkerKindStats,\n WorkerLane,\n WorkerLateRule,\n WorkerResultSource,\n} from '@adatechnology/game-contracts'\nimport { checkSchedule } from './define'\nimport { planWorkers } from './plan'\nimport type { WorkerPlan, WorkerPlanOptions } from './plan'\nimport { isFromWorker } from './protocol'\nimport type { Spawn, ToWorker, WorkerLike } from './protocol'\n\n/** Jobs a worker holds at once unless `CoordinatorOptions.inFlightPerWorker` says otherwise (room measurement, spec 009 T7). */\nexport const IN_FLIGHT_PER_WORKER = 16\n\nexport interface CoordinatorOptions extends WorkerPlanOptions {\n /** Makes one worker (`browserSpawn`, `sourceSpawn`, `nodeSpawn`, `inThreadSpawn`). Without it every job runs on the main thread. */\n readonly spawn?: Spawn\n /** The game's overrides of a kind's schedule, by kind id. */\n readonly kinds?: Readonly<Record<string, Partial<WorkerKindSchedule>>>\n /**\n * Jobs a worker holds at once (default `IN_FLIGHT_PER_WORKER`, 16): the rest wait in the coordinator's queue, where a more urgent one can pass them. A job only leaves that\n * queue when the main thread reads a worker's answer, which on a busy frame is once per frame: a burst (a blast asks for dozens of ground tiles at once) with a small cap\n * needs several frames of round trips and misses its due frame. Measured in the room (crater, 4 threads): 2 left 139 of 163 tiles late, 16 none.\n */\n readonly inFlightPerWorker?: number\n /** The machine's cores for the automatic count (default `navigator.hardwareConcurrency`). */\n readonly cores?: number\n /** Clock in milliseconds (default `performance.now`). */\n readonly now?: () => number\n}\n\n/** The promise of a job given up by `late: 'drop'` rejects with it. */\nexport class WorkerTaskDropped extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind} dropped: no worker took it`)\n this.name = 'WorkerTaskDropped'\n }\n}\n\n/** The promise of a cancelled job rejects with it. */\nexport class WorkerTaskCancelled extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind} cancelled`)\n this.name = 'WorkerTaskCancelled'\n }\n}\n\n/**\n * The promise of an awaited job whose input was transferred (`transferAwaitedInput`) rejects with it when its worker died holding it: the input went with the worker, so the\n * coordinator cannot run it here; the caller makes it from its own copy (`isWorkerInputLost`). A worker that answers with an error rejects with that error instead.\n */\nexport class WorkerTaskInputLost extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind}: its worker died holding its transferred input`)\n this.name = WORKER_INPUT_LOST\n }\n}\n\ntype JobState = 'queued' | 'running' | 'done' | 'settled' | 'cancelled'\n\ntype KindCounters = { -readonly [K in keyof WorkerKindStats]: WorkerKindStats[K] }\n\ninterface Resident {\n readonly rid: number\n readonly kind: ResidentKind<unknown, unknown, unknown>\n readonly schedule: WorkerKindSchedule\n readonly init: unknown\n slot: Slot | null\n local: ResidentInstance<unknown, unknown> | null\n disposed: boolean\n}\n\ninterface Job {\n readonly id: number\n readonly seq: number\n readonly kindId: string\n readonly counters: KindCounters\n readonly lane: WorkerLane\n readonly priority: number\n readonly late: WorkerLateRule\n readonly dueFrame: number\n readonly message: ToWorker\n readonly transfer: readonly ArrayBuffer[]\n /** A `sync` job whose input is transferred (`transferAwaitedInput`): once sent, it cannot run here nor be sent again. */\n readonly moved: boolean\n readonly runHere: () => unknown\n readonly resident: Resident | null\n readonly queuedAt: number\n state: JobState\n /** Workers that died holding it: a job that keeps killing its worker runs here (or fails) instead of killing the next one. */\n crashes: number\n output: unknown\n error: Error | null\n source: WorkerResultSource | null\n slot: Slot | null\n readonly settle: { resolve: (value: unknown) => void; reject: (error: Error) => void }\n readonly promise: Promise<unknown>\n}\n\ninterface Slot {\n readonly index: number\n readonly home: WorkerLane\n readonly serves: readonly WorkerLane[]\n worker: WorkerLike\n readonly running: Map<number, Job>\n /** Steps of the residents pinned here, in order. */\n readonly own: Job[]\n readonly residents: Set<Resident>\n readonly hello: Map<number, (kinds: readonly string[]) => void>\n alive: boolean\n}\n\nconst MAX_CRASHES = 2\nconst MAX_RESPAWNS = 5\n\nconst defaultNow = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/** Higher priority first, then the nearest due frame, then the order of submission. */\nconst before = (a: Job, b: Job): boolean => a.priority > b.priority || (a.priority === b.priority && (a.dueFrame < b.dueFrame || (a.dueFrame === b.dueFrame && a.seq < b.seq)))\n\nconst insertSorted = (queue: Job[], job: Job): void => {\n let i = queue.length\n while (i > 0 && before(job, queue[i - 1]!)) i--\n queue.splice(i, 0, job)\n}\n\n/**\n * The coordinator of every worker of a game (see the `game-workers` README). `sim` jobs are applied in a fixed frame: `collect(dueFrame)`\n * gives the worker's answer when it is back and runs the same kernel here when it is not, so the result never depends on timing. The main\n * thread never waits for a worker.\n */\nexport function createWorkerCoordinator(options: CoordinatorOptions = {}): WorkerCoordinator & { readonly plan: WorkerPlan } {\n const now = options.now ?? defaultNow\n const perWorker = Math.max(1, Math.floor(options.inFlightPerWorker ?? IN_FLIGHT_PER_WORKER))\n const overrides = options.kinds ?? {}\n const plan: WorkerPlan = options.spawn ? planWorkers(options, options.cores) : { total: 0, lanes: { sim: 0, build: 0, background: 0 }, homes: [], serves: [] }\n const queues: Record<WorkerLane, Job[]> = { sim: [], build: [], background: [] }\n const mainQueue: Job[] = []\n const counters = new Map<string, KindCounters>()\n const residents = new Set<Resident>()\n const slots: Slot[] = []\n let frame = 0\n let nextId = 1\n let nextRid = 1\n let respawned = 0\n const deathsAt = new Map<number, number>()\n let disposed = false\n let mainTimer: ReturnType<typeof setTimeout> | null = null\n\n const countersOf = (kind: AnyWorkerKind, lane: WorkerLane): KindCounters => {\n let c = counters.get(kind.id)\n if (!c) counters.set(kind.id, (c = { id: kind.id, lane, submitted: 0, answered: 0, onTime: 0, fallback: 0, dropped: 0, cancelled: 0, failed: 0, workerMs: 0, mainMs: 0, queueMs: 0 }))\n return c\n }\n\n const scheduleOf = (kind: AnyWorkerKind): WorkerKindSchedule => {\n const own = overrides[kind.id]\n if (!own) return kind\n const merged: WorkerKindSchedule = { lane: own.lane ?? kind.lane, priority: own.priority ?? kind.priority, latencyFrames: own.latencyFrames ?? kind.latencyFrames, late: own.late ?? kind.late }\n checkSchedule(kind.id, merged)\n return merged\n }\n\n // ── workers ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n const makeSlot = (index: number, home: WorkerLane, serves: readonly WorkerLane[]): Slot | null => {\n let worker: WorkerLike\n try {\n worker = (options.spawn as Spawn)()\n } catch {\n return null\n }\n const slot: Slot = { index, home, serves, worker, running: new Map(), own: [], residents: new Set(), hello: new Map(), alive: true }\n worker.onmessage = (event) => onReply(slot, event.data)\n worker.onerror = () => onCrash(slot)\n return slot\n }\n\n for (let i = 0; i < plan.serves.length; i++) {\n const slot = makeSlot(i, plan.homes[i]!, plan.serves[i]!)\n if (slot) slots.push(slot)\n }\n const served = (lane: WorkerLane): boolean => slots.some((slot) => slot.serves.includes(lane))\n const homeOf = (lane: WorkerLane): Slot | null => {\n let best: Slot | null = null\n for (const slot of slots) {\n if (!slot.alive || !slot.serves.includes(lane)) continue\n const own = slot.home === lane ? 0 : 1\n const bestOwn = best && best.home === lane ? 0 : 1\n if (!best || own < bestOwn || (own === bestOwn && slot.residents.size < best.residents.size)) best = slot\n }\n return best\n }\n\n const send = (slot: Slot, job: Job): void => {\n job.state = 'running'\n job.slot = slot\n job.counters.queueMs += now() - job.queuedAt\n slot.running.set(job.id, job)\n try {\n slot.worker.postMessage(job.message, job.transfer)\n } catch (error) {\n // a message that cannot be posted (an input that does not clone) is not the caller's synchronous throw: a sync job runs here (nothing was transferred), any other fails\n slot.running.delete(job.id)\n job.slot = null\n job.counters.failed++\n if (job.late === 'sync') runOnMain(job)\n else fail(job, error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n const dispatch = (): void => {\n if (disposed) return\n for (const slot of slots) {\n while (slot.alive && slot.running.size < perWorker) {\n let job = slot.own.shift()\n if (!job) for (const lane of slot.serves) if ((job = queues[lane].shift())) break\n if (!job) break\n send(slot, job)\n }\n }\n }\n\n const onReply = (slot: Slot, data: unknown): void => {\n if (!isFromWorker(data)) return\n if (data.t === 'hello') {\n slot.hello.get(data.id)?.(data.kinds)\n slot.hello.delete(data.id)\n return\n }\n const job = slot.running.get(data.id)\n if (!job) return\n slot.running.delete(data.id)\n job.counters.workerMs += data.ms\n job.counters.answered++\n if (job.state === 'running') {\n if (data.ok) {\n job.state = 'done'\n job.output = data.output\n job.source = 'worker'\n // a job with no frame to wait for is on time as soon as it is back\n if (job.lane !== 'sim' && !job.resident) finish(job)\n else job.settle.resolve(job.output)\n } else {\n job.counters.failed++\n // a transferred input cannot run here: the worker's own error (the kernel threw, or the worker does not host the kind)\n if (job.late === 'sync' && !job.moved) runOnMain(job)\n else fail(job, new Error(data.error))\n }\n }\n dispatch()\n }\n\n const onCrash = (slot: Slot): void => {\n if (!slot.alive) return\n slot.alive = false\n slot.worker.terminate()\n const deaths = (deathsAt.get(slot.index) ?? 0) + 1\n deathsAt.set(slot.index, deaths)\n // a worker that keeps dying (a script that does not load) is not replaced forever: its lanes fall back to the others, or the main thread\n const replacement = disposed || deaths > MAX_RESPAWNS ? null : makeSlot(slot.index, slot.home, slot.serves)\n if (replacement) {\n respawned++\n slots[slots.indexOf(slot)] = replacement\n } else slots.splice(slots.indexOf(slot), 1)\n for (const resident of slot.residents) {\n resident.slot = replacement\n if (replacement) {\n replacement.residents.add(resident)\n replacement.worker.postMessage({ t: 'create', rid: resident.rid, kind: resident.kind.id, init: resident.init } satisfies ToWorker)\n }\n }\n // what the dead worker held goes back in line, steps of a resident first and in their order\n const waiting = [...slot.own]\n const back = [...slot.running.values()].filter((job) => job.state === 'running').sort((a, b) => a.seq - b.seq)\n slot.own.length = 0\n for (const job of back) job.crashes++\n for (const job of [...back, ...waiting]) {\n job.state = 'queued'\n job.slot = null\n if (job.crashes >= MAX_CRASHES || job.moved) {\n job.counters.failed++\n if (job.moved) fail(job, new WorkerTaskInputLost(job.kindId))\n else if (job.late === 'sync') runOnMain(job)\n else fail(job, new Error(`${job.kindId}: its worker died ${job.crashes} times running it`))\n } else if (job.resident) {\n if (replacement) replacement.own.push(job)\n // no worker for it any more: it is run here when it is collected\n } else if (served(job.lane)) insertSorted(queues[job.lane], job)\n else toMain(job)\n }\n dispatch()\n }\n\n // ── results ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n const finish = (job: Job): void => {\n if (job.source === 'worker') job.counters.onTime++\n job.state = 'settled'\n job.settle.resolve(job.output)\n }\n const fail = (job: Job, error: Error): void => {\n job.state = 'settled'\n job.error = error\n job.settle.reject(error)\n }\n const unqueue = (job: Job): void => {\n for (const queue of [queues[job.lane], mainQueue, job.resident?.slot?.own ?? []]) {\n const at = queue.indexOf(job)\n if (at >= 0) queue.splice(at, 1)\n }\n }\n /** The kernel here, now: a late worker, a crash, or no worker. A running job's answer is thrown away when it comes. */\n const runOnMain = (job: Job): void => {\n unqueue(job)\n const started = now()\n try {\n job.output = job.runHere()\n job.source = 'main'\n job.counters.fallback++\n job.counters.mainMs += now() - started\n finish(job)\n } catch (error) {\n job.counters.mainMs += now() - started\n fail(job, error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n const drainMain = (): void => {\n mainTimer = null\n const job = mainQueue.shift()\n if (job && job.state === 'queued') runOnMain(job)\n if (mainQueue.length && !disposed) mainTimer = setTimeout(drainMain, 0)\n }\n /** A `build` or `background` job no worker can take: dropped, or run here one per macrotask, by priority. */\n const toMain = (job: Job): void => {\n if (job.late === 'drop') {\n job.counters.dropped++\n fail(job, new WorkerTaskDropped(job.kindId))\n return\n }\n insertSorted(mainQueue, job)\n if (!mainTimer) mainTimer = setTimeout(drainMain, 0)\n }\n\n // ── jobs ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n interface JobSpec {\n readonly kind: AnyWorkerKind\n readonly schedule: WorkerKindSchedule\n readonly dueFrame: number\n readonly message: (id: number) => ToWorker\n readonly transfer: readonly ArrayBuffer[]\n readonly moved?: boolean\n readonly runHere: () => unknown\n readonly resident: Resident | null\n }\n const makeJob = (spec: JobSpec): Job => {\n let settle: Job['settle'] = { resolve: () => undefined, reject: () => undefined }\n const promise = new Promise<unknown>((resolve, reject) => (settle = { resolve, reject }))\n // a job read only through `collect` must not leave an unhandled rejection behind\n promise.catch(() => undefined)\n const id = nextId++\n const job: Job = {\n id,\n seq: id,\n kindId: spec.kind.id,\n counters: countersOf(spec.kind, spec.schedule.lane),\n lane: spec.schedule.lane,\n priority: spec.schedule.priority,\n late: spec.schedule.late,\n dueFrame: spec.dueFrame,\n message: spec.message(id),\n transfer: spec.transfer,\n moved: spec.moved ?? false,\n runHere: spec.runHere,\n resident: spec.resident,\n queuedAt: now(),\n state: 'queued',\n crashes: 0,\n output: undefined,\n error: null,\n source: null,\n slot: null,\n settle,\n promise,\n }\n job.counters.submitted++\n return job\n }\n\n const handleOf = <Out>(job: Job): TaskHandle<Out> => ({\n dueFrame: job.dueFrame,\n promise: job.promise as Promise<Out>,\n get source() {\n return job.source\n },\n collect(at: number): Out {\n if (at < job.dueFrame) throw new Error(`${job.kindId}: collected in frame ${at}, before its due frame ${job.dueFrame}`)\n if (job.state === 'cancelled') throw new WorkerTaskCancelled(job.kindId)\n if (job.state === 'done') finish(job)\n else if (job.state === 'queued' || job.state === 'running') runOnMain(job)\n if (job.error) throw job.error\n return job.output as Out\n },\n cancel(): void {\n if (job.state !== 'queued' && job.state !== 'running') return\n unqueue(job)\n job.state = 'cancelled'\n job.counters.cancelled++\n job.settle.reject(new WorkerTaskCancelled(job.kindId))\n },\n })\n\n const enqueue = (job: Job): void => {\n if (disposed) throw new Error('worker coordinator: disposed')\n if (job.resident) {\n if (job.resident.slot) job.resident.slot.own.push(job)\n // a resident with no worker runs here, at its collect\n } else if (served(job.lane)) insertSorted(queues[job.lane], job)\n else if (job.lane !== 'sim') toMain(job)\n // a sim job no worker serves waits for its collect, where it runs here\n dispatch()\n }\n\n const latencyOf = (schedule: WorkerKindSchedule, at?: { readonly latencyFrames?: number }): number => Math.max(1, Math.floor(at?.latencyFrames ?? schedule.latencyFrames ?? 1))\n\n const taskJob = <In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }, awaited = false): Job => {\n const schedule = scheduleOf(kind as TaskKind<unknown, unknown>)\n const submitted = at?.frame ?? frame\n const moved = schedule.late === 'sync' && awaited && kind.transferAwaitedInput === true && kind.transferInput !== undefined\n const job = makeJob({\n kind: kind as TaskKind<unknown, unknown>,\n schedule,\n dueFrame: schedule.lane === 'sim' ? submitted + latencyOf(schedule, at) : Number.POSITIVE_INFINITY,\n message: (id) => ({ t: 'task', id, kind: kind.id, input }),\n transfer: schedule.late === 'sync' && !moved ? [] : [...(kind.transferInput?.(input) ?? [])],\n moved,\n runHere: () => kind.run(input),\n resident: null,\n })\n return job\n }\n\n const coordinator: WorkerCoordinator & { readonly plan: WorkerPlan } = {\n plan,\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out> {\n const job = taskJob(kind, input, at)\n enqueue(job)\n return handleOf<Out>(job)\n },\n\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out> {\n const job = taskJob(kind, input, undefined, true)\n enqueue(job)\n // nobody collects an awaited job: a `sim` kind with no worker to serve it runs here, as the other lanes do (the simulation thread awaits its jobs)\n if (job.lane === 'sim' && job.state === 'queued' && !served('sim')) toMain(job)\n const handle = handleOf<Out>(job)\n if (signal) {\n if (signal.aborted) handle.cancel()\n else signal.addEventListener('abort', () => handle.cancel(), { once: true })\n }\n return handle.promise\n },\n\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result> {\n const any = kind as unknown as ResidentKind<unknown, unknown, unknown>\n const schedule = scheduleOf(any)\n const resident: Resident = { rid: nextRid++, kind: any, schedule, init, slot: homeOf(schedule.lane), local: null, disposed: false }\n residents.add(resident)\n resident.slot?.residents.add(resident)\n resident.slot?.worker.postMessage({ t: 'create', rid: resident.rid, kind: kind.id, init } satisfies ToWorker)\n const local = (): ResidentInstance<unknown, unknown> => (resident.local ??= any.create(init))\n return {\n id: kind.id,\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result> {\n if (resident.disposed) throw new Error(`${kind.id}: resident disposed`)\n const submitted = at?.frame ?? frame\n const job = makeJob({\n kind: any,\n schedule,\n dueFrame: submitted + latencyOf(schedule, at),\n message: (id) => ({ t: 'step', id, rid: resident.rid, input }),\n transfer: schedule.late === 'sync' ? [] : [...(kind.transferInput?.(input) ?? [])],\n runHere: () => local().step(input),\n resident,\n })\n enqueue(job)\n return handleOf<Result>(job)\n },\n dispose(): void {\n if (resident.disposed) return\n resident.disposed = true\n residents.delete(resident)\n resident.slot?.residents.delete(resident)\n if (resident.slot?.alive) resident.slot.worker.postMessage({ t: 'dispose', rid: resident.rid } satisfies ToWorker)\n resident.local?.dispose?.()\n },\n }\n },\n\n tick(at: number): void {\n frame = at\n dispatch()\n },\n\n async warm(kinds: readonly AnyWorkerKind[]): Promise<void> {\n for (const kind of kinds) scheduleOf(kind)\n await Promise.all(\n slots.map(async (slot) => {\n const id = nextId++\n const known = await new Promise<readonly string[]>((resolve) => {\n slot.hello.set(id, resolve)\n slot.worker.postMessage({ t: 'hello', id } satisfies ToWorker)\n })\n const missing = kinds.filter((kind) => !known.includes(kind.id)).map((kind) => kind.id)\n if (missing.length) throw new Error(`worker ${slot.index} does not know ${missing.join(', ')}: add them to its installWorkerHost`)\n }),\n )\n // each worker runs each warm-up once, straight to it (the queue would give them all to the first free worker)\n const warmups: Promise<unknown>[] = []\n for (const kind of kinds) {\n if (kind.kind !== 'task' || kind.warmup === undefined) continue\n for (const slot of slots) {\n const job = makeJob({ kind, schedule: scheduleOf(kind), dueFrame: Number.NEGATIVE_INFINITY, message: (id) => ({ t: 'task', id, kind: kind.id, input: kind.warmup }), transfer: [], runHere: () => kind.run(kind.warmup), resident: null })\n job.counters.submitted--\n send(slot, job)\n warmups.push(job.promise.catch(() => undefined))\n }\n }\n await Promise.all(warmups)\n },\n\n scheduleOf,\n\n stats(): WorkerCoordinatorStats {\n let running = 0\n for (const slot of slots) running += slot.running.size\n const lanes = { sim: 0, build: 0, background: 0 }\n for (const slot of slots) lanes[slot.home]++\n return {\n workers: slots.length,\n lanes,\n queued: WORKER_LANES.reduce((n, lane) => n + queues[lane].length, 0) + mainQueue.length + slots.reduce((n, slot) => n + slot.own.length, 0),\n running,\n respawned,\n kinds: [...counters.values()].map((c) => ({ ...c })),\n }\n },\n\n dispose(): void {\n if (disposed) return\n disposed = true\n if (mainTimer) clearTimeout(mainTimer)\n const pending = [...WORKER_LANES.flatMap((lane) => queues[lane]), ...mainQueue, ...slots.flatMap((slot) => [...slot.own, ...slot.running.values()])]\n for (const job of pending) if (job.state === 'queued' || job.state === 'running') fail(job, new Error('worker coordinator: disposed'))\n for (const slot of slots) {\n slot.alive = false\n slot.worker.terminate()\n }\n for (const resident of residents) resident.local?.dispose?.()\n residents.clear()\n slots.length = 0\n },\n }\n return coordinator\n}\n","import type { AnyResidentKind, AnyWorkerKind, ResidentInstance } from '@adatechnology/game-contracts'\nimport { isToWorker } from './protocol'\nimport type { FromWorker, WorkerScopeLike } from './protocol'\n\nconst now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/**\n * The worker side of the coordinator: answers each job with the kind's own `run` (or the resident instance's `step`) and transfers the\n * output's buffers back. Call it in the file the worker loads, with every kind the game registers, the kit's and its own:\n *\n * ```ts\n * // game-worker.ts\n * import { installWorkerHost } from '@adatechnology/game-workers'\n * installWorkerHost(self, [...KIT_WORKER_KINDS, pathfinding])\n * ```\n */\nexport function installWorkerHost(scope: WorkerScopeLike, kinds: readonly AnyWorkerKind[]): void {\n const byId = new Map<string, AnyWorkerKind>()\n for (const kind of kinds) {\n if (byId.has(kind.id) && byId.get(kind.id) !== kind) throw new Error(`installWorkerHost: two kinds with the id ${kind.id}`)\n byId.set(kind.id, kind)\n }\n const residents = new Map<number, { kind: AnyResidentKind; instance: ResidentInstance<unknown, unknown> }>()\n const reply = (message: FromWorker, transfer: readonly ArrayBuffer[] = []): void => scope.postMessage(message, transfer)\n const fail = (id: number, error: unknown, started: number): void => reply({ t: 'done', id, ok: false, error: error instanceof Error ? error.message : String(error), ms: now() - started })\n\n scope.onmessage = (event) => {\n const message = event.data\n if (!isToWorker(message)) return\n switch (message.t) {\n case 'hello':\n reply({ t: 'hello', id: message.id, kinds: [...byId.keys()] })\n return\n case 'task': {\n const started = now()\n const kind = byId.get(message.kind)\n if (!kind || kind.kind !== 'task') return fail(message.id, new Error(`this worker has no task kind ${message.kind}`), started)\n try {\n const output = kind.run(message.input)\n reply({ t: 'done', id: message.id, ok: true, output, ms: now() - started }, kind.transferOutput?.(output) ?? [])\n } catch (error) {\n fail(message.id, error, started)\n }\n return\n }\n case 'create': {\n const kind = byId.get(message.kind)\n // an unknown kind answers at its first step, where there is a job id to fail\n if (kind?.kind === 'resident') residents.set(message.rid, { kind, instance: kind.create(message.init) })\n return\n }\n case 'step': {\n const started = now()\n const resident = residents.get(message.rid)\n if (!resident) return fail(message.id, new Error(`this worker has no resident ${message.rid}`), started)\n try {\n const output = resident.instance.step(message.input)\n reply({ t: 'done', id: message.id, ok: true, output, ms: now() - started }, resident.kind.transferOutput?.(output) ?? [])\n } catch (error) {\n fail(message.id, error, started)\n }\n return\n }\n case 'dispose':\n residents.get(message.rid)?.instance.dispose?.()\n residents.delete(message.rid)\n return\n }\n }\n}\n","import type { AnyWorkerKind } from '@adatechnology/game-contracts'\nimport { installWorkerHost } from './host'\nimport type { Spawn, WorkerLike, WorkerScopeLike } from './protocol'\n\nexport interface InThreadOptions {\n /** Milliseconds before each answer reaches the coordinator (default 0: the next macrotask), to play a slow worker in tests. */\n readonly delayMs?: number\n}\n\n/**\n * A worker that runs `installWorkerHost` in this thread and answers on a later macrotask, as a real one does: the same protocol, the same\n * copy of the input (`structuredClone`) and the same transfer of the output. For tests, and the reference of `checkTaskKind`.\n */\nexport function inThreadSpawn(kinds: readonly AnyWorkerKind[], options: InThreadOptions = {}): Spawn {\n return () => {\n let alive = true\n const worker: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage(message, transfer = []) {\n const copy: unknown = structuredClone(message, { transfer: [...transfer] })\n setTimeout(() => alive && scope.onmessage?.({ data: copy }), 0)\n },\n terminate() {\n alive = false\n },\n }\n const scope: WorkerScopeLike = {\n onmessage: null,\n postMessage(message, transfer = []) {\n const copy: unknown = structuredClone(message, { transfer: [...transfer] })\n setTimeout(() => alive && worker.onmessage?.({ data: copy }), options.delayMs ?? 0)\n },\n }\n installWorkerHost(scope, kinds)\n return worker\n }\n}\n","import type { AnyWorkerKind, TaskKind } from '@adatechnology/game-contracts'\nimport { createWorkerCoordinator } from './coordinator'\nimport { inThreadSpawn } from './in-thread'\nimport type { Spawn } from './protocol'\n\nexport interface KindReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nconst bytesOf = (view: ArrayBufferView): Uint8Array => new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n\n/** Where two values differ, byte for byte in typed arrays (`-0`, `NaN` payloads included); `null` when they are the same. */\nexport function firstDifference(a: unknown, b: unknown, path = 'output'): string | null {\n if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {\n if (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b) || a.constructor !== b.constructor) return `${path}: not the same kind of array`\n const x = bytesOf(a)\n const y = bytesOf(b)\n if (x.length !== y.length) return `${path}: ${x.length} bytes against ${y.length}`\n for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return `${path}: byte ${i} differs`\n return null\n }\n if (a instanceof ArrayBuffer || b instanceof ArrayBuffer) {\n if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) return `${path}: not both ArrayBuffers`\n return firstDifference(new Uint8Array(a), new Uint8Array(b), path)\n }\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return Object.is(a, b) ? null : `${path}: ${String(a)} against ${String(b)}`\n if (Array.isArray(a) !== Array.isArray(b)) return `${path}: an array against an object`\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of keys) {\n const difference = firstDifference((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], `${path}.${key}`)\n if (difference) return difference\n }\n return null\n}\n\n/**\n * The equivalence test every kind passes (CLAUDE.md §14): each sample run on the main thread, through the in-thread worker (the protocol,\n * the copy and the transfer) and through each `spawn` given (a real `worker_threads` worker in CI), and the outputs compared byte for byte.\n * `extraKinds`: the other kinds the given workers host.\n */\nexport async function checkTaskKind<In, Out>(kind: TaskKind<In, Out>, samples: readonly In[], spawns: readonly Spawn[] = [], extraKinds: readonly AnyWorkerKind[] = []): Promise<KindReport> {\n const problems: string[] = []\n const any = kind as TaskKind<unknown, unknown>\n const paths: { name: string; spawn: Spawn }[] = [{ name: 'in-thread worker', spawn: inThreadSpawn([any, ...extraKinds]) }, ...spawns.map((spawn, i) => ({ name: `worker ${i + 1}`, spawn }))]\n for (const path of paths) {\n const coordinator = createWorkerCoordinator({ spawn: path.spawn, workers: 1 })\n try {\n await coordinator.warm([any])\n for (let i = 0; i < samples.length; i++) {\n const reference = kind.run(structuredClone(samples[i]) as In)\n const handle = coordinator.submit(kind, structuredClone(samples[i]) as In, { frame: 0 })\n const out = await handle.promise\n if (handle.source !== 'worker') problems.push(`${kind.id} sample ${i}: ${path.name} did not answer (${handle.source ?? 'no result'})`)\n const difference = firstDifference(reference, out)\n if (difference) problems.push(`${kind.id} sample ${i}, ${path.name}: ${difference}`)\n // an awaited job of a kind that transfers its input goes another way: checked too\n if (kind.transferAwaitedInput) {\n const awaited = firstDifference(reference, await coordinator.run(kind, structuredClone(samples[i]) as In))\n if (awaited) problems.push(`${kind.id} sample ${i}, ${path.name}, awaited: ${awaited}`)\n }\n }\n } catch (error) {\n problems.push(`${kind.id}, ${path.name}: ${error instanceof Error ? error.message : String(error)}`)\n } finally {\n coordinator.dispose()\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","import type { Spawn, WorkerLike } from './protocol'\n\ninterface BrowserWorker {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer: Transferable[]): void\n terminate(): void\n}\ntype WorkerConstructor = new (url: string | URL, options?: { type?: 'module' | 'classic'; name?: string }) => BrowserWorker\n\nconst workerConstructor = (): WorkerConstructor | null => (globalThis as { Worker?: WorkerConstructor }).Worker ?? null\n\n/** Whether this runtime has browser workers. */\nexport const canSpawnBrowserWorkers = (): boolean => workerConstructor() !== null\n\nconst wrap = (worker: BrowserWorker): WorkerLike => {\n const like: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage: (message, transfer = []) => worker.postMessage(message, [...transfer]),\n terminate: () => worker.terminate(),\n }\n worker.onmessage = (event) => like.onmessage?.(event)\n worker.onerror = (event) => like.onerror?.(event)\n return like\n}\n\n/**\n * Module workers that load `url`, the file that calls `installWorkerHost` (a bundler resolves `new URL('./game-worker.js', import.meta.url)`).\n * Throws where there is no `Worker`; the coordinator then runs every job on the main thread.\n */\nexport function browserSpawn(url: string | URL, options: { readonly type?: 'module' | 'classic'; readonly name?: string } = {}): Spawn {\n return () => {\n const Ctor = workerConstructor()\n if (!Ctor) throw new Error('browserSpawn: no Worker in this runtime')\n return wrap(new Ctor(url, { type: options.type ?? 'module', ...(options.name ? { name: options.name } : {}) }))\n }\n}\n\n/**\n * Workers made from the worker's own source text, for a page that is one file (no worker file beside it to load): the build embeds the\n * bundle of the worker as a string and this makes a Blob URL of it once.\n */\nexport function sourceSpawn(source: string, options: { readonly type?: 'module' | 'classic'; readonly name?: string } = {}): Spawn {\n let url: string | null = null\n return () => {\n if (!url) {\n if (typeof Blob === 'undefined' || typeof URL.createObjectURL !== 'function') throw new Error('sourceSpawn: no Blob URLs in this runtime')\n url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }))\n }\n return browserSpawn(url, options)()\n }\n}\n","/**\n * Memory the main thread and the simulation thread share, with no lock and no wait on the main thread (it may not wait in a browser or in\n * the Electron renderer): a triple buffer of snapshots (the simulation writes, the page reads the newest whole one) and a ring of commands\n * (the page writes input, the simulation drains it at the start of a step). One writer and one reader each.\n */\n\nconst HEADER_BYTES = 32\nconst SLOTS = 3\n// header Int32 words of the snapshot buffer\nconst PUBLISHED = 0 // slot + 1 of the newest whole snapshot, 0 before the first\nconst CLAIMED = 1 // slot + 1 the reader is reading, 0 none\nconst FRAME = 2 // frame of each slot (3 words)\n\nconst align8 = (n: number): number => Math.ceil(n / 8) * 8\n\n/** Whether this runtime shares memory between threads: `SharedArrayBuffer` and, in a page, cross-origin isolation (COOP/COEP; always in Electron). */\nexport function canShareMemory(): boolean {\n if (typeof SharedArrayBuffer === 'undefined' || typeof Atomics === 'undefined') return false\n const isolated = (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated\n return isolated !== false\n}\n\n/** A buffer of three snapshots of `bytes` each. */\nexport function createSnapshotBuffer(bytes: number): SharedArrayBuffer {\n return new SharedArrayBuffer(HEADER_BYTES + SLOTS * align8(bytes))\n}\n\nconst slotBytes = (buffer: SharedArrayBuffer): number => (buffer.byteLength - HEADER_BYTES) / SLOTS\n\n/** One snapshot as the reader sees it: valid until its next `latest()`, which may hand the slot back to the writer. */\nexport interface Snapshot {\n readonly frame: number\n readonly buffer: SharedArrayBuffer\n readonly byteOffset: number\n readonly byteLength: number\n readonly bytes: Uint8Array\n}\n\n/** The writer's side (the simulation thread): `begin` a free slot, fill it, `commit` it with its frame. Never waits. */\nexport class SnapshotWriter {\n private readonly header: Int32Array\n private readonly views: Uint8Array[]\n private slot = -1\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4)\n const size = slotBytes(buffer)\n this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * size, size))\n }\n /** A slot neither published nor being read: there is always one of the three. */\n begin(): Uint8Array {\n const published = Atomics.load(this.header, PUBLISHED) - 1\n const claimed = Atomics.load(this.header, CLAIMED) - 1\n let slot = 0\n while (slot === published || slot === claimed) slot++\n this.slot = slot\n return this.views[slot]!\n }\n commit(frame: number): void {\n if (this.slot < 0) throw new Error('SnapshotWriter.commit: no begin')\n Atomics.store(this.header, FRAME + this.slot, frame)\n Atomics.store(this.header, PUBLISHED, this.slot + 1)\n this.slot = -1\n }\n}\n\n/** The reader's side (the page): the newest whole snapshot, or `null` before the first. Never waits; retries only when a commit lands mid-claim. */\nexport class SnapshotReader {\n private readonly header: Int32Array\n private readonly size: number\n private readonly views: Uint8Array[]\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4)\n this.size = slotBytes(buffer)\n this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * this.size, this.size))\n }\n latest(): Snapshot | null {\n for (;;) {\n const published = Atomics.load(this.header, PUBLISHED)\n if (published === 0) return null\n Atomics.store(this.header, CLAIMED, published)\n // the writer only skips the claimed slot from its next begin on: the claim holds when the slot is still the newest after it\n if (Atomics.load(this.header, PUBLISHED) !== published) continue\n const slot = published - 1\n return {\n frame: Atomics.load(this.header, FRAME + slot),\n buffer: this.buffer,\n byteOffset: HEADER_BYTES + slot * this.size,\n byteLength: this.size,\n bytes: this.views[slot]!,\n }\n }\n }\n /** Lets the writer take the slot of the last snapshot (the reader is done with it). */\n release(): void {\n Atomics.store(this.header, CLAIMED, 0)\n }\n}\n\nconst RING_HEADER_BYTES = 8 // Int32: written, read\n\n/** A ring of `capacity` commands of `width` numbers each. */\nexport function createCommandBuffer(width: number, capacity: number): SharedArrayBuffer {\n if (!Number.isInteger(width) || width < 1 || !Number.isInteger(capacity) || capacity < 1) throw new Error('createCommandBuffer: width and capacity are integers >= 1')\n const buffer = new SharedArrayBuffer(RING_HEADER_BYTES + 8 + width * capacity * 8)\n // the layout is read back from the buffer: width in the slot after the header\n new Float64Array(buffer, RING_HEADER_BYTES, 1)[0] = width\n return buffer\n}\n\n/** Both ends of the ring: the page `push`es, the simulation `drain`s; a full ring refuses the command (`false`) rather than waiting. */\nexport class CommandRing {\n private readonly header: Int32Array\n private readonly data: Float64Array\n readonly width: number\n readonly capacity: number\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, 2)\n this.width = new Float64Array(buffer, RING_HEADER_BYTES, 1)[0]!\n this.data = new Float64Array(buffer, RING_HEADER_BYTES + 8)\n this.capacity = this.data.length / this.width\n }\n push(command: ArrayLike<number>): boolean {\n if (command.length > this.width) throw new Error(`CommandRing.push: ${command.length} numbers, the ring holds ${this.width}`)\n const written = Atomics.load(this.header, 0)\n if (written - Atomics.load(this.header, 1) >= this.capacity) return false\n const at = (written % this.capacity) * this.width\n this.data.fill(0, at, at + this.width)\n for (let k = 0; k < command.length; k++) this.data[at + k] = command[k]!\n Atomics.store(this.header, 0, written + 1)\n return true\n }\n /** Every command pushed so far, oldest first, each a copy. */\n drain(): Float64Array[] {\n const written = Atomics.load(this.header, 0)\n const read = Atomics.load(this.header, 1)\n const out: Float64Array[] = []\n for (let k = read; k < written; k++) {\n const at = (k % this.capacity) * this.width\n out.push(this.data.slice(at, at + this.width))\n }\n Atomics.store(this.header, 1, written)\n return out\n }\n}\n","import { CommandRing, SnapshotReader, SnapshotWriter, canShareMemory, createCommandBuffer, createSnapshotBuffer } from './shared'\nimport type { Snapshot } from './shared'\nimport type { AnySimModule, SimInstance, SimModule } from '@adatechnology/game-contracts'\nimport type { Spawn, WorkerScopeLike } from './protocol'\n\n/**\n * The simulation thread (spec 009, T22): the whole fixed step of a game runs in one dedicated worker, which **may wait** (for the jobs it\n * hands to other workers, for its next step), as the main thread of a native engine's simulation does. The page only pushes input into a\n * command ring and draws the newest whole snapshot, so it never waits, in a browser or in the Electron renderer.\n *\n * The same module also runs on the calling thread (`runSimInline`): the snapshot bytes are the same after the same steps and commands, which\n * is what the equivalence test checks.\n */\n\nexport interface SimLoopOptions {\n /** Seconds of one fixed step (default 1/60). */\n readonly stepSeconds?: number\n /** Stop after this many steps (tests, a replay); default: run until `stop`. */\n readonly steps?: number\n /** Steps on the clock (default) or as fast as they compute (`false`: tests, a server). */\n readonly paced?: boolean\n /** Steps the loop catches up after a stall before it drops the time instead (default 4). */\n readonly maxCatchUp?: number\n}\n\nexport interface SimThreadOptions<Init> extends SimLoopOptions {\n readonly module: string\n readonly init: Init\n /** Bytes of one snapshot. */\n readonly snapshotBytes: number\n /** Numbers in one command (default 8) and commands the ring holds (default 256). */\n readonly commandWidth?: number\n readonly commandCapacity?: number\n}\n\nexport interface SimThreadStats {\n /** Steps done. */\n readonly steps: number\n readonly lastStepMs: number\n readonly meanStepMs: number\n readonly maxStepMs: number\n /** Stalls the loop gave up catching up on. */\n readonly dropped: number\n}\n\n/** The page's side of a running simulation thread. */\nexport interface SimThread {\n /** Resolves when the module is built and the first step is about to run; rejects when the thread could not build it. */\n readonly ready: Promise<void>\n /** Resolves with the steps done when the loop ends (`steps` reached or `stop`). */\n readonly done: Promise<number>\n /** The newest whole snapshot (never waits), `null` before the first. Valid until the next `latest`. */\n latest(): Snapshot | null\n /** Queues a command for the start of the next step; `false` when the ring is full. */\n send(command: ArrayLike<number>): boolean\n stats(): SimThreadStats\n /** Ends the loop after the step it is in. */\n stop(): void\n /** Stops and terminates the worker. */\n dispose(): void\n}\n\n// control buffer: Int32 words, then Float64 numbers from byte 32\nconst STOP = 0\nconst STEPS = 1\nconst WAKE = 2\nconst DROPPED = 3\nconst LAST_MS = 0\nconst SUM_MS = 1\nconst MAX_MS = 2\nconst CONTROL_BYTES = 64\n\ntype ToSim = {\n readonly t: 'sim-start'\n readonly module: string\n readonly init: unknown\n readonly snapshot: SharedArrayBuffer\n readonly commands: SharedArrayBuffer\n readonly control: SharedArrayBuffer\n readonly loop: SimLoopOptions\n}\ntype FromSim = { readonly t: 'sim-ready' } | { readonly t: 'sim-done'; readonly steps: number } | { readonly t: 'sim-error'; readonly error: string }\n\nconst now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\nconst message = (error: unknown): string => (error instanceof Error ? error.message : String(error))\nconst isThenable = (value: unknown): value is PromiseLike<void> => typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function'\n\ninterface LoopIo {\n readonly ring: CommandRing\n readonly writer: SnapshotWriter\n readonly control: SharedArrayBuffer\n /** A real sleep: `Atomics.wait` in a worker; never called with `paced: false`. */\n readonly sleep: (ms: number) => void\n /** Called before each step's drain (the inline runner pushes that frame's commands). */\n readonly beforeStep?: (frame: number) => void\n}\n\n/** The fixed-step loop, the same in the simulation thread and inline: drain commands, step (awaited), write the snapshot, sleep to the next step. */\nasync function simLoop(instance: SimInstance, options: SimLoopOptions, io: LoopIo): Promise<number> {\n const stepSeconds = options.stepSeconds ?? 1 / 60\n const stepMs = stepSeconds * 1000\n const paced = options.paced ?? true\n const maxCatchUp = options.maxCatchUp ?? 4\n const words = new Int32Array(io.control, 0, 8)\n const numbers = new Float64Array(io.control, 32, 4)\n let frame = 0\n let next = now()\n while (Atomics.load(words, STOP) === 0 && (options.steps === undefined || frame < options.steps)) {\n if (paced) {\n const wait = next - now()\n if (wait > 0.25) {\n io.sleep(wait)\n continue\n }\n if (-wait > maxCatchUp * stepMs) {\n next = now()\n Atomics.add(words, DROPPED, 1)\n }\n }\n io.beforeStep?.(frame)\n const commands = io.ring.drain()\n const started = now()\n const stepped = instance.step(frame, stepSeconds, commands)\n if (isThenable(stepped)) await stepped\n instance.write(io.writer.begin(), frame)\n io.writer.commit(frame)\n const ms = now() - started\n numbers[LAST_MS] = ms\n numbers[SUM_MS] = numbers[SUM_MS]! + ms\n if (ms > numbers[MAX_MS]!) numbers[MAX_MS] = ms\n frame++\n Atomics.store(words, STEPS, frame)\n next += stepMs\n }\n return frame\n}\n\nconst statsOf = (control: SharedArrayBuffer): SimThreadStats => {\n const words = new Int32Array(control, 0, 8)\n const numbers = new Float64Array(control, 32, 4)\n const steps = Atomics.load(words, STEPS)\n return { steps, lastStepMs: numbers[LAST_MS]!, meanStepMs: steps ? numbers[SUM_MS]! / steps : 0, maxStepMs: numbers[MAX_MS]!, dropped: Atomics.load(words, DROPPED) }\n}\n\nconst isToSim = (data: unknown): data is ToSim => typeof data === 'object' && data !== null && (data as { t?: unknown }).t === 'sim-start'\nconst isFromSim = (data: unknown): data is FromSim => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\n\n/**\n * The simulation thread's side: call it in the file of the simulation worker with every module the game may start.\n *\n * ```ts\n * // sim-worker.ts\n * import { installSimThread } from '@adatechnology/game-workers'\n * installSimThread(self, [hordeSim])\n * ```\n */\nexport function installSimThread(scope: WorkerScopeLike, modules: readonly AnySimModule[]): void {\n const byId = new Map(modules.map((m) => [m.id, m]))\n scope.onmessage = (event) => {\n const start = event.data\n if (!isToSim(start)) return\n const reply = (m: FromSim): void => scope.postMessage(m)\n const module = byId.get(start.module)\n if (!module) {\n reply({ t: 'sim-error', error: `installSimThread: no module ${start.module} (this thread has ${[...byId.keys()].join(', ') || 'none'})` })\n return\n }\n const words = new Int32Array(start.control, 0, 8)\n const io: LoopIo = {\n ring: new CommandRing(start.commands),\n writer: new SnapshotWriter(start.snapshot),\n control: start.control,\n // a worker may wait: this is the native engine's sleep, woken early by `stop`\n sleep: (ms) => void Atomics.wait(words, WAKE, 0, ms),\n }\n void (async () => {\n let instance: SimInstance | null = null\n try {\n instance = await module.create(start.init)\n reply({ t: 'sim-ready' })\n reply({ t: 'sim-done', steps: await simLoop(instance, start.loop, io) })\n } catch (error) {\n reply({ t: 'sim-error', error: message(error) })\n } finally {\n instance?.dispose?.()\n }\n })()\n }\n}\n\n/** Whether a simulation thread can run here: shared memory (`canShareMemory`) and workers to spawn. */\nexport const canRunSimThread = (): boolean => canShareMemory()\n\n/** Starts `options.module` in a new worker from `spawn` (a worker that calls `installSimThread`). Throws where memory cannot be shared. */\nexport function startSimThread<Init>(spawn: Spawn, options: SimThreadOptions<Init>): SimThread {\n if (!canShareMemory()) throw new Error('startSimThread: no shared memory here (SharedArrayBuffer and cross-origin isolation: COOP/COEP, always on in Electron)')\n const snapshot = createSnapshotBuffer(options.snapshotBytes)\n const commands = createCommandBuffer(options.commandWidth ?? 8, options.commandCapacity ?? 256)\n const control = new SharedArrayBuffer(CONTROL_BYTES)\n const words = new Int32Array(control, 0, 8)\n const reader = new SnapshotReader(snapshot)\n const ring = new CommandRing(commands)\n const worker = spawn()\n let readyResolve!: () => void\n let readyReject!: (error: Error) => void\n let doneResolve!: (steps: number) => void\n let doneReject!: (error: Error) => void\n const ready = new Promise<void>((resolve, reject) => ((readyResolve = resolve), (readyReject = reject)))\n const done = new Promise<number>((resolve, reject) => ((doneResolve = resolve), (doneReject = reject)))\n // a caller that awaits only `ready` sees the failure there: `done`'s copy of it is not an unhandled rejection\n done.catch(() => {})\n const fail = (error: Error): void => {\n readyReject(error)\n doneReject(error)\n }\n worker.onmessage = (event) => {\n const data = event.data\n if (!isFromSim(data)) return\n if (data.t === 'sim-ready') readyResolve()\n else if (data.t === 'sim-done') doneResolve(data.steps)\n else fail(new Error(data.error))\n }\n worker.onerror = (event) => fail(event instanceof Error ? event : new Error(`simulation thread failed: ${message((event as { message?: unknown }).message ?? event)}`))\n const loop: SimLoopOptions = {\n ...(options.stepSeconds !== undefined ? { stepSeconds: options.stepSeconds } : {}),\n ...(options.steps !== undefined ? { steps: options.steps } : {}),\n ...(options.paced !== undefined ? { paced: options.paced } : {}),\n ...(options.maxCatchUp !== undefined ? { maxCatchUp: options.maxCatchUp } : {}),\n }\n const start: ToSim = { t: 'sim-start', module: options.module, init: options.init, snapshot, commands, control, loop }\n worker.postMessage(start)\n const stop = (): void => {\n Atomics.store(words, STOP, 1)\n Atomics.notify(words, WAKE)\n }\n return {\n ready,\n done,\n latest: () => reader.latest(),\n send: (command) => ring.push(command),\n stats: () => statsOf(control),\n stop,\n dispose: () => {\n stop()\n worker.terminate()\n },\n }\n}\n\n/**\n * The same module and loop on this thread, unpaced: the snapshot after `steps` steps, with `commands[frame]` pushed before that step. The\n * reference the simulation thread must match byte for byte, and the fallback where memory cannot be shared.\n */\nexport async function runSimInline<Init>(\n module: SimModule<Init>,\n init: Init,\n options: { readonly steps: number; readonly snapshotBytes: number; readonly stepSeconds?: number; readonly commands?: readonly (readonly ArrayLike<number>[])[]; readonly commandWidth?: number },\n): Promise<Uint8Array> {\n const snapshot = createSnapshotBuffer(options.snapshotBytes)\n const control = new SharedArrayBuffer(CONTROL_BYTES)\n const ring = new CommandRing(createCommandBuffer(options.commandWidth ?? 8, 4096))\n const instance = await module.create(init)\n try {\n await simLoop(instance, { steps: options.steps, paced: false, ...(options.stepSeconds !== undefined ? { stepSeconds: options.stepSeconds } : {}) }, {\n ring,\n writer: new SnapshotWriter(snapshot),\n control,\n sleep: () => {},\n beforeStep: (frame) => {\n for (const command of options.commands?.[frame] ?? []) if (!ring.push(command)) throw new Error('runSimInline: more commands in one frame than the ring holds')\n },\n })\n } finally {\n instance.dispose?.()\n }\n return new SnapshotReader(snapshot).latest()!.bytes.slice()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,MAAM,wBAAiE,EAAE,UAAU,KAAK,MAAM,MAAM,UAAU,KAAK,aAAa,OAAO,IAAO;AKVrJ,MAAM,gCAAgC,OAAO;AYmCtC,MAAM,oBAAoB;IAC/B,oBAAoB;IACpB,cA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AAI;AAAA,IAC5B;AACA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,QAAQ,MAAM,OAAO,OAAO;AAAA,MAC5B,MAAM,CAAC,YAAY,KAAK,KAAK,OAAO;AAAA,MACpC,OAAO,MAAM,QAAQ,OAAO;AAAA,MAC5B;AAAA,MACA,SAAS,MAAM;AACb,aAAK;AACL,eAAO,UAAU;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AAMA,iBAAsB,aACpB,QACA,MACA,SACqB;AACrB,UAAM,WAAW,qBAAqB,QAAQ,aAAa;AAC3D,UAAM,UAAU,IAAI,kBAAkB,aAAa;AACnD,UAAM,OAAO,IAAI,YAAY,oBAAoB,QAAQ,gBAAgB,GAAG,IAAI,CAAC;AACjF,UAAM,WAAW,MAAM,OAAO,OAAO,IAAI;AACzC,QAAI;AACF,YAAM,QAAQ,UAAU,EAAE,OAAO,QAAQ,OAAO,OAAO,OAAO,GAAI,QAAQ,gBAAgB,SAAY,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC,EAAG,GAAG;AAAA,QAClJ;AAAA,QACA,QAAQ,IAAI,eAAe,QAAQ;AAAA,QACnC;AAAA,QACA,OAAO,MAAM;AAAA,QAAC;AAAA,QACd,YAAY,CAAC,UAAU;AACrB,qBAAW,WAAW,QAAQ,WAAW,KAAK,KAAK,CAAC,EAAG,KAAI,CAAC,KAAK,KAAK,OAAO,EAAG,OAAM,IAAI,MAAM,8DAA8D;AAAA,QAChK;AAAA,MACF,CAAC;AAAA,IACH,UAAE;AACA,eAAS,UAAU;AAAA,IACrB;AACA,WAAO,IAAI,eAAe,QAAQ,EAAE,OAAO,EAAG,MAAM,MAAM;AAAA,EAC5D;","names":["now","message","message","message","now"]}
1
+ {"version":3,"sources":["../src/index.ts","../../game-contracts/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/item-controls.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/rain-cover.ts","../../game-contracts/src/nav-obstacles.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/workers.ts","../../game-contracts/src/index.ts","../src/define.ts","../src/plan.ts","../src/protocol.ts","../src/coordinator.ts","../src/host.ts","../src/in-thread.ts","../src/check.ts","../src/spawn.ts","../src/shared.ts","../src/sim-thread.ts"],"sourcesContent":["export { checkTaskKind, firstDifference } from './check'\nexport type { KindReport } from './check'\nexport { createWorkerCoordinator, IN_FLIGHT_PER_WORKER, WorkerTaskCancelled, WorkerTaskDropped, WorkerTaskInputLost } from './coordinator'\nexport type { CoordinatorOptions } from './coordinator'\nexport { checkSchedule, defineResidentKind, defineTaskKind, kitScheduleOf } from './define'\nexport { installWorkerHost } from './host'\nexport { inThreadSpawn } from './in-thread'\nexport type { InThreadOptions } from './in-thread'\nexport { DEFAULT_MAX_WORKERS, hardwareCores, planWorkers } from './plan'\nexport type { LaneOptions, WorkerPlan, WorkerPlanOptions } from './plan'\nexport type { FromWorker, Spawn, ToWorker, WorkerLike, WorkerScopeLike } from './protocol'\nexport { browserSpawn, canSpawnBrowserWorkers, sourceSpawn } from './spawn'\nexport { CommandRing, SnapshotReader, SnapshotWriter, canShareMemory, createCommandBuffer, createSnapshotBuffer } from './shared'\nexport type { Snapshot } from './shared'\nexport { canRunSimThread, installSimThread, runSimInline, startSimThread } from './sim-thread'\nexport type { SimLoopOptions, SimThread, SimThreadOptions, SimThreadStats } from './sim-thread'\nexport type {\n AnyResidentKind,\n AnySimModule,\n AnyTaskKind,\n AnyWorkerKind,\n ResidentHandle,\n ResidentInstance,\n ResidentKind,\n SimInstance,\n SimModule,\n TaskHandle,\n TaskKind,\n WorkerCoordinator,\n WorkerCoordinatorStats,\n WorkerKindSchedule,\n WorkerKindStats,\n WorkerLane,\n WorkerLateRule,\n WorkerResultSource,\n} from '@adatechnology/game-contracts'\nexport { WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES } from '@adatechnology/game-contracts'\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. */\nexport const 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 /** How far the seat's backrest leans back from upright, radians, when the seat has one drawn. */\n readonly recline?: number\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', '+', '-', 'all']\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/**\n * Told every frame, after the arms reached for the targets, where the hands really are (world space, `HandPose`): an arm stops where a person's stops (the wrist turns only so far, the\n * elbow folds only so far), so a hand may end short of its target or turned from it. A tool held rigid in that hand (a knife, a bat, a spanner) is moved with it, its grip staying in the\n * palm, and the next read of the source answers the targets of the tool where it now is (the other hand comes to it). A side left out was not drawn. Answers whether the tool moved: only\n * then are the targets read again and the arms reach again (a gun keeps its aim and never moves; a blade in a hand that came to its grip does not either).\n */\nexport type HandSeat = (reached: { readonly R?: HandPose | null; readonly L?: HandPose | null }) => boolean\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\n/**\n * The `userData` flag of the part of a drawn thing that is its carry handle (a bucket's bail, a jerrycan's or a toolbox's handle): a hand takes the thing there and carries it\n * hanging (`gripOnHandle` of game-player). The model that draws the thing sets it; the host finds it in the drawing.\n */\nexport const CARRY_HANDLE_TAG = 'carryHandle'\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/** A rotation as a unit quaternion [x, y, z, w]. */\nexport type ClipQuat = [number, number, number, number]\n\n/** Euler XYZ (three.js' default order, as in `AnimationPose.rotation`) to a quaternion. */\nexport const quatFromEuler = (e: readonly number[]): ClipQuat => {\n const c1 = Math.cos((e[0] ?? 0) / 2), c2 = Math.cos((e[1] ?? 0) / 2), c3 = Math.cos((e[2] ?? 0) / 2)\n const s1 = Math.sin((e[0] ?? 0) / 2), s2 = Math.sin((e[1] ?? 0) / 2), s3 = Math.sin((e[2] ?? 0) / 2)\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n}\n\n/** A quaternion to Euler XYZ (three.js' default order). */\nexport const eulerFromQuat = (q: readonly number[]): [number, number, number] => {\n const [x = 0, y = 0, z = 0, w = 1] = q\n const m13 = 2 * (x * z + w * y)\n const ey = Math.asin(Math.max(-1, Math.min(1, m13)))\n if (Math.abs(m13) < 0.9999999) return [Math.atan2(-2 * (y * z - w * x), 1 - 2 * (x * x + y * y)), ey, Math.atan2(-2 * (x * y - w * z), 1 - 2 * (y * y + z * z))]\n return [Math.atan2(2 * (y * z + w * x), 1 - 2 * (x * x + z * z)), ey, 0]\n}\n\n/** Spherical interpolation, the short way round. */\nexport const slerpQuat = (a: readonly number[], b: readonly number[], f: number): ClipQuat => {\n const [ax = 0, ay = 0, az = 0, aw = 1] = a\n let [bx = 0, by = 0, bz = 0, bw = 1] = b\n let cos = ax * bx + ay * by + az * bz + aw * bw\n if (cos < 0) {\n cos = -cos\n bx = -bx; by = -by; bz = -bz; bw = -bw\n }\n let ka = 1 - f\n let kb = f\n if (cos < 0.9999) {\n const angle = Math.acos(cos)\n const sin = Math.sin(angle)\n ka = Math.sin((1 - f) * angle) / sin\n kb = Math.sin(f * angle) / sin\n }\n const out: ClipQuat = [ax * ka + bx * kb, ay * ka + by * kb, az * ka + bz * kb, aw * ka + bw * kb]\n const size = Math.hypot(out[0], out[1], out[2], out[3]) || 1\n return [out[0] / size, out[1] / size, out[2] / size, out[3] / size]\n}\n\n/**\n * The turn between two keys. Euler angles cannot be mixed one by one: a door that opens past 90 degrees about y is the key (180, 82, 180)\n * degrees, and mixing those three numbers from (0, 0, 0) tips the door out of its plane on the way. So a turn about one axis (only one\n * angle changes: it may be more than a full turn, a fan or a knob) is mixed as that angle, and any other turn goes the short way round.\n */\nconst mixTurn = (from: readonly number[], to: readonly number[], fraction: number): { euler: [number, number, number]; quat: ClipQuat } => {\n let changed = 0\n for (let i = 0; i < 3; i++) if (Math.abs((to[i] ?? 0) - (from[i] ?? 0)) > 1e-9) changed++\n if (changed <= 1) {\n const euler = mix(from, to, fraction)\n return { euler, quat: quatFromEuler(euler) }\n }\n const quat = slerpQuat(quatFromEuler(from), quatFromEuler(to), fraction)\n return { euler: eulerFromQuat(quat), quat }\n}\n\n/** A pose sampled from a clip: `rotation` is Euler XYZ and `quaternion` the same turn; apply the quaternion on top of the rest rotation (rest × turn). */\nexport interface ClipSample {\n readonly position: [number, number, number]\n readonly rotation: [number, number, number]\n readonly quaternion: ClipQuat\n}\n\nconst IDENTITY: ClipQuat = [0, 0, 0, 1]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys (the turn as in `mixTurn`); a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): ClipSample => {\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: [0, 0, 0], rotation: [0, 0, 0], quaternion: [...IDENTITY] }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0), quaternion: quatFromEuler(last.rotation) }\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: [0, 0, 0], rotation: [0, 0, 0], quaternion: [...IDENTITY] }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n const turn = mixTurn(from.rotation, to.rotation, fraction)\n return { position: mix(from.position, to.position, fraction), rotation: turn.euler, quaternion: turn.quat }\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","/**\n * What an object of a module does beyond what every host does with any piece (open its doors, take it, push it, sit on it): a TV turned on and its channel\n * changed, a tap opened, a washing machine run, a bin given what the hand holds. The module owns the state and the rules (`TestableItem.controls`); the host\n * lists the controls in its menu, runs the one the player picks, lends its hand and its parts, and advances the object every frame.\n */\ntype Vec3Tuple = readonly [number, number, number]\n\n/** What an item works as for an object's uses (`ItemDef.tools` of game-items): a `plunger` pumps a clogged trap. */\nexport const ITEM_TOOLS = ['plunger'] as const\nexport type ItemTool = (typeof ITEM_TOOLS)[number]\n\n/** What the player's hand holds, as an object of the world can take it. */\nexport interface ControlledHand {\n /** The catalogue id of the item. */\n readonly itemId: string\n readonly name: string\n readonly kg: number\n /** Width, height and depth, metres. */\n readonly size: Vec3Tuple\n /** The liquid it holds now, when it is a container with something in it (`water`, `milk`...); `closed`: shut (a capped bottle), it pours nothing until opened. */\n readonly liquid?: { readonly kind: string; readonly litres: number; readonly closed?: boolean }\n /** What the item works as (its catalogue `tools`): an object's use that needs a tool asks for it here, never by the item's id. */\n readonly tools?: readonly ItemTool[]\n}\n\n/** What an object's controls ask of the host. */\nexport interface ItemControlsHost {\n /** What the hand holds now; null when it is empty. */\n hand(): ControlledHand | null\n /** The hand lets go of what it holds inside the object, at `point` (object-local, metres): a thing of the world again, lying there. False when it could not. */\n placeHand(point: Vec3Tuple): boolean\n /** Pours up to `litres` of the hand's liquid into the object; returns the litres that left the hand. */\n pourHand(litres: number): number\n /** Works one of the object's moving parts the host moves itself (a tap handle, a rocker, a lid): `open` true to its open or on end. False when there is no such part. */\n setPart(part: string, open: boolean): boolean\n /** How open that part is now, 0 closed (or off) to 1 open (or on). */\n partOpening(part: string): number\n /** Takes out of the world every loose thing and every drawn content inside the object-local box from `from` to `to` (a bin emptied); returns how many. */\n emptyInside(from: Vec3Tuple, to: Vec3Tuple): number\n /** Tells the player something the object did on its own time (a wash finished). */\n say(text: string): void\n /**\n * The first item of one of the catalogue `ids` the player can use now: the one in the hand first, then the nearest within reach of the player (a cup on the\n * counter, the soap on the basin). Null when there is none. A host without items to lend leaves it out (the uses that need one are then unavailable).\n */\n itemAt?(ids: readonly string[]): ReachedItem | null\n /**\n * The vessel the player can drink from now: an item whose container is open, takes liquid and holds no things (a glass, a mug, a coffee cup; not a mug with a\n * toothbrush in it), the one in the hand first, then the nearest clean one within reach. Known by what the item is, never by its name.\n */\n vesselAt?(): ReachedItem | null\n /**\n * The body steps toward the object-local point `at` for `dt` seconds (up to the sink, to reach under its tap) and turns the eye to it; answers true once it stands\n * there or the object stops it. A host whose player does not walk leaves it out (the use then reaches from where the body is).\n */\n approach?(at: Vec3Tuple, dt: number): boolean\n /** Both hands are free: nothing held, no weapon or tool in them (what drinking from the cupped hands needs). */\n handsFree?(): boolean\n /** The items of one of the catalogue `ids` lying inside the object-local box from `from` to `to` (the dishes in a sink's basin). */\n itemsInside?(ids: readonly string[], from: Vec3Tuple, to: Vec3Tuple): readonly ReachedItem[]\n /** Takes one dose (`dose` in the item's own unit, its usual dose when left out) out of a consumable item (detergent, soap, toothpaste). */\n takeDose?(objectId: string, dose?: number): ItemDose\n /**\n * The player's body plays the hand use `clip` (a hand use of the host's catalogue: `wash_dishes`, `fill_cup`, `drink`), with the item `objectId` in the hand when given;\n * `at` (object-local) is where the use reaches to: the hands bring the glass, the dish or themselves under the stream there (the use's `reach` keys).\n */\n playUse?(clip: string, objectId?: string, at?: Vec3Tuple): boolean\n /** The hand takes the item `objectId` (a cup from the counter); false when it cannot. */\n holdItem?(objectId: string): boolean\n /** The item `objectId` goes down, still, at the object-local `point` (a washed plate on the drainboard, the cup back where it was). */\n placeItem?(objectId: string, point: Vec3Tuple): boolean\n /** How dirty the item `objectId` is now, 0 clean to 1 caked (what is left of food on a plate); the host keeps and draws it. */\n setDirt?(objectId: string, dirt: number): void\n /** Pours up to `litres` of `liquid` into the item `objectId` (a cup under the tap); returns the litres it took. */\n fillItem?(objectId: string, liquid: string, litres: number): number\n /** The player drinks up to `litres` out of the item `objectId`; returns the litres drunk. */\n drinkItem?(objectId: string, litres: number): number\n /**\n * The player drinks up to `litres` of `liquid` caught in the cupped hands from a running fixture's stream; the hands are wet and what they do not hold runs off\n * through the fingers. Returns the litres drunk.\n */\n drinkFromHands?(liquid: string, litres: number): number\n /** Scrubs `amount` (0..1 of a full layer) of foam onto `target` (an item's `objectId`, or a part of the body: `hands`, `hair`, `body`, `mouth`); returns the foam on it now, 0..1. */\n lather?(target: string, amount: number): number\n /** Runs `flowLps` litres per second of water over `target` for `dt` seconds; returns the foam left on it, 0..1. */\n rinse?(target: string, flowLps: number, dt: number): number\n /**\n * The body that uses the object (the player's): its sex decides how it uses a toilet, and it takes the pose of a use that has one (`ItemControlResult.body`). The\n * object runs the use's time and tells the body; the host only moves and draws it. A host without a body leaves it out: the uses that need one are then refused,\n * with the reason, never answered as done. This and the four below are optional for a host whose objects have no such use; an object that needs them refuses\n * its uses without them.\n */\n body?(): ControlledBody | null\n /** Shows `litres` of liquid in the object's basin (`BasinSpec.id` of game-interactables): the host's liquid there rises or falls to it. */\n setBasin?(basin: string, litres: number): void\n /** Liquid that went over the object's rim at `point` (object-local, metres), gathered by the object over a short while: the host spills it there as its own liquid (a puddle). */\n spill?(point: Vec3Tuple, litres: number, liquid: string): void\n /** The loose things of the world lying inside the object-local box from `from` to `to` (an object dropped in a toilet bowl), with their size. */\n looseInside?(from: Vec3Tuple, to: Vec3Tuple): readonly LooseThing[]\n /**\n * The loose thing `id` goes down the object's drain toward `point` (object-local): `progress` runs from 0 where it lay to 1, once a step while it goes (the object\n * runs the time). At 1 it leaves the world; the host draws the way down.\n */\n swallow?(id: string, point: Vec3Tuple, progress: number): void\n}\n\n/** An item the host lends an object's use (`ItemControlsHost.itemAt`). */\nexport interface ReachedItem {\n /** The host's id of the item in the world. */\n readonly objectId: string\n /** Its catalogue id. */\n readonly itemId: string\n /** Localized. */\n readonly name: string\n /** In the player's hand, within the player's reach, or inside a box of the object. */\n readonly where: 'hand' | 'reach' | 'inside'\n /** Where it lies now, object-local metres (the place a cup goes back to). */\n readonly at?: Vec3Tuple\n /** 0 clean to 1 caked. */\n readonly dirt?: number\n /** Share of a consumable still in it, 0 (spent) to 1 (full). */\n readonly remaining?: number\n /** The liquid it holds now and how much it takes full, litres. */\n readonly liquid?: { readonly kind?: string; readonly litres: number; readonly capacity: number }\n}\n\n/** What one dose taken out of a consumable did (`ItemControlsHost.takeDose`): how much came out, whether it was less than asked, and whether it is spent now. */\nexport interface ItemDose {\n readonly taken: number\n readonly short: boolean\n readonly empty: boolean\n}\n\n/**\n * What the body does to work a control (CLAUDE.md §18: every action has a body animation): the hand reaches the point and `press`es a button, `turn`s a knob or a tap's\n * handle, `flip`s a rocker or a lever, `strike`s a match at a burner, `pour`s what it holds over a bowl, `put_in` lets what it holds go inside a container, `tip`s a\n * container over to empty it, `stow`s the thing aimed at into the bag on the body, holds a paper up to the eyes to `read` it, or closes on a pull, a latch or a curtain's edge and\n * `pull`s it toward the body (a drawer, a cabinet's door, a gate, a curtain drawn).\n */\nexport type BodyGesture = 'press' | 'turn' | 'flip' | 'strike' | 'pour' | 'put_in' | 'tip' | 'stow' | 'read' | 'pull'\n\n/** Why a body cannot take a use's pose (`ControlledBody.blocked`): the object has no such seat, the object is not there, the body is busy with another. */\nexport type ControlBodyBlock = 'no_seat' | 'object_gone' | 'busy'\n\n/**\n * The body that uses an object (`ItemControlsHost.body`). The object decides and times what the body does for a use (`ControlBodyAction`): it asks `blocked` before\n * it answers the use is available, `begin` when it runs, `step` once a step with the time, and `end` when the seconds are over; the host moves and draws the body.\n */\nexport interface ControlledBody {\n readonly sex: 'male' | 'female'\n /** Why the body cannot take `action` now, or null when it can. */\n blocked(action: ControlBodyAction): ControlBodyBlock | null\n /** The body takes the action's pose: seated on its seat, or on its feet at its spot facing the object with the walk held. False when it could not. */\n begin(action: ControlBodyAction): boolean\n /** While it lasts: `time` seconds since it began and `progress` 0 to 1 of its length, for the host to draw the pose. False when the body has left it (got up, walked off). */\n step(time: number, progress: number): boolean\n /** Its seconds are over (or the object left the world): up from the seat at its exit, or the walk let go. */\n end(): void\n}\n\n/** Seconds of one push and pull of a plunger: the strokes the object counts (the clog it breaks) and the ones the body draws are the same. */\nexport const PLUNGE_STROKE_SECONDS = 0.8\n\n/** A loose thing of the world inside an object (`ItemControlsHost.looseInside`). */\nexport interface LooseThing {\n readonly id: string\n /** Width, height and depth, metres. */\n readonly size: Vec3Tuple\n readonly kg: number\n}\n\n/**\n * What the body does while a control runs (`ItemControlResult.body`), for the host to animate: `relieve_stand` stands at `at` facing `faces` (a man peeing in a\n * toilet), `relieve_sit` sits on the object's seat `seat` (peeing or pooing seated), `plunge` stands at `at` working a plunger in the bowl at `faces`.\n */\nexport interface ControlBodyAction {\n readonly pose: 'relieve_stand' | 'relieve_sit' | 'plunge'\n readonly seconds: number\n /** Object-local point under the feet (standing poses). */\n readonly at?: Vec3Tuple\n /** Object-local point the body faces. */\n readonly faces?: Vec3Tuple\n /** The object's seat the body sits on (`relieve_sit`). */\n readonly seat?: string\n}\n\n/** One control of an object as the host lists it. */\nexport interface ItemControl {\n readonly id: string\n /** What the body does to work it; with `at`, the host's body plays it and runs the control when the hand gets there. Absent: the host runs it at once. */\n readonly gesture?: BodyGesture\n /** Where the hand goes, object-local metres (the button, the knob, the inside of the bin). */\n readonly at?: Vec3Tuple\n /** Localized, the verb first (`Ligar a TV`, `Trocar de canal`). */\n readonly label: string\n /** False when it cannot be used now: the host still lists it, greyed, with `reason`. */\n readonly available: boolean\n /** Localized, why it cannot be used now. */\n readonly reason?: string\n}\n\n/** What running a control did, in words for the player. */\nexport interface ItemControlResult {\n readonly ok: boolean\n readonly text: string\n /** What the body does for it, which the host animates (CLAUDE.md §18). */\n readonly body?: ControlBodyAction\n}\n\n/** The controls of one object in the world (`TestableItem.controls`). */\nexport interface ItemControls {\n /** The controls the object offers now, in the order the menu shows them. */\n list(host: ItemControlsHost): readonly ItemControl[]\n run(id: string, host: ItemControlsHost): ItemControlResult\n /** Advances the object's own time (a program running, a fire burning, a flush) by `dt` seconds. */\n update(dt: number, host: ItemControlsHost): void\n /** Lets go of what the controls drew or kept; called when the object leaves the world. */\n dispose(): void\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/** A fixed box a module gives the host as the body of an obstacle (`ModuleHost.addBlocker`): centre and half sizes in the world, the turn as a quaternion (default none). */\nexport interface HostSolid {\n readonly center: readonly [number, number, number]\n readonly half: readonly [number, number, number]\n readonly rotation?: readonly [number, number, number, number]\n /** Names the box across calls (a box measured again is the same box): without it, the place in the list. */\n readonly key?: string\n}\n\n/**\n * The fixed box of `footprint` on `object`, `height` metres tall from the floor: the body of what `footprintBlocker` stops the player at. An object out of the scene (no parent) has no box.\n * The turn is read from the object's x and z columns (a turn about the vertical axis, as the blocker reads it).\n */\nexport function footprintSolid(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined), height: number): HostSolid[] {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return []\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n const sx = Math.hypot(e[0] as number, e[2] as number) || 1\n const sz = Math.hypot(e[8] as number, e[10] as number) || 1\n const angle = Math.atan2(-(e[2] as number), e[0] as number)\n const cx = (fp.minX + fp.maxX) / 2\n const cz = (fp.minZ + fp.maxZ) / 2\n const centreX = (e[12] as number) + cx * (e[0] as number) + cz * (e[8] as number)\n const centreZ = (e[14] as number) + cx * (e[2] as number) + cz * (e[10] as number)\n return [{ center: [centreX, height / 2, centreZ], half: [((fp.maxX - fp.minX) / 2) * sx, height / 2, ((fp.maxZ - fp.minZ) / 2) * sz], rotation: [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)] }]\n}\n","/** A world rectangle `[x0, z0, x1, z1]`, metres. */\nexport type RainCoverBounds = readonly [x0: number, z0: number, x1: number, z1: number]\n\n/**\n * Something with a roof or a slab over it (a house, a shed, a bus stop, a car): it says, for a point on the ground plan, how high the cover over it is.\n * The rain asks before it falls, splashes or wets the ground: under a cover there is none.\n */\nexport interface RainCoverSource {\n /** Where the source may cover anything; a point outside is never asked. */\n bounds(): RainCoverBounds\n /** Top (world y, metres) of the highest intact roof or slab over (x, z); `undefined` for open sky, or for a hole a blast or a collapse opened. */\n coverTopAt(x: number, z: number): number | undefined\n /** Grows whenever the covers change (a roof panel broke, a hole opened): whoever caches reads it. */\n version(): number\n}\n\n/** What the rain reads (`ModuleHost.rainCover`): every source of the host together. */\nexport interface RainCover {\n /** The highest cover over (x, z) among the sources, or `undefined` for open sky. */\n coverTopAt(x: number, z: number): number | undefined\n /** Changes whenever a source is added or removed or one of them changes. */\n version(): number\n /** True while there is no source: the rain skips the test. */\n isEmpty(): boolean\n /** Adds a source; returns the function that takes it away. */\n add(source: RainCoverSource): () => void\n}\n\nexport function createRainCover(): RainCover {\n const sources = new Set<RainCoverSource>()\n let list: RainCoverSource[] = []\n let membership = 0\n return {\n coverTopAt(x, z) {\n let top: number | undefined\n for (const source of list) {\n const [x0, z0, x1, z1] = source.bounds()\n if (x < x0 || x > x1 || z < z0 || z > z1) continue\n const value = source.coverTopAt(x, z)\n if (value !== undefined && (top === undefined || value > top)) top = value\n }\n return top\n },\n version() {\n let sum = membership\n for (const source of list) sum += source.version()\n return sum\n },\n isEmpty: () => list.length === 0,\n add(source) {\n sources.add(source)\n list = [...sources]\n membership++\n return () => {\n if (!sources.delete(source)) return\n list = [...sources]\n membership++\n }\n },\n }\n}\n\nexport type GridRainCoverOptions = {\n readonly bounds: RainCoverBounds\n /** Side of a cell, metres (default 0.25: a blast hole is bigger). */\n readonly cellSize?: number\n /** The exact answer at a cell centre; called again for every cell only after `invalidate`. */\n readonly coverTopAt: (x: number, z: number) => number | undefined\n}\n\nexport type GridRainCoverSource = RainCoverSource & {\n /** The covers changed (a roof panel broke): the grid is cut again on the next question, and `version` grows. */\n invalidate(): void\n}\n\nconst NO_COVER = -Infinity\n\n/** A source answered from a grid cut once from `coverTopAt`: a question is two array reads, however many panels the roof has. */\nexport function createGridRainCover(options: GridRainCoverOptions): GridRainCoverSource {\n const [x0, z0, x1, z1] = options.bounds\n const cell = options.cellSize ?? 0.25\n const columns = Math.max(1, Math.ceil((x1 - x0) / cell))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cell))\n const cells = new Float32Array(columns * rows)\n let revision = 0\n let isCut = false\n const cut = (): void => {\n for (let row = 0; row < rows; row++) {\n for (let column = 0; column < columns; column++) {\n const top = options.coverTopAt(x0 + (column + 0.5) * cell, z0 + (row + 0.5) * cell)\n cells[row * columns + column] = top === undefined ? NO_COVER : top\n }\n }\n isCut = true\n }\n return {\n bounds: () => options.bounds,\n coverTopAt(x, z) {\n if (!isCut) cut()\n const column = Math.floor((x - x0) / cell)\n const row = Math.floor((z - z0) / cell)\n if (column < 0 || row < 0 || column >= columns || row >= rows) return undefined\n const top = cells[row * columns + column]!\n return top === NO_COVER ? undefined : top\n },\n version: () => revision,\n invalidate() {\n isCut = false\n revision++\n },\n }\n}\n\n/** A roof or slab seen from above: the rectangle it covers and the height of its top. */\nexport type RainCoverRect = { readonly bounds: RainCoverBounds; readonly top: number }\n\n/** A round opening in a cover (a blast hole), centre and radius in the ground plan. */\nexport type RainCoverHole = { readonly x: number; readonly z: number; readonly radius: number }\n\n/** The exact answer for a list of rectangles with holes: the highest rectangle over the point whose hole does not take the point. */\nexport function rainCoverTopOf(rects: readonly RainCoverRect[], holes: readonly RainCoverHole[], x: number, z: number): number | undefined {\n let top: number | undefined\n for (const rect of rects) {\n if (x < rect.bounds[0] || x > rect.bounds[2] || z < rect.bounds[1] || z > rect.bounds[3]) continue\n if (top !== undefined && rect.top <= top) continue\n if (holes.some((hole) => (x - hole.x) ** 2 + (z - hole.z) ** 2 <= hole.radius ** 2)) continue\n top = rect.top\n }\n return top\n}\n\n/** A roof seen from above as a turned rectangle: its centre on the ground plan, half sides along its own axes, the turn about y and the height of its top. */\nexport type RainCoverFootprint = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly yaw: number; readonly top: number }\n\nexport type FootprintRainCoverSource = RainCoverSource & {\n /**\n * Puts the roofs and the openings where they are now (a car moved, a window broke). The answer follows at once; the version grows only with `bumpVersion`,\n * which a mover asks once it has gone far enough for whoever caches (the far curtain) to cut again.\n */\n set(footprints: readonly RainCoverFootprint[], openings: readonly RainCoverFootprint[], bumpVersion: boolean): void\n}\n\ntype Prepared = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly cos: number; readonly sin: number; readonly top: number }\n\nconst prepare = (f: RainCoverFootprint): Prepared => ({ x: f.x, z: f.z, halfX: f.halfX, halfZ: f.halfZ, cos: Math.cos(f.yaw), sin: Math.sin(f.yaw), top: f.top })\n\nconst insideTurned = (f: Prepared, x: number, z: number): boolean => {\n const dx = x - f.x\n const dz = z - f.z\n return Math.abs(dx * f.cos + dz * f.sin) <= f.halfX && Math.abs(-dx * f.sin + dz * f.cos) <= f.halfZ\n}\n\n/**\n * A source of turned rectangles with openings (a car's cabin, a tent, a kiosk): a question is a few multiplications per rectangle, no allocation, so the near rain\n * asks it for every drop. `set` moves the rectangles whenever the thing moves; nothing else is cut or cached.\n */\nexport function createFootprintRainCover(): FootprintRainCoverSource {\n let roofs: Prepared[] = []\n let openings: Prepared[] = []\n let bounds: RainCoverBounds = [0, 0, 0, 0]\n let revision = 0\n return {\n bounds: () => bounds,\n version: () => revision,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) {\n if ((top !== undefined && roof.top <= top) || !insideTurned(roof, x, z)) continue\n top = roof.top\n }\n if (top === undefined) return undefined\n for (const opening of openings) if (insideTurned(opening, x, z)) return undefined\n return top\n },\n set(footprints, cutouts, bumpVersion) {\n roofs = footprints.map(prepare)\n openings = cutouts.map(prepare)\n let x0 = Infinity\n let z0 = Infinity\n let x1 = -Infinity\n let z1 = -Infinity\n for (const roof of roofs) {\n const reach = Math.abs(roof.halfX * roof.cos) + Math.abs(roof.halfZ * roof.sin)\n const reachZ = Math.abs(roof.halfX * roof.sin) + Math.abs(roof.halfZ * roof.cos)\n x0 = Math.min(x0, roof.x - reach)\n x1 = Math.max(x1, roof.x + reach)\n z0 = Math.min(z0, roof.z - reachZ)\n z1 = Math.max(z1, roof.z + reachZ)\n }\n bounds = roofs.length === 0 ? [0, 0, 0, 0] : [x0, z0, x1, z1]\n if (bumpVersion) revision++\n },\n }\n}\n\n/** The most cells a fixed footprint cover cuts: a wide district gets a coarser cell instead of a bigger grid. */\nconst FIXED_COVER_MAX_CELLS = 1_000_000\n\n/** A source of turned rectangles that never move (the buildings of a district, a tent, a kiosk): answered from a grid cut once, two array reads a question however many roofs there are. */\nexport function createFixedFootprintRainCover(footprints: readonly RainCoverFootprint[], cellSize = 0.5): RainCoverSource {\n const roofs = footprints.map(prepare)\n if (roofs.length === 0) return { bounds: () => [0, 0, 0, 0], coverTopAt: () => undefined, version: () => 0 }\n const x0 = Math.min(...roofs.map((r) => r.x - Math.abs(r.halfX * r.cos) - Math.abs(r.halfZ * r.sin)))\n const x1 = Math.max(...roofs.map((r) => r.x + Math.abs(r.halfX * r.cos) + Math.abs(r.halfZ * r.sin)))\n const z0 = Math.min(...roofs.map((r) => r.z - Math.abs(r.halfX * r.sin) - Math.abs(r.halfZ * r.cos)))\n const z1 = Math.max(...roofs.map((r) => r.z + Math.abs(r.halfX * r.sin) + Math.abs(r.halfZ * r.cos)))\n const cell = Math.max(cellSize, Math.sqrt(((x1 - x0) * (z1 - z0)) / FIXED_COVER_MAX_CELLS))\n return createGridRainCover({\n bounds: [x0, z0, x1, z1],\n cellSize: cell,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) if ((top === undefined || roof.top > top) && insideTurned(roof, x, z)) top = roof.top\n return top\n },\n })\n}\n","/** What an obstacle on the ground is to a walker: a solid (a wall, a lot wall, a fence, a board) or a door (a door or a gate, which opens and can be broken). */\nexport const NAV_OBSTACLE_KIND = { SOLID: 'solid', DOOR: 'door' } as const\nexport type NavObstacleKind = (typeof NAV_OBSTACLE_KIND)[keyof typeof NAV_OBSTACLE_KIND]\n\n/** A box of an obstacle on the ground: world metres `[x0, z0, x1, z1]` and how high it stands over the ground (a low remnant of a wall can be climbed). */\nexport type NavObstacleBox = {\n readonly rect: readonly [number, number, number, number]\n readonly height: number\n}\n\n/**\n * One thing that stops a walker on the ground, as the SDK that builds it publishes it for a navigation grid (the crowd's): a whole wall is one box, a wall a blast\n * cut stands in the boxes of what is left of it, a wall that is gone has none. A door is one box, passable while `open`.\n */\nexport type NavObstacle = {\n /** Stable for the life of the source: a change names the same obstacle again. */\n readonly id: string\n readonly kind: NavObstacleKind\n readonly boxes: readonly NavObstacleBox[]\n /** A door or a gate that lets walkers through now (always false for a solid). */\n readonly open: boolean\n /** A door the barricade's boards cover, each making it harder to break (0 for none). */\n readonly boards: number\n}\n\n/**\n * The obstacles one or more SDKs put on the ground (the houses' walls, doors, lot walls and gates), for whoever keeps a navigation grid. Pulled once per fixed step, so a\n * grid that follows it changes at the same step on every run.\n */\nexport type NavObstacleSource = {\n /** Every obstacle as it stands now. */\n obstacles(): readonly NavObstacle[]\n /** The obstacles that changed since the last call (a door opened or closed, a wall cut or gone); empty when none did. */\n changes(): readonly NavObstacle[]\n /** A walker broke the door `id` open (the horde hit it until it gave way): the owner shows it open. */\n breakDoor(id: string): void\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 spring_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 VEHICLE_HULL_PLAN: 'vehicles.hull-plan',\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 [WORKER_KIND_ID.VEHICLE_HULL_PLAN]: { lane: 'build', priority: 120, late: 'keep-waiting' },\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 PartSolid,\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 { TNT_JOULES, 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, HandSeat, HandTargetSource, HandTargets, MuzzlePose, MuzzleSource, ToolHand } from './hands'\nexport { CARRY_HANDLE_TAG, 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, eulerFromQuat, leadClipEvents, quatFromEuler, sampleClip, scaleClip, slerpQuat, toolAnimationStep } from './tool-animation'\nexport type { ClipQuat, ClipSample, 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 { BodyGesture, ControlBodyAction, ControlBodyBlock, ControlledBody, ControlledHand, ItemControl, ItemControlResult, ItemControls, ItemControlsHost, ItemDose, ItemTool, LooseThing, ReachedItem } from './item-controls'\nexport { ITEM_TOOLS, PLUNGE_STROKE_SECONDS } from './item-controls'\nexport type { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleItemUse, ModuleItemWash, ModuleItemConsumable, ModuleScenario, PlayerState, ItemSeat, HostSeatHolder, HostSeatState, HostSeating, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostGesture, HostReach, HostTakenItem, HostTap } 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, footprintSolid } from './footprint'\nexport { createFixedFootprintRainCover, createFootprintRainCover, createGridRainCover, createRainCover, rainCoverTopOf } from './rain-cover'\nexport type { FootprintRainCoverSource, GridRainCoverOptions, GridRainCoverSource, RainCover, RainCoverBounds, RainCoverFootprint, RainCoverHole, RainCoverRect, RainCoverSource } from './rain-cover'\nexport type { UtilityConnection, UtilityNetwork } from './utility'\nexport type { Footprint, FootprintObject, HostSolid } from './footprint'\nexport { NAV_OBSTACLE_KIND } from './nav-obstacles'\nexport type { NavObstacle, NavObstacleBox, NavObstacleKind, NavObstacleSource } from './nav-obstacles'\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","import { WORKER_KIND_DEFAULTS, WORKER_LANES, WORKER_LATE_RULES } from '@adatechnology/game-contracts'\nimport type { ResidentKind, TaskKind, WorkerKindSchedule } from '@adatechnology/game-contracts'\n\nconst ID = /^[a-z0-9-]+(\\.[a-z0-9-]+)+$/\n\n/** Checks a schedule: a known lane and rule, `sync` on the `sim` lane (its result is read in a fixed frame), a whole latency >= 1. */\nexport function checkSchedule(id: string, schedule: WorkerKindSchedule): void {\n if (!WORKER_LANES.includes(schedule.lane)) throw new Error(`worker kind ${id}: unknown lane \"${schedule.lane}\"`)\n if (!WORKER_LATE_RULES.includes(schedule.late)) throw new Error(`worker kind ${id}: unknown late rule \"${schedule.late}\"`)\n if (schedule.lane === 'sim' && schedule.late !== 'sync') throw new Error(`worker kind ${id}: the sim lane needs late \"sync\" (its result is applied in a fixed frame)`)\n if (!Number.isFinite(schedule.priority)) throw new Error(`worker kind ${id}: priority must be a number`)\n const latency = schedule.latencyFrames ?? 1\n if (!Number.isInteger(latency) || latency < 1) throw new Error(`worker kind ${id}: latencyFrames must be a whole number >= 1`)\n}\n\nconst checkId = (id: string): void => {\n if (!ID.test(id)) throw new Error(`worker kind \"${id}\": the id is \"package.thing\" in lowercase (destruction.ground-tiles)`)\n}\n\n/** The schedule a kit kind declares by default, by id (`WORKER_KIND_DEFAULTS`); `undefined` for a game's own kind. */\nexport const kitScheduleOf = (id: string): WorkerKindSchedule | undefined => (WORKER_KIND_DEFAULTS as Readonly<Record<string, WorkerKindSchedule>>)[id]\n\n/**\n * A task kind, checked: the id, the lane and the late rule. The kit's kinds take their schedule from `WORKER_KIND_DEFAULTS`.\n *\n * ```ts\n * export const pathfinding = defineTaskKind<PathInput, PathOutput>({ id: 'mygame.pathfinding', lane: 'sim', priority: 180, latencyFrames: 2, late: 'sync', run: aStar })\n * ```\n */\nexport function defineTaskKind<In, Out>(kind: Omit<TaskKind<In, Out>, 'kind'>): TaskKind<In, Out> {\n checkId(kind.id)\n checkSchedule(kind.id, kind)\n if (kind.transferAwaitedInput && !kind.transferInput) throw new Error(`worker kind ${kind.id}: transferAwaitedInput needs transferInput (the buffers to transfer)`)\n return Object.freeze({ ...kind, kind: 'task' as const })\n}\n\n/** A resident kind, checked as `defineTaskKind`. */\nexport function defineResidentKind<Init, Step, Result>(kind: Omit<ResidentKind<Init, Step, Result>, 'kind'>): ResidentKind<Init, Step, Result> {\n checkId(kind.id)\n checkSchedule(kind.id, kind)\n return Object.freeze({ ...kind, kind: 'resident' as const })\n}\n","import type { WorkerLane } from '@adatechnology/game-contracts'\n\nexport interface LaneOptions {\n /** Workers of this lane (default: the automatic split). */\n readonly workers?: number\n /** `build` only: its idle workers take `sim` jobs (default true). */\n readonly borrow?: boolean\n}\n\nexport interface WorkerPlanOptions {\n /** `'auto'` (default): `cores - 1 - reserveCores`, at most `maxWorkers`. A number: exactly that many. 0: everything on the main thread. */\n readonly workers?: 'auto' | number\n /** Ceiling of the automatic count (default 8). */\n readonly maxWorkers?: number\n /** Cores others use (Jolt's job threads, an audio worklet): the automatic count leaves them free. */\n readonly reserveCores?: number\n readonly lanes?: Partial<Readonly<Record<WorkerLane, LaneOptions>>>\n}\n\nexport interface WorkerPlan {\n readonly total: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n /** For each worker, by index, the lane it belongs to. */\n readonly homes: readonly WorkerLane[]\n /** For each worker, by index, the lanes it takes jobs from, in order (a `build` worker takes `sim` jobs first: they have a deadline). */\n readonly serves: readonly (readonly WorkerLane[])[]\n}\n\nexport const DEFAULT_MAX_WORKERS = 8\n\n/** The cores of this machine, or 1 where the runtime does not say. */\nexport function hardwareCores(): number {\n const n = (globalThis as { navigator?: { hardwareConcurrency?: number } }).navigator?.hardwareConcurrency\n return typeof n === 'number' && n > 0 ? n : 1\n}\n\nconst whole = (n: number): number => Math.max(0, Math.floor(n))\n\n/**\n * How many workers and which lanes each one serves. Automatic: `cores - 1 - reserveCores` workers (the main thread keeps a core), at most\n * `maxWorkers`; the `sim` lane takes a third rounded up (1 to 3), `background` gets its own worker from 6 on, `build` the rest. One worker\n * serves every lane. A `build` worker takes `sim` jobs first (they have a deadline), then its own, then `background` when that lane has\n * none of its own; a `background` worker never takes `sim` jobs, so the far world never delays a frame.\n */\nexport function planWorkers(options: WorkerPlanOptions = {}, cores = hardwareCores()): WorkerPlan {\n const max = whole(options.maxWorkers ?? DEFAULT_MAX_WORKERS)\n const asked = options.workers ?? 'auto'\n const total = asked === 'auto' ? Math.min(max, whole(cores - 1 - (options.reserveCores ?? 0))) : whole(asked)\n const fixed = options.lanes ?? {}\n let sim: number\n let background: number\n if (total <= 1) {\n sim = total\n background = 0\n } else {\n sim = Math.min(3, Math.max(1, Math.ceil(total / 3)))\n background = total >= 6 ? 1 : 0\n }\n if (fixed.sim?.workers !== undefined) sim = whole(fixed.sim.workers)\n if (fixed.background?.workers !== undefined) background = whole(fixed.background.workers)\n let build = fixed.build?.workers !== undefined ? whole(fixed.build.workers) : Math.max(0, total - sim - background)\n // lanes given by hand win over the total; the automatic split never goes over it\n if (fixed.sim?.workers === undefined && fixed.build?.workers === undefined && fixed.background?.workers === undefined) build = total - sim - background\n const count = sim + build + background\n const borrow = fixed.build?.borrow !== false\n const serves: WorkerLane[][] = []\n for (let i = 0; i < sim; i++) serves.push(['sim', ...(build === 0 ? (['build'] as const) : []), ...(build === 0 && background === 0 ? (['background'] as const) : [])])\n for (let i = 0; i < build; i++) serves.push([...(borrow ? (['sim'] as const) : []), 'build', ...(background === 0 ? (['background'] as const) : [])])\n for (let i = 0; i < background; i++) serves.push(['background'])\n const homes: WorkerLane[] = [...Array<WorkerLane>(sim).fill('sim'), ...Array<WorkerLane>(build).fill('build'), ...Array<WorkerLane>(background).fill('background')]\n return { total: count, lanes: { sim, build, background }, homes, serves }\n}\n","/** Messages between the coordinator and a worker host. One protocol for browser workers, `worker_threads` and the in-thread host. */\n\nexport type ToWorker =\n | { readonly t: 'hello'; readonly id: number }\n | { readonly t: 'task'; readonly id: number; readonly kind: string; readonly input: unknown }\n | { readonly t: 'create'; readonly rid: number; readonly kind: string; readonly init: unknown }\n | { readonly t: 'step'; readonly id: number; readonly rid: number; readonly input: unknown }\n | { readonly t: 'dispose'; readonly rid: number }\n\nexport type FromWorker =\n | { readonly t: 'hello'; readonly id: number; readonly kinds: readonly string[] }\n | { readonly t: 'done'; readonly id: number; readonly ok: true; readonly output: unknown; readonly ms: number }\n | { readonly t: 'done'; readonly id: number; readonly ok: false; readonly error: string; readonly ms: number }\n\n/** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, the in-thread host. */\nexport interface WorkerLike {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void\n terminate(): void\n}\n\n/** The worker side: `self` in a browser worker, `parentPort` in Node (through `nodeWorkerScope`), or the in-thread host. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null\n postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void\n}\n\n/** Makes one worker that runs `installWorkerHost` with the kinds the coordinator is asked for. */\nexport type Spawn = () => WorkerLike\n\nexport const isFromWorker = (data: unknown): data is FromWorker => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\nexport const isToWorker = (data: unknown): data is ToWorker => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\n","import { WORKER_INPUT_LOST, WORKER_LANES } from '@adatechnology/game-contracts'\nimport type {\n AnyWorkerKind,\n ResidentHandle,\n ResidentInstance,\n ResidentKind,\n TaskHandle,\n TaskKind,\n WorkerCoordinator,\n WorkerCoordinatorStats,\n WorkerKindSchedule,\n WorkerKindStats,\n WorkerLane,\n WorkerLateRule,\n WorkerResultSource,\n} from '@adatechnology/game-contracts'\nimport { checkSchedule } from './define'\nimport { planWorkers } from './plan'\nimport type { WorkerPlan, WorkerPlanOptions } from './plan'\nimport { isFromWorker } from './protocol'\nimport type { Spawn, ToWorker, WorkerLike } from './protocol'\n\n/** Jobs a worker holds at once unless `CoordinatorOptions.inFlightPerWorker` says otherwise (room measurement, spec 009 T7). */\nexport const IN_FLIGHT_PER_WORKER = 16\n\nexport interface CoordinatorOptions extends WorkerPlanOptions {\n /** Makes one worker (`browserSpawn`, `sourceSpawn`, `nodeSpawn`, `inThreadSpawn`). Without it every job runs on the main thread. */\n readonly spawn?: Spawn\n /** The game's overrides of a kind's schedule, by kind id. */\n readonly kinds?: Readonly<Record<string, Partial<WorkerKindSchedule>>>\n /**\n * Jobs a worker holds at once (default `IN_FLIGHT_PER_WORKER`, 16): the rest wait in the coordinator's queue, where a more urgent one can pass them. A job only leaves that\n * queue when the main thread reads a worker's answer, which on a busy frame is once per frame: a burst (a blast asks for dozens of ground tiles at once) with a small cap\n * needs several frames of round trips and misses its due frame. Measured in the room (crater, 4 threads): 2 left 139 of 163 tiles late, 16 none.\n */\n readonly inFlightPerWorker?: number\n /** The machine's cores for the automatic count (default `navigator.hardwareConcurrency`). */\n readonly cores?: number\n /** Clock in milliseconds (default `performance.now`). */\n readonly now?: () => number\n}\n\n/** The promise of a job given up by `late: 'drop'` rejects with it. */\nexport class WorkerTaskDropped extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind} dropped: no worker took it`)\n this.name = 'WorkerTaskDropped'\n }\n}\n\n/** The promise of a cancelled job rejects with it. */\nexport class WorkerTaskCancelled extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind} cancelled`)\n this.name = 'WorkerTaskCancelled'\n }\n}\n\n/**\n * The promise of an awaited job whose input was transferred (`transferAwaitedInput`) rejects with it when its worker died holding it: the input went with the worker, so the\n * coordinator cannot run it here; the caller makes it from its own copy (`isWorkerInputLost`). A worker that answers with an error rejects with that error instead.\n */\nexport class WorkerTaskInputLost extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind}: its worker died holding its transferred input`)\n this.name = WORKER_INPUT_LOST\n }\n}\n\ntype JobState = 'queued' | 'running' | 'done' | 'settled' | 'cancelled'\n\ntype KindCounters = { -readonly [K in keyof WorkerKindStats]: WorkerKindStats[K] }\n\ninterface Resident {\n readonly rid: number\n readonly kind: ResidentKind<unknown, unknown, unknown>\n readonly schedule: WorkerKindSchedule\n readonly init: unknown\n slot: Slot | null\n local: ResidentInstance<unknown, unknown> | null\n disposed: boolean\n}\n\ninterface Job {\n readonly id: number\n readonly seq: number\n readonly kindId: string\n readonly counters: KindCounters\n readonly lane: WorkerLane\n readonly priority: number\n readonly late: WorkerLateRule\n readonly dueFrame: number\n readonly message: ToWorker\n readonly transfer: readonly ArrayBuffer[]\n /** A `sync` job whose input is transferred (`transferAwaitedInput`): once sent, it cannot run here nor be sent again. */\n readonly moved: boolean\n readonly runHere: () => unknown\n readonly resident: Resident | null\n readonly queuedAt: number\n state: JobState\n /** Workers that died holding it: a job that keeps killing its worker runs here (or fails) instead of killing the next one. */\n crashes: number\n output: unknown\n error: Error | null\n source: WorkerResultSource | null\n slot: Slot | null\n readonly settle: { resolve: (value: unknown) => void; reject: (error: Error) => void }\n readonly promise: Promise<unknown>\n}\n\ninterface Slot {\n readonly index: number\n readonly home: WorkerLane\n readonly serves: readonly WorkerLane[]\n worker: WorkerLike\n readonly running: Map<number, Job>\n /** Steps of the residents pinned here, in order. */\n readonly own: Job[]\n readonly residents: Set<Resident>\n readonly hello: Map<number, (kinds: readonly string[]) => void>\n alive: boolean\n}\n\nconst MAX_CRASHES = 2\nconst MAX_RESPAWNS = 5\n\nconst defaultNow = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/** Higher priority first, then the nearest due frame, then the order of submission. */\nconst before = (a: Job, b: Job): boolean => a.priority > b.priority || (a.priority === b.priority && (a.dueFrame < b.dueFrame || (a.dueFrame === b.dueFrame && a.seq < b.seq)))\n\nconst insertSorted = (queue: Job[], job: Job): void => {\n let i = queue.length\n while (i > 0 && before(job, queue[i - 1]!)) i--\n queue.splice(i, 0, job)\n}\n\n/**\n * The coordinator of every worker of a game (see the `game-workers` README). `sim` jobs are applied in a fixed frame: `collect(dueFrame)`\n * gives the worker's answer when it is back and runs the same kernel here when it is not, so the result never depends on timing. The main\n * thread never waits for a worker.\n */\nexport function createWorkerCoordinator(options: CoordinatorOptions = {}): WorkerCoordinator & { readonly plan: WorkerPlan } {\n const now = options.now ?? defaultNow\n const perWorker = Math.max(1, Math.floor(options.inFlightPerWorker ?? IN_FLIGHT_PER_WORKER))\n const overrides = options.kinds ?? {}\n const plan: WorkerPlan = options.spawn ? planWorkers(options, options.cores) : { total: 0, lanes: { sim: 0, build: 0, background: 0 }, homes: [], serves: [] }\n const queues: Record<WorkerLane, Job[]> = { sim: [], build: [], background: [] }\n const mainQueue: Job[] = []\n const counters = new Map<string, KindCounters>()\n const residents = new Set<Resident>()\n const slots: Slot[] = []\n let frame = 0\n let nextId = 1\n let nextRid = 1\n let respawned = 0\n const deathsAt = new Map<number, number>()\n let disposed = false\n let mainTimer: ReturnType<typeof setTimeout> | null = null\n\n const countersOf = (kind: AnyWorkerKind, lane: WorkerLane): KindCounters => {\n let c = counters.get(kind.id)\n if (!c) counters.set(kind.id, (c = { id: kind.id, lane, submitted: 0, answered: 0, onTime: 0, fallback: 0, dropped: 0, cancelled: 0, failed: 0, workerMs: 0, mainMs: 0, queueMs: 0 }))\n return c\n }\n\n const scheduleOf = (kind: AnyWorkerKind): WorkerKindSchedule => {\n const own = overrides[kind.id]\n if (!own) return kind\n const merged: WorkerKindSchedule = { lane: own.lane ?? kind.lane, priority: own.priority ?? kind.priority, latencyFrames: own.latencyFrames ?? kind.latencyFrames, late: own.late ?? kind.late }\n checkSchedule(kind.id, merged)\n return merged\n }\n\n // ── workers ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n const makeSlot = (index: number, home: WorkerLane, serves: readonly WorkerLane[]): Slot | null => {\n let worker: WorkerLike\n try {\n worker = (options.spawn as Spawn)()\n } catch {\n return null\n }\n const slot: Slot = { index, home, serves, worker, running: new Map(), own: [], residents: new Set(), hello: new Map(), alive: true }\n worker.onmessage = (event) => onReply(slot, event.data)\n worker.onerror = () => onCrash(slot)\n return slot\n }\n\n for (let i = 0; i < plan.serves.length; i++) {\n const slot = makeSlot(i, plan.homes[i]!, plan.serves[i]!)\n if (slot) slots.push(slot)\n }\n const served = (lane: WorkerLane): boolean => slots.some((slot) => slot.serves.includes(lane))\n const homeOf = (lane: WorkerLane): Slot | null => {\n let best: Slot | null = null\n for (const slot of slots) {\n if (!slot.alive || !slot.serves.includes(lane)) continue\n const own = slot.home === lane ? 0 : 1\n const bestOwn = best && best.home === lane ? 0 : 1\n if (!best || own < bestOwn || (own === bestOwn && slot.residents.size < best.residents.size)) best = slot\n }\n return best\n }\n\n const send = (slot: Slot, job: Job): void => {\n job.state = 'running'\n job.slot = slot\n job.counters.queueMs += now() - job.queuedAt\n slot.running.set(job.id, job)\n try {\n slot.worker.postMessage(job.message, job.transfer)\n } catch (error) {\n // a message that cannot be posted (an input that does not clone) is not the caller's synchronous throw: a sync job runs here (nothing was transferred), any other fails\n slot.running.delete(job.id)\n job.slot = null\n job.counters.failed++\n if (job.late === 'sync') runOnMain(job)\n else fail(job, error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n const dispatch = (): void => {\n if (disposed) return\n for (const slot of slots) {\n while (slot.alive && slot.running.size < perWorker) {\n let job = slot.own.shift()\n if (!job) for (const lane of slot.serves) if ((job = queues[lane].shift())) break\n if (!job) break\n send(slot, job)\n }\n }\n }\n\n const onReply = (slot: Slot, data: unknown): void => {\n if (!isFromWorker(data)) return\n if (data.t === 'hello') {\n slot.hello.get(data.id)?.(data.kinds)\n slot.hello.delete(data.id)\n return\n }\n const job = slot.running.get(data.id)\n if (!job) return\n slot.running.delete(data.id)\n job.counters.workerMs += data.ms\n job.counters.answered++\n if (job.state === 'running') {\n if (data.ok) {\n job.state = 'done'\n job.output = data.output\n job.source = 'worker'\n // a job with no frame to wait for is on time as soon as it is back\n if (job.lane !== 'sim' && !job.resident) finish(job)\n else job.settle.resolve(job.output)\n } else {\n job.counters.failed++\n // a transferred input cannot run here: the worker's own error (the kernel threw, or the worker does not host the kind)\n if (job.late === 'sync' && !job.moved) runOnMain(job)\n else fail(job, new Error(data.error))\n }\n }\n dispatch()\n }\n\n const onCrash = (slot: Slot): void => {\n if (!slot.alive) return\n slot.alive = false\n slot.worker.terminate()\n const deaths = (deathsAt.get(slot.index) ?? 0) + 1\n deathsAt.set(slot.index, deaths)\n // a worker that keeps dying (a script that does not load) is not replaced forever: its lanes fall back to the others, or the main thread\n const replacement = disposed || deaths > MAX_RESPAWNS ? null : makeSlot(slot.index, slot.home, slot.serves)\n if (replacement) {\n respawned++\n slots[slots.indexOf(slot)] = replacement\n } else slots.splice(slots.indexOf(slot), 1)\n for (const resident of slot.residents) {\n resident.slot = replacement\n if (replacement) {\n replacement.residents.add(resident)\n replacement.worker.postMessage({ t: 'create', rid: resident.rid, kind: resident.kind.id, init: resident.init } satisfies ToWorker)\n }\n }\n // what the dead worker held goes back in line, steps of a resident first and in their order\n const waiting = [...slot.own]\n const back = [...slot.running.values()].filter((job) => job.state === 'running').sort((a, b) => a.seq - b.seq)\n slot.own.length = 0\n for (const job of back) job.crashes++\n for (const job of [...back, ...waiting]) {\n job.state = 'queued'\n job.slot = null\n if (job.crashes >= MAX_CRASHES || job.moved) {\n job.counters.failed++\n if (job.moved) fail(job, new WorkerTaskInputLost(job.kindId))\n else if (job.late === 'sync') runOnMain(job)\n else fail(job, new Error(`${job.kindId}: its worker died ${job.crashes} times running it`))\n } else if (job.resident) {\n if (replacement) replacement.own.push(job)\n // no worker for it any more: it is run here when it is collected\n } else if (served(job.lane)) insertSorted(queues[job.lane], job)\n else toMain(job)\n }\n dispatch()\n }\n\n // ── results ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n const finish = (job: Job): void => {\n if (job.source === 'worker') job.counters.onTime++\n job.state = 'settled'\n job.settle.resolve(job.output)\n }\n const fail = (job: Job, error: Error): void => {\n job.state = 'settled'\n job.error = error\n job.settle.reject(error)\n }\n const unqueue = (job: Job): void => {\n for (const queue of [queues[job.lane], mainQueue, job.resident?.slot?.own ?? []]) {\n const at = queue.indexOf(job)\n if (at >= 0) queue.splice(at, 1)\n }\n }\n /** The kernel here, now: a late worker, a crash, or no worker. A running job's answer is thrown away when it comes. */\n const runOnMain = (job: Job): void => {\n unqueue(job)\n const started = now()\n try {\n job.output = job.runHere()\n job.source = 'main'\n job.counters.fallback++\n job.counters.mainMs += now() - started\n finish(job)\n } catch (error) {\n job.counters.mainMs += now() - started\n fail(job, error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n const drainMain = (): void => {\n mainTimer = null\n const job = mainQueue.shift()\n if (job && job.state === 'queued') runOnMain(job)\n if (mainQueue.length && !disposed) mainTimer = setTimeout(drainMain, 0)\n }\n /** A `build` or `background` job no worker can take: dropped, or run here one per macrotask, by priority. */\n const toMain = (job: Job): void => {\n if (job.late === 'drop') {\n job.counters.dropped++\n fail(job, new WorkerTaskDropped(job.kindId))\n return\n }\n insertSorted(mainQueue, job)\n if (!mainTimer) mainTimer = setTimeout(drainMain, 0)\n }\n\n // ── jobs ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n interface JobSpec {\n readonly kind: AnyWorkerKind\n readonly schedule: WorkerKindSchedule\n readonly dueFrame: number\n readonly message: (id: number) => ToWorker\n readonly transfer: readonly ArrayBuffer[]\n readonly moved?: boolean\n readonly runHere: () => unknown\n readonly resident: Resident | null\n }\n const makeJob = (spec: JobSpec): Job => {\n let settle: Job['settle'] = { resolve: () => undefined, reject: () => undefined }\n const promise = new Promise<unknown>((resolve, reject) => (settle = { resolve, reject }))\n // a job read only through `collect` must not leave an unhandled rejection behind\n promise.catch(() => undefined)\n const id = nextId++\n const job: Job = {\n id,\n seq: id,\n kindId: spec.kind.id,\n counters: countersOf(spec.kind, spec.schedule.lane),\n lane: spec.schedule.lane,\n priority: spec.schedule.priority,\n late: spec.schedule.late,\n dueFrame: spec.dueFrame,\n message: spec.message(id),\n transfer: spec.transfer,\n moved: spec.moved ?? false,\n runHere: spec.runHere,\n resident: spec.resident,\n queuedAt: now(),\n state: 'queued',\n crashes: 0,\n output: undefined,\n error: null,\n source: null,\n slot: null,\n settle,\n promise,\n }\n job.counters.submitted++\n return job\n }\n\n const handleOf = <Out>(job: Job): TaskHandle<Out> => ({\n dueFrame: job.dueFrame,\n promise: job.promise as Promise<Out>,\n get source() {\n return job.source\n },\n collect(at: number): Out {\n if (at < job.dueFrame) throw new Error(`${job.kindId}: collected in frame ${at}, before its due frame ${job.dueFrame}`)\n if (job.state === 'cancelled') throw new WorkerTaskCancelled(job.kindId)\n if (job.state === 'done') finish(job)\n else if (job.state === 'queued' || job.state === 'running') runOnMain(job)\n if (job.error) throw job.error\n return job.output as Out\n },\n cancel(): void {\n if (job.state !== 'queued' && job.state !== 'running') return\n unqueue(job)\n job.state = 'cancelled'\n job.counters.cancelled++\n job.settle.reject(new WorkerTaskCancelled(job.kindId))\n },\n })\n\n const enqueue = (job: Job): void => {\n if (disposed) throw new Error('worker coordinator: disposed')\n if (job.resident) {\n if (job.resident.slot) job.resident.slot.own.push(job)\n // a resident with no worker runs here, at its collect\n } else if (served(job.lane)) insertSorted(queues[job.lane], job)\n else if (job.lane !== 'sim') toMain(job)\n // a sim job no worker serves waits for its collect, where it runs here\n dispatch()\n }\n\n const latencyOf = (schedule: WorkerKindSchedule, at?: { readonly latencyFrames?: number }): number => Math.max(1, Math.floor(at?.latencyFrames ?? schedule.latencyFrames ?? 1))\n\n const taskJob = <In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }, awaited = false): Job => {\n const schedule = scheduleOf(kind as TaskKind<unknown, unknown>)\n const submitted = at?.frame ?? frame\n const moved = schedule.late === 'sync' && awaited && kind.transferAwaitedInput === true && kind.transferInput !== undefined\n const job = makeJob({\n kind: kind as TaskKind<unknown, unknown>,\n schedule,\n dueFrame: schedule.lane === 'sim' ? submitted + latencyOf(schedule, at) : Number.POSITIVE_INFINITY,\n message: (id) => ({ t: 'task', id, kind: kind.id, input }),\n transfer: schedule.late === 'sync' && !moved ? [] : [...(kind.transferInput?.(input) ?? [])],\n moved,\n runHere: () => kind.run(input),\n resident: null,\n })\n return job\n }\n\n const coordinator: WorkerCoordinator & { readonly plan: WorkerPlan } = {\n plan,\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out> {\n const job = taskJob(kind, input, at)\n enqueue(job)\n return handleOf<Out>(job)\n },\n\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out> {\n const job = taskJob(kind, input, undefined, true)\n enqueue(job)\n // nobody collects an awaited job: a `sim` kind with no worker to serve it runs here, as the other lanes do (the simulation thread awaits its jobs)\n if (job.lane === 'sim' && job.state === 'queued' && !served('sim')) toMain(job)\n const handle = handleOf<Out>(job)\n if (signal) {\n if (signal.aborted) handle.cancel()\n else signal.addEventListener('abort', () => handle.cancel(), { once: true })\n }\n return handle.promise\n },\n\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result> {\n const any = kind as unknown as ResidentKind<unknown, unknown, unknown>\n const schedule = scheduleOf(any)\n const resident: Resident = { rid: nextRid++, kind: any, schedule, init, slot: homeOf(schedule.lane), local: null, disposed: false }\n residents.add(resident)\n resident.slot?.residents.add(resident)\n resident.slot?.worker.postMessage({ t: 'create', rid: resident.rid, kind: kind.id, init } satisfies ToWorker)\n const local = (): ResidentInstance<unknown, unknown> => (resident.local ??= any.create(init))\n return {\n id: kind.id,\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result> {\n if (resident.disposed) throw new Error(`${kind.id}: resident disposed`)\n const submitted = at?.frame ?? frame\n const job = makeJob({\n kind: any,\n schedule,\n dueFrame: submitted + latencyOf(schedule, at),\n message: (id) => ({ t: 'step', id, rid: resident.rid, input }),\n transfer: schedule.late === 'sync' ? [] : [...(kind.transferInput?.(input) ?? [])],\n runHere: () => local().step(input),\n resident,\n })\n enqueue(job)\n return handleOf<Result>(job)\n },\n dispose(): void {\n if (resident.disposed) return\n resident.disposed = true\n residents.delete(resident)\n resident.slot?.residents.delete(resident)\n if (resident.slot?.alive) resident.slot.worker.postMessage({ t: 'dispose', rid: resident.rid } satisfies ToWorker)\n resident.local?.dispose?.()\n },\n }\n },\n\n tick(at: number): void {\n frame = at\n dispatch()\n },\n\n async warm(kinds: readonly AnyWorkerKind[]): Promise<void> {\n for (const kind of kinds) scheduleOf(kind)\n await Promise.all(\n slots.map(async (slot) => {\n const id = nextId++\n const known = await new Promise<readonly string[]>((resolve) => {\n slot.hello.set(id, resolve)\n slot.worker.postMessage({ t: 'hello', id } satisfies ToWorker)\n })\n const missing = kinds.filter((kind) => !known.includes(kind.id)).map((kind) => kind.id)\n if (missing.length) throw new Error(`worker ${slot.index} does not know ${missing.join(', ')}: add them to its installWorkerHost`)\n }),\n )\n // each worker runs each warm-up once, straight to it (the queue would give them all to the first free worker)\n const warmups: Promise<unknown>[] = []\n for (const kind of kinds) {\n if (kind.kind !== 'task' || kind.warmup === undefined) continue\n for (const slot of slots) {\n const job = makeJob({ kind, schedule: scheduleOf(kind), dueFrame: Number.NEGATIVE_INFINITY, message: (id) => ({ t: 'task', id, kind: kind.id, input: kind.warmup }), transfer: [], runHere: () => kind.run(kind.warmup), resident: null })\n job.counters.submitted--\n send(slot, job)\n warmups.push(job.promise.catch(() => undefined))\n }\n }\n await Promise.all(warmups)\n },\n\n scheduleOf,\n\n stats(): WorkerCoordinatorStats {\n let running = 0\n for (const slot of slots) running += slot.running.size\n const lanes = { sim: 0, build: 0, background: 0 }\n for (const slot of slots) lanes[slot.home]++\n return {\n workers: slots.length,\n lanes,\n queued: WORKER_LANES.reduce((n, lane) => n + queues[lane].length, 0) + mainQueue.length + slots.reduce((n, slot) => n + slot.own.length, 0),\n running,\n respawned,\n kinds: [...counters.values()].map((c) => ({ ...c })),\n }\n },\n\n dispose(): void {\n if (disposed) return\n disposed = true\n if (mainTimer) clearTimeout(mainTimer)\n const pending = [...WORKER_LANES.flatMap((lane) => queues[lane]), ...mainQueue, ...slots.flatMap((slot) => [...slot.own, ...slot.running.values()])]\n for (const job of pending) if (job.state === 'queued' || job.state === 'running') fail(job, new Error('worker coordinator: disposed'))\n for (const slot of slots) {\n slot.alive = false\n slot.worker.terminate()\n }\n for (const resident of residents) resident.local?.dispose?.()\n residents.clear()\n slots.length = 0\n },\n }\n return coordinator\n}\n","import type { AnyResidentKind, AnyWorkerKind, ResidentInstance } from '@adatechnology/game-contracts'\nimport { isToWorker } from './protocol'\nimport type { FromWorker, WorkerScopeLike } from './protocol'\n\nconst now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/**\n * The worker side of the coordinator: answers each job with the kind's own `run` (or the resident instance's `step`) and transfers the\n * output's buffers back. Call it in the file the worker loads, with every kind the game registers, the kit's and its own:\n *\n * ```ts\n * // game-worker.ts\n * import { installWorkerHost } from '@adatechnology/game-workers'\n * installWorkerHost(self, [...KIT_WORKER_KINDS, pathfinding])\n * ```\n */\nexport function installWorkerHost(scope: WorkerScopeLike, kinds: readonly AnyWorkerKind[]): void {\n const byId = new Map<string, AnyWorkerKind>()\n for (const kind of kinds) {\n if (byId.has(kind.id) && byId.get(kind.id) !== kind) throw new Error(`installWorkerHost: two kinds with the id ${kind.id}`)\n byId.set(kind.id, kind)\n }\n const residents = new Map<number, { kind: AnyResidentKind; instance: ResidentInstance<unknown, unknown> }>()\n const reply = (message: FromWorker, transfer: readonly ArrayBuffer[] = []): void => scope.postMessage(message, transfer)\n const fail = (id: number, error: unknown, started: number): void => reply({ t: 'done', id, ok: false, error: error instanceof Error ? error.message : String(error), ms: now() - started })\n\n scope.onmessage = (event) => {\n const message = event.data\n if (!isToWorker(message)) return\n switch (message.t) {\n case 'hello':\n reply({ t: 'hello', id: message.id, kinds: [...byId.keys()] })\n return\n case 'task': {\n const started = now()\n const kind = byId.get(message.kind)\n if (!kind || kind.kind !== 'task') return fail(message.id, new Error(`this worker has no task kind ${message.kind}`), started)\n try {\n const output = kind.run(message.input)\n reply({ t: 'done', id: message.id, ok: true, output, ms: now() - started }, kind.transferOutput?.(output) ?? [])\n } catch (error) {\n fail(message.id, error, started)\n }\n return\n }\n case 'create': {\n const kind = byId.get(message.kind)\n // an unknown kind answers at its first step, where there is a job id to fail\n if (kind?.kind === 'resident') residents.set(message.rid, { kind, instance: kind.create(message.init) })\n return\n }\n case 'step': {\n const started = now()\n const resident = residents.get(message.rid)\n if (!resident) return fail(message.id, new Error(`this worker has no resident ${message.rid}`), started)\n try {\n const output = resident.instance.step(message.input)\n reply({ t: 'done', id: message.id, ok: true, output, ms: now() - started }, resident.kind.transferOutput?.(output) ?? [])\n } catch (error) {\n fail(message.id, error, started)\n }\n return\n }\n case 'dispose':\n residents.get(message.rid)?.instance.dispose?.()\n residents.delete(message.rid)\n return\n }\n }\n}\n","import type { AnyWorkerKind } from '@adatechnology/game-contracts'\nimport { installWorkerHost } from './host'\nimport type { Spawn, WorkerLike, WorkerScopeLike } from './protocol'\n\nexport interface InThreadOptions {\n /** Milliseconds before each answer reaches the coordinator (default 0: the next macrotask), to play a slow worker in tests. */\n readonly delayMs?: number\n}\n\n/**\n * A worker that runs `installWorkerHost` in this thread and answers on a later macrotask, as a real one does: the same protocol, the same\n * copy of the input (`structuredClone`) and the same transfer of the output. For tests, and the reference of `checkTaskKind`.\n */\nexport function inThreadSpawn(kinds: readonly AnyWorkerKind[], options: InThreadOptions = {}): Spawn {\n return () => {\n let alive = true\n const worker: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage(message, transfer = []) {\n const copy: unknown = structuredClone(message, { transfer: [...transfer] })\n setTimeout(() => alive && scope.onmessage?.({ data: copy }), 0)\n },\n terminate() {\n alive = false\n },\n }\n const scope: WorkerScopeLike = {\n onmessage: null,\n postMessage(message, transfer = []) {\n const copy: unknown = structuredClone(message, { transfer: [...transfer] })\n setTimeout(() => alive && worker.onmessage?.({ data: copy }), options.delayMs ?? 0)\n },\n }\n installWorkerHost(scope, kinds)\n return worker\n }\n}\n","import type { AnyWorkerKind, TaskKind } from '@adatechnology/game-contracts'\nimport { createWorkerCoordinator } from './coordinator'\nimport { inThreadSpawn } from './in-thread'\nimport type { Spawn } from './protocol'\n\nexport interface KindReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nconst bytesOf = (view: ArrayBufferView): Uint8Array => new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n\n/** Where two values differ, byte for byte in typed arrays (`-0`, `NaN` payloads included); `null` when they are the same. */\nexport function firstDifference(a: unknown, b: unknown, path = 'output'): string | null {\n if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {\n if (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b) || a.constructor !== b.constructor) return `${path}: not the same kind of array`\n const x = bytesOf(a)\n const y = bytesOf(b)\n if (x.length !== y.length) return `${path}: ${x.length} bytes against ${y.length}`\n for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return `${path}: byte ${i} differs`\n return null\n }\n if (a instanceof ArrayBuffer || b instanceof ArrayBuffer) {\n if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) return `${path}: not both ArrayBuffers`\n return firstDifference(new Uint8Array(a), new Uint8Array(b), path)\n }\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return Object.is(a, b) ? null : `${path}: ${String(a)} against ${String(b)}`\n if (Array.isArray(a) !== Array.isArray(b)) return `${path}: an array against an object`\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of keys) {\n const difference = firstDifference((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], `${path}.${key}`)\n if (difference) return difference\n }\n return null\n}\n\n/**\n * The equivalence test every kind passes (CLAUDE.md §14): each sample run on the main thread, through the in-thread worker (the protocol,\n * the copy and the transfer) and through each `spawn` given (a real `worker_threads` worker in CI), and the outputs compared byte for byte.\n * `extraKinds`: the other kinds the given workers host.\n */\nexport async function checkTaskKind<In, Out>(kind: TaskKind<In, Out>, samples: readonly In[], spawns: readonly Spawn[] = [], extraKinds: readonly AnyWorkerKind[] = []): Promise<KindReport> {\n const problems: string[] = []\n const any = kind as TaskKind<unknown, unknown>\n const paths: { name: string; spawn: Spawn }[] = [{ name: 'in-thread worker', spawn: inThreadSpawn([any, ...extraKinds]) }, ...spawns.map((spawn, i) => ({ name: `worker ${i + 1}`, spawn }))]\n for (const path of paths) {\n const coordinator = createWorkerCoordinator({ spawn: path.spawn, workers: 1 })\n try {\n await coordinator.warm([any])\n for (let i = 0; i < samples.length; i++) {\n const reference = kind.run(structuredClone(samples[i]) as In)\n const handle = coordinator.submit(kind, structuredClone(samples[i]) as In, { frame: 0 })\n const out = await handle.promise\n if (handle.source !== 'worker') problems.push(`${kind.id} sample ${i}: ${path.name} did not answer (${handle.source ?? 'no result'})`)\n const difference = firstDifference(reference, out)\n if (difference) problems.push(`${kind.id} sample ${i}, ${path.name}: ${difference}`)\n // an awaited job of a kind that transfers its input goes another way: checked too\n if (kind.transferAwaitedInput) {\n const awaited = firstDifference(reference, await coordinator.run(kind, structuredClone(samples[i]) as In))\n if (awaited) problems.push(`${kind.id} sample ${i}, ${path.name}, awaited: ${awaited}`)\n }\n }\n } catch (error) {\n problems.push(`${kind.id}, ${path.name}: ${error instanceof Error ? error.message : String(error)}`)\n } finally {\n coordinator.dispose()\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","import type { Spawn, WorkerLike } from './protocol'\n\ninterface BrowserWorker {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer: Transferable[]): void\n terminate(): void\n}\ntype WorkerConstructor = new (url: string | URL, options?: { type?: 'module' | 'classic'; name?: string }) => BrowserWorker\n\nconst workerConstructor = (): WorkerConstructor | null => (globalThis as { Worker?: WorkerConstructor }).Worker ?? null\n\n/** Whether this runtime has browser workers. */\nexport const canSpawnBrowserWorkers = (): boolean => workerConstructor() !== null\n\nconst wrap = (worker: BrowserWorker): WorkerLike => {\n const like: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage: (message, transfer = []) => worker.postMessage(message, [...transfer]),\n terminate: () => worker.terminate(),\n }\n worker.onmessage = (event) => like.onmessage?.(event)\n worker.onerror = (event) => like.onerror?.(event)\n return like\n}\n\n/**\n * Module workers that load `url`, the file that calls `installWorkerHost` (a bundler resolves `new URL('./game-worker.js', import.meta.url)`).\n * Throws where there is no `Worker`; the coordinator then runs every job on the main thread.\n */\nexport function browserSpawn(url: string | URL, options: { readonly type?: 'module' | 'classic'; readonly name?: string } = {}): Spawn {\n return () => {\n const Ctor = workerConstructor()\n if (!Ctor) throw new Error('browserSpawn: no Worker in this runtime')\n return wrap(new Ctor(url, { type: options.type ?? 'module', ...(options.name ? { name: options.name } : {}) }))\n }\n}\n\n/**\n * Workers made from the worker's own source text, for a page that is one file (no worker file beside it to load): the build embeds the\n * bundle of the worker as a string and this makes a Blob URL of it once.\n */\nexport function sourceSpawn(source: string, options: { readonly type?: 'module' | 'classic'; readonly name?: string } = {}): Spawn {\n let url: string | null = null\n return () => {\n if (!url) {\n if (typeof Blob === 'undefined' || typeof URL.createObjectURL !== 'function') throw new Error('sourceSpawn: no Blob URLs in this runtime')\n url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }))\n }\n return browserSpawn(url, options)()\n }\n}\n","/**\n * Memory the main thread and the simulation thread share, with no lock and no wait on the main thread (it may not wait in a browser or in\n * the Electron renderer): a triple buffer of snapshots (the simulation writes, the page reads the newest whole one) and a ring of commands\n * (the page writes input, the simulation drains it at the start of a step). One writer and one reader each.\n */\n\nconst HEADER_BYTES = 32\nconst SLOTS = 3\n// header Int32 words of the snapshot buffer\nconst PUBLISHED = 0 // slot + 1 of the newest whole snapshot, 0 before the first\nconst CLAIMED = 1 // slot + 1 the reader is reading, 0 none\nconst FRAME = 2 // frame of each slot (3 words)\n\nconst align8 = (n: number): number => Math.ceil(n / 8) * 8\n\n/** Whether this runtime shares memory between threads: `SharedArrayBuffer` and, in a page, cross-origin isolation (COOP/COEP; always in Electron). */\nexport function canShareMemory(): boolean {\n if (typeof SharedArrayBuffer === 'undefined' || typeof Atomics === 'undefined') return false\n const isolated = (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated\n return isolated !== false\n}\n\n/** A buffer of three snapshots of `bytes` each. */\nexport function createSnapshotBuffer(bytes: number): SharedArrayBuffer {\n return new SharedArrayBuffer(HEADER_BYTES + SLOTS * align8(bytes))\n}\n\nconst slotBytes = (buffer: SharedArrayBuffer): number => (buffer.byteLength - HEADER_BYTES) / SLOTS\n\n/** One snapshot as the reader sees it: valid until its next `latest()`, which may hand the slot back to the writer. */\nexport interface Snapshot {\n readonly frame: number\n readonly buffer: SharedArrayBuffer\n readonly byteOffset: number\n readonly byteLength: number\n readonly bytes: Uint8Array\n}\n\n/** The writer's side (the simulation thread): `begin` a free slot, fill it, `commit` it with its frame. Never waits. */\nexport class SnapshotWriter {\n private readonly header: Int32Array\n private readonly views: Uint8Array[]\n private slot = -1\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4)\n const size = slotBytes(buffer)\n this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * size, size))\n }\n /** A slot neither published nor being read: there is always one of the three. */\n begin(): Uint8Array {\n const published = Atomics.load(this.header, PUBLISHED) - 1\n const claimed = Atomics.load(this.header, CLAIMED) - 1\n let slot = 0\n while (slot === published || slot === claimed) slot++\n this.slot = slot\n return this.views[slot]!\n }\n commit(frame: number): void {\n if (this.slot < 0) throw new Error('SnapshotWriter.commit: no begin')\n Atomics.store(this.header, FRAME + this.slot, frame)\n Atomics.store(this.header, PUBLISHED, this.slot + 1)\n this.slot = -1\n }\n}\n\n/** The reader's side (the page): the newest whole snapshot, or `null` before the first. Never waits; retries only when a commit lands mid-claim. */\nexport class SnapshotReader {\n private readonly header: Int32Array\n private readonly size: number\n private readonly views: Uint8Array[]\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4)\n this.size = slotBytes(buffer)\n this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * this.size, this.size))\n }\n latest(): Snapshot | null {\n for (;;) {\n const published = Atomics.load(this.header, PUBLISHED)\n if (published === 0) return null\n Atomics.store(this.header, CLAIMED, published)\n // the writer only skips the claimed slot from its next begin on: the claim holds when the slot is still the newest after it\n if (Atomics.load(this.header, PUBLISHED) !== published) continue\n const slot = published - 1\n return {\n frame: Atomics.load(this.header, FRAME + slot),\n buffer: this.buffer,\n byteOffset: HEADER_BYTES + slot * this.size,\n byteLength: this.size,\n bytes: this.views[slot]!,\n }\n }\n }\n /** Lets the writer take the slot of the last snapshot (the reader is done with it). */\n release(): void {\n Atomics.store(this.header, CLAIMED, 0)\n }\n}\n\nconst RING_HEADER_BYTES = 8 // Int32: written, read\n\n/** A ring of `capacity` commands of `width` numbers each. */\nexport function createCommandBuffer(width: number, capacity: number): SharedArrayBuffer {\n if (!Number.isInteger(width) || width < 1 || !Number.isInteger(capacity) || capacity < 1) throw new Error('createCommandBuffer: width and capacity are integers >= 1')\n const buffer = new SharedArrayBuffer(RING_HEADER_BYTES + 8 + width * capacity * 8)\n // the layout is read back from the buffer: width in the slot after the header\n new Float64Array(buffer, RING_HEADER_BYTES, 1)[0] = width\n return buffer\n}\n\n/** Both ends of the ring: the page `push`es, the simulation `drain`s; a full ring refuses the command (`false`) rather than waiting. */\nexport class CommandRing {\n private readonly header: Int32Array\n private readonly data: Float64Array\n readonly width: number\n readonly capacity: number\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, 2)\n this.width = new Float64Array(buffer, RING_HEADER_BYTES, 1)[0]!\n this.data = new Float64Array(buffer, RING_HEADER_BYTES + 8)\n this.capacity = this.data.length / this.width\n }\n push(command: ArrayLike<number>): boolean {\n if (command.length > this.width) throw new Error(`CommandRing.push: ${command.length} numbers, the ring holds ${this.width}`)\n const written = Atomics.load(this.header, 0)\n if (written - Atomics.load(this.header, 1) >= this.capacity) return false\n const at = (written % this.capacity) * this.width\n this.data.fill(0, at, at + this.width)\n for (let k = 0; k < command.length; k++) this.data[at + k] = command[k]!\n Atomics.store(this.header, 0, written + 1)\n return true\n }\n /** Every command pushed so far, oldest first, each a copy. */\n drain(): Float64Array[] {\n const written = Atomics.load(this.header, 0)\n const read = Atomics.load(this.header, 1)\n const out: Float64Array[] = []\n for (let k = read; k < written; k++) {\n const at = (k % this.capacity) * this.width\n out.push(this.data.slice(at, at + this.width))\n }\n Atomics.store(this.header, 1, written)\n return out\n }\n}\n","import { CommandRing, SnapshotReader, SnapshotWriter, canShareMemory, createCommandBuffer, createSnapshotBuffer } from './shared'\nimport type { Snapshot } from './shared'\nimport type { AnySimModule, SimInstance, SimModule } from '@adatechnology/game-contracts'\nimport type { Spawn, WorkerScopeLike } from './protocol'\n\n/**\n * The simulation thread (spec 009, T22): the whole fixed step of a game runs in one dedicated worker, which **may wait** (for the jobs it\n * hands to other workers, for its next step), as the main thread of a native engine's simulation does. The page only pushes input into a\n * command ring and draws the newest whole snapshot, so it never waits, in a browser or in the Electron renderer.\n *\n * The same module also runs on the calling thread (`runSimInline`): the snapshot bytes are the same after the same steps and commands, which\n * is what the equivalence test checks.\n */\n\nexport interface SimLoopOptions {\n /** Seconds of one fixed step (default 1/60). */\n readonly stepSeconds?: number\n /** Stop after this many steps (tests, a replay); default: run until `stop`. */\n readonly steps?: number\n /** Steps on the clock (default) or as fast as they compute (`false`: tests, a server). */\n readonly paced?: boolean\n /** Steps the loop catches up after a stall before it drops the time instead (default 4). */\n readonly maxCatchUp?: number\n}\n\nexport interface SimThreadOptions<Init> extends SimLoopOptions {\n readonly module: string\n readonly init: Init\n /** Bytes of one snapshot. */\n readonly snapshotBytes: number\n /** Numbers in one command (default 8) and commands the ring holds (default 256). */\n readonly commandWidth?: number\n readonly commandCapacity?: number\n}\n\nexport interface SimThreadStats {\n /** Steps done. */\n readonly steps: number\n readonly lastStepMs: number\n readonly meanStepMs: number\n readonly maxStepMs: number\n /** Stalls the loop gave up catching up on. */\n readonly dropped: number\n}\n\n/** The page's side of a running simulation thread. */\nexport interface SimThread {\n /** Resolves when the module is built and the first step is about to run; rejects when the thread could not build it. */\n readonly ready: Promise<void>\n /** Resolves with the steps done when the loop ends (`steps` reached or `stop`). */\n readonly done: Promise<number>\n /** The newest whole snapshot (never waits), `null` before the first. Valid until the next `latest`. */\n latest(): Snapshot | null\n /** Queues a command for the start of the next step; `false` when the ring is full. */\n send(command: ArrayLike<number>): boolean\n stats(): SimThreadStats\n /** Ends the loop after the step it is in. */\n stop(): void\n /** Stops and terminates the worker. */\n dispose(): void\n}\n\n// control buffer: Int32 words, then Float64 numbers from byte 32\nconst STOP = 0\nconst STEPS = 1\nconst WAKE = 2\nconst DROPPED = 3\nconst LAST_MS = 0\nconst SUM_MS = 1\nconst MAX_MS = 2\nconst CONTROL_BYTES = 64\n\ntype ToSim = {\n readonly t: 'sim-start'\n readonly module: string\n readonly init: unknown\n readonly snapshot: SharedArrayBuffer\n readonly commands: SharedArrayBuffer\n readonly control: SharedArrayBuffer\n readonly loop: SimLoopOptions\n}\ntype FromSim = { readonly t: 'sim-ready' } | { readonly t: 'sim-done'; readonly steps: number } | { readonly t: 'sim-error'; readonly error: string }\n\nconst now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\nconst message = (error: unknown): string => (error instanceof Error ? error.message : String(error))\nconst isThenable = (value: unknown): value is PromiseLike<void> => typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function'\n\ninterface LoopIo {\n readonly ring: CommandRing\n readonly writer: SnapshotWriter\n readonly control: SharedArrayBuffer\n /** A real sleep: `Atomics.wait` in a worker; never called with `paced: false`. */\n readonly sleep: (ms: number) => void\n /** Called before each step's drain (the inline runner pushes that frame's commands). */\n readonly beforeStep?: (frame: number) => void\n}\n\n/** The fixed-step loop, the same in the simulation thread and inline: drain commands, step (awaited), write the snapshot, sleep to the next step. */\nasync function simLoop(instance: SimInstance, options: SimLoopOptions, io: LoopIo): Promise<number> {\n const stepSeconds = options.stepSeconds ?? 1 / 60\n const stepMs = stepSeconds * 1000\n const paced = options.paced ?? true\n const maxCatchUp = options.maxCatchUp ?? 4\n const words = new Int32Array(io.control, 0, 8)\n const numbers = new Float64Array(io.control, 32, 4)\n let frame = 0\n let next = now()\n while (Atomics.load(words, STOP) === 0 && (options.steps === undefined || frame < options.steps)) {\n if (paced) {\n const wait = next - now()\n if (wait > 0.25) {\n io.sleep(wait)\n continue\n }\n if (-wait > maxCatchUp * stepMs) {\n next = now()\n Atomics.add(words, DROPPED, 1)\n }\n }\n io.beforeStep?.(frame)\n const commands = io.ring.drain()\n const started = now()\n const stepped = instance.step(frame, stepSeconds, commands)\n if (isThenable(stepped)) await stepped\n instance.write(io.writer.begin(), frame)\n io.writer.commit(frame)\n const ms = now() - started\n numbers[LAST_MS] = ms\n numbers[SUM_MS] = numbers[SUM_MS]! + ms\n if (ms > numbers[MAX_MS]!) numbers[MAX_MS] = ms\n frame++\n Atomics.store(words, STEPS, frame)\n next += stepMs\n }\n return frame\n}\n\nconst statsOf = (control: SharedArrayBuffer): SimThreadStats => {\n const words = new Int32Array(control, 0, 8)\n const numbers = new Float64Array(control, 32, 4)\n const steps = Atomics.load(words, STEPS)\n return { steps, lastStepMs: numbers[LAST_MS]!, meanStepMs: steps ? numbers[SUM_MS]! / steps : 0, maxStepMs: numbers[MAX_MS]!, dropped: Atomics.load(words, DROPPED) }\n}\n\nconst isToSim = (data: unknown): data is ToSim => typeof data === 'object' && data !== null && (data as { t?: unknown }).t === 'sim-start'\nconst isFromSim = (data: unknown): data is FromSim => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\n\n/**\n * The simulation thread's side: call it in the file of the simulation worker with every module the game may start.\n *\n * ```ts\n * // sim-worker.ts\n * import { installSimThread } from '@adatechnology/game-workers'\n * installSimThread(self, [hordeSim])\n * ```\n */\nexport function installSimThread(scope: WorkerScopeLike, modules: readonly AnySimModule[]): void {\n const byId = new Map(modules.map((m) => [m.id, m]))\n scope.onmessage = (event) => {\n const start = event.data\n if (!isToSim(start)) return\n const reply = (m: FromSim): void => scope.postMessage(m)\n const module = byId.get(start.module)\n if (!module) {\n reply({ t: 'sim-error', error: `installSimThread: no module ${start.module} (this thread has ${[...byId.keys()].join(', ') || 'none'})` })\n return\n }\n const words = new Int32Array(start.control, 0, 8)\n const io: LoopIo = {\n ring: new CommandRing(start.commands),\n writer: new SnapshotWriter(start.snapshot),\n control: start.control,\n // a worker may wait: this is the native engine's sleep, woken early by `stop`\n sleep: (ms) => void Atomics.wait(words, WAKE, 0, ms),\n }\n void (async () => {\n let instance: SimInstance | null = null\n try {\n instance = await module.create(start.init)\n reply({ t: 'sim-ready' })\n reply({ t: 'sim-done', steps: await simLoop(instance, start.loop, io) })\n } catch (error) {\n reply({ t: 'sim-error', error: message(error) })\n } finally {\n instance?.dispose?.()\n }\n })()\n }\n}\n\n/** Whether a simulation thread can run here: shared memory (`canShareMemory`) and workers to spawn. */\nexport const canRunSimThread = (): boolean => canShareMemory()\n\n/** Starts `options.module` in a new worker from `spawn` (a worker that calls `installSimThread`). Throws where memory cannot be shared. */\nexport function startSimThread<Init>(spawn: Spawn, options: SimThreadOptions<Init>): SimThread {\n if (!canShareMemory()) throw new Error('startSimThread: no shared memory here (SharedArrayBuffer and cross-origin isolation: COOP/COEP, always on in Electron)')\n const snapshot = createSnapshotBuffer(options.snapshotBytes)\n const commands = createCommandBuffer(options.commandWidth ?? 8, options.commandCapacity ?? 256)\n const control = new SharedArrayBuffer(CONTROL_BYTES)\n const words = new Int32Array(control, 0, 8)\n const reader = new SnapshotReader(snapshot)\n const ring = new CommandRing(commands)\n const worker = spawn()\n let readyResolve!: () => void\n let readyReject!: (error: Error) => void\n let doneResolve!: (steps: number) => void\n let doneReject!: (error: Error) => void\n const ready = new Promise<void>((resolve, reject) => ((readyResolve = resolve), (readyReject = reject)))\n const done = new Promise<number>((resolve, reject) => ((doneResolve = resolve), (doneReject = reject)))\n // a caller that awaits only `ready` sees the failure there: `done`'s copy of it is not an unhandled rejection\n done.catch(() => {})\n const fail = (error: Error): void => {\n readyReject(error)\n doneReject(error)\n }\n worker.onmessage = (event) => {\n const data = event.data\n if (!isFromSim(data)) return\n if (data.t === 'sim-ready') readyResolve()\n else if (data.t === 'sim-done') doneResolve(data.steps)\n else fail(new Error(data.error))\n }\n worker.onerror = (event) => fail(event instanceof Error ? event : new Error(`simulation thread failed: ${message((event as { message?: unknown }).message ?? event)}`))\n const loop: SimLoopOptions = {\n ...(options.stepSeconds !== undefined ? { stepSeconds: options.stepSeconds } : {}),\n ...(options.steps !== undefined ? { steps: options.steps } : {}),\n ...(options.paced !== undefined ? { paced: options.paced } : {}),\n ...(options.maxCatchUp !== undefined ? { maxCatchUp: options.maxCatchUp } : {}),\n }\n const start: ToSim = { t: 'sim-start', module: options.module, init: options.init, snapshot, commands, control, loop }\n worker.postMessage(start)\n const stop = (): void => {\n Atomics.store(words, STOP, 1)\n Atomics.notify(words, WAKE)\n }\n return {\n ready,\n done,\n latest: () => reader.latest(),\n send: (command) => ring.push(command),\n stats: () => statsOf(control),\n stop,\n dispose: () => {\n stop()\n worker.terminate()\n },\n }\n}\n\n/**\n * The same module and loop on this thread, unpaced: the snapshot after `steps` steps, with `commands[frame]` pushed before that step. The\n * reference the simulation thread must match byte for byte, and the fallback where memory cannot be shared.\n */\nexport async function runSimInline<Init>(\n module: SimModule<Init>,\n init: Init,\n options: { readonly steps: number; readonly snapshotBytes: number; readonly stepSeconds?: number; readonly commands?: readonly (readonly ArrayLike<number>[])[]; readonly commandWidth?: number },\n): Promise<Uint8Array> {\n const snapshot = createSnapshotBuffer(options.snapshotBytes)\n const control = new SharedArrayBuffer(CONTROL_BYTES)\n const ring = new CommandRing(createCommandBuffer(options.commandWidth ?? 8, 4096))\n const instance = await module.create(init)\n try {\n await simLoop(instance, { steps: options.steps, paced: false, ...(options.stepSeconds !== undefined ? { stepSeconds: options.stepSeconds } : {}) }, {\n ring,\n writer: new SnapshotWriter(snapshot),\n control,\n sleep: () => {},\n beforeStep: (frame) => {\n for (const command of options.commands?.[frame] ?? []) if (!ring.push(command)) throw new Error('runSimInline: more commands in one frame than the ring holds')\n },\n })\n } finally {\n instance.dispose?.()\n }\n return new SnapshotReader(snapshot).latest()!.bytes.slice()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,MAAM,wBAAiE,EAAE,UAAU,KAAK,MAAM,MAAM,UAAU,KAAK,aAAa,OAAO,IAAO;AKVrJ,MAAM,gCAAgC,OAAO;AYmCtC,MAAM,oBAAoB;IAC/B,oBAAoB;IACpB,cAAc;IACd,YAAY;IACZ,cAAc;IACd,gBAAgB;IAChB,iBAAiB;IACjB,YAAY;IACZ,mBAAmB;IACnB,eAAe;IACf,cAAc;IACd,sBAAsB;IACtB,yBAAyB;IACzB,oBAAoB;IACpB,oBAAoB;EACtB;AAGO,MAAM,oBAAoB;IAC/B,CAAC,kBAAkB,kBAAkB,GAAG,EAAE,UAAU,KAAK,OAAO,UAAU;;IAE1E,CAAC,kBAAkB,UAAU,GAAG,EAAE,UAAU,KAAK,OAAO,WAAW,gBAAgB,EAAE;IACrF,CAAC,kBAAkB,YAAY,GAAG,EAAE,UAAU,KAAK,OAAO,WAAW,gBAAgB,EAAE;IACvF,CAAC,kBAAkB,YAAY,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,WAAW,EAAE;IAC/E,CAAC,kBAAkB,eAAe,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,gBAAgB,EAAE;IACvF,CAAC,kBAAkB,UAAU,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,gBAAgB,EAAE;IAClF,CAAC,kBAAkB,cAAc,G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